repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/main_test.go
main_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "bytes" "encoding/json" "fmt" "io" "io/fs" "log" "net/http" "os" "path/filepath" "regexp" "runtime" "strconv" "strings" "testing" "time" "github.com/bep/helpers/envhelpers" "github.com/gohugoio/hugo/commands" "github.com/rogpeppe/go-internal/testscript" ) func TestCommands(t *testing.T) { // These are somewhat flakey and takes some time, // so usefule to have a way to skip them when developing. const skipEnv = "HUGOTESTING_SKIP_COMMANDS" if os.Getenv(skipEnv) != "" { t.Skipf("skip because %s set in env", skipEnv) } p := commonTestScriptsParam p.Dir = "testscripts/commands" testscript.Run(t, p) } // Tests in development can be put in "testscripts/unfinished". // Also see the watch_testscripts.sh script. func TestUnfinished(t *testing.T) { if os.Getenv("CI") != "" { t.Skip("skip unfinished tests on CI") } p := commonTestScriptsParam p.Dir = "testscripts/unfinished" // p.UpdateScripts = true // p.TestWork = true testscript.Run(t, p) } func TestMain(m *testing.M) { testscript.Main(m, map[string]func(){ // The main program. "hugo": func() { err := commands.Execute(os.Args[1:]) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }, }) } var commonTestScriptsParam = testscript.Params{ Setup: func(env *testscript.Env) error { return testSetupFunc()(env) }, Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){ // log prints to stderr. "log": func(ts *testscript.TestScript, neg bool, args []string) { log.Println(args) }, // dostounix converts \r\n to \n. "dostounix": func(ts *testscript.TestScript, neg bool, args []string) { filename := ts.MkAbs(args[0]) b, err := os.ReadFile(filename) if err != nil { ts.Fatalf("%v", err) } b = bytes.Replace(b, []byte("\r\n"), []byte{'\n'}, -1) if err := os.WriteFile(filename, b, 0o666); err != nil { ts.Fatalf("%v", err) } }, // cat prints a file to stdout. "cat": func(ts *testscript.TestScript, neg bool, args []string) { filename := ts.MkAbs(args[0]) b, err := os.ReadFile(filename) if err != nil { ts.Fatalf("%v", err) } fmt.Print(string(b)) }, // sleep sleeps for a second. "sleep": func(ts *testscript.TestScript, neg bool, args []string) { i := 1 if len(args) > 0 { var err error i, err = strconv.Atoi(args[0]) if err != nil { i = 1 } } time.Sleep(time.Duration(i) * time.Second) }, // tree lists a directory recursively to stdout as a simple tree. "tree": func(ts *testscript.TestScript, neg bool, args []string) { dirname := ts.MkAbs(args[0]) err := filepath.WalkDir(dirname, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } rel, err := filepath.Rel(dirname, path) if err != nil { return err } if rel == "." { fmt.Fprintln(ts.Stdout(), ".") return nil } depth := strings.Count(rel, string(os.PathSeparator)) prefix := strings.Repeat(" ", depth) + "└─" if d.IsDir() { fmt.Fprintf(ts.Stdout(), "%s%s/\n", prefix, d.Name()) } else { fmt.Fprintf(ts.Stdout(), "%s%s\n", prefix, d.Name()) } return nil }) if err != nil { ts.Fatalf("%v", err) } }, // ls lists a directory to stdout. "ls": func(ts *testscript.TestScript, neg bool, args []string) { dirname := ts.MkAbs(args[0]) dir, err := os.Open(dirname) if err != nil { ts.Fatalf("%v", err) } fis, err := dir.Readdir(-1) if err != nil { ts.Fatalf("%v", err) } if len(fis) == 0 { // To simplify empty dir checks. fmt.Fprintln(ts.Stdout(), "Empty dir") return } for _, fi := range fis { fmt.Fprintf(ts.Stdout(), "%s %04o %s %s\n", fi.Mode(), fi.Mode().Perm(), fi.ModTime().Format(time.RFC3339), fi.Name()) } }, // lsr lists a directory recursively to stdout. "lsr": func(ts *testscript.TestScript, neg bool, args []string) { dirname := ts.MkAbs(args[0]) err := filepath.WalkDir(dirname, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return nil } fi, err := d.Info() if err != nil { return err } rel, err := filepath.Rel(dirname, path) if err != nil { return err } fmt.Fprintf(ts.Stdout(), "%s %04o %s\n", fi.Mode(), fi.Mode().Perm(), filepath.ToSlash(rel)) return nil }) if err != nil { ts.Fatalf("%v", err) } }, // append appends to a file with a leading newline. "append": func(ts *testscript.TestScript, neg bool, args []string) { if len(args) < 2 { ts.Fatalf("usage: append FILE TEXT") } filename := ts.MkAbs(args[0]) words := args[1:] for i, word := range words { words[i] = strings.Trim(word, "\"") } text := strings.Join(words, " ") _, err := os.Stat(filename) if err != nil { if os.IsNotExist(err) { ts.Fatalf("file does not exist: %s", filename) } ts.Fatalf("failed to stat file: %v", err) } f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0o644) if err != nil { ts.Fatalf("failed to open file: %v", err) } defer f.Close() _, err = f.WriteString("\n" + text) if err != nil { ts.Fatalf("failed to write to file: %v", err) } }, // replace replaces a string in a file. "replace": func(ts *testscript.TestScript, neg bool, args []string) { if len(args) < 3 { ts.Fatalf("usage: replace FILE OLD NEW") } filename := ts.MkAbs(args[0]) oldContent, err := os.ReadFile(filename) if err != nil { ts.Fatalf("failed to read file %v", err) } newContent := bytes.Replace(oldContent, []byte(args[1]), []byte(args[2]), -1) err = os.WriteFile(filename, newContent, 0o644) if err != nil { ts.Fatalf("failed to write file: %v", err) } }, // httpget checks that a HTTP resource's body matches (if it compiles as a regexp) or contains all of the strings given as arguments. "httpget": func(ts *testscript.TestScript, neg bool, args []string) { if len(args) < 2 { ts.Fatalf("usage: httpget URL STRING...") } tryget := func() error { resp, err := http.Get(args[0]) if err != nil { return fmt.Errorf("failed to get URL %q: %v", args[0], err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("failed to read response body: %v", err) } for _, s := range args[1:] { re, err := regexp.Compile(s) if err == nil { ok := re.Match(body) if ok != !neg { return fmt.Errorf("response body %q for URL %q does not match %q", body, args[0], s) } } else { ok := bytes.Contains(body, []byte(s)) if ok != !neg { return fmt.Errorf("response body %q for URL %q does not contain %q", body, args[0], s) } } } return nil } // The timing on server rebuilds can be a little tricky to get right, // so we try again a few times until the server is ready. // There may be smarter ways to do this, but this works. start := time.Now() for { time.Sleep(200 * time.Millisecond) err := tryget() if err == nil { return } if time.Since(start) > 6*time.Second { ts.Fatalf("timeout waiting for %q: %v", args[0], err) } } }, // checkfile checks that a file exists and is not empty. "checkfile": func(ts *testscript.TestScript, neg bool, args []string) { var readonly, exec bool loop: for len(args) > 0 { switch args[0] { case "-readonly": readonly = true args = args[1:] case "-exec": exec = true args = args[1:] default: break loop } } if len(args) == 0 { ts.Fatalf("usage: checkfile [-readonly] [-exec] file...") } for _, filename := range args { filename = ts.MkAbs(filename) fi, err := os.Stat(filename) ok := err == nil != neg if !ok { ts.Fatalf("stat %s: %v", filename, err) } if fi.Size() == 0 { ts.Fatalf("%s is empty", filename) } if readonly && fi.Mode()&0o222 != 0 { ts.Fatalf("%s is writable", filename) } if exec && runtime.GOOS != "windows" && fi.Mode()&0o111 == 0 { ts.Fatalf("%s is not executable", filename) } } }, // checkfilecount checks that the number of files in a directory is equal to the given count. "checkfilecount": func(ts *testscript.TestScript, neg bool, args []string) { if len(args) != 2 { ts.Fatalf("usage: checkfilecount count dir") } count, err := strconv.Atoi(args[0]) if err != nil { ts.Fatalf("invalid count: %v", err) } if count < 0 { ts.Fatalf("count must be non-negative") } dir := args[1] dir = ts.MkAbs(dir) found := 0 filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return nil } found++ return nil }) ok := found == count != neg if !ok { ts.Fatalf("found %d files, want %d", found, count) } }, // waitServer waits for the .ready file to be created by the server. "waitServer": func(ts *testscript.TestScript, neg bool, args []string) { type testInfo struct { BaseURLs []string } // The server will write a .ready file when ready. // We wait for that. readyFilename := ts.MkAbs(".ready") limit := time.Now().Add(10 * time.Second) for { _, err := os.Stat(readyFilename) if err != nil { time.Sleep(500 * time.Millisecond) if time.Now().After(limit) { ts.Fatalf("timeout waiting for .ready file") } continue } var info testInfo // Read the .ready file's JSON into info. f, err := os.Open(readyFilename) if err != nil { ts.Fatalf("failed to open .ready file: %v", err) } err = json.NewDecoder(f).Decode(&info) if err != nil { ts.Fatalf("error decoding json: %v", err) } f.Close() for i, s := range info.BaseURLs { ts.Setenv(fmt.Sprintf("HUGOTEST_BASEURL_%d", i), s) } return } }, "stopServer": func(ts *testscript.TestScript, neg bool, args []string) { baseURL := ts.Getenv("HUGOTEST_BASEURL_0") if baseURL == "" { ts.Fatalf("HUGOTEST_BASEURL_0 not set") } if !strings.HasSuffix(baseURL, "/") { baseURL += "/" } resp, err := http.Head(baseURL + "__stop") if err != nil { ts.Fatalf("failed to shutdown server: %v", err) } resp.Body.Close() // Allow some time for the server to shut down. time.Sleep(2 * time.Second) }, }, } func testSetupFunc() func(env *testscript.Env) error { sourceDir, _ := os.Getwd() return func(env *testscript.Env) error { var keyVals []string keyVals = append(keyVals, "HUGO_TESTRUN", "true") keyVals = append(keyVals, "HUGO_CACHEDIR", filepath.Join(env.WorkDir, "hugocache")) xdghome := filepath.Join(env.WorkDir, "xdgcachehome") keyVals = append(keyVals, "XDG_CACHE_HOME", xdghome) home := filepath.Join(env.WorkDir, "home") keyVals = append(keyVals, "HOME", home) if runtime.GOOS == "darwin" { if err := os.MkdirAll(filepath.Join(home, "Library", "Caches"), 0o777); err != nil { return err } } if runtime.GOOS == "linux" { if err := os.MkdirAll(xdghome, 0o777); err != nil { return err } } keyVals = append(keyVals, "SOURCE", sourceDir) goVersion := runtime.Version() goVersion = strings.TrimPrefix(goVersion, "go") if strings.HasPrefix(goVersion, "1.20") { // Strip patch version. goVersion = goVersion[:strings.LastIndex(goVersion, ".")] } keyVals = append(keyVals, "GOVERSION", goVersion) envhelpers.SetEnvVars(&env.Vars, keyVals...) return nil } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/main_withdeploy_off_test.go
main_withdeploy_off_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !withdeploy package main import ( "testing" "github.com/rogpeppe/go-internal/testscript" ) func TestWithdeploy(t *testing.T) { p := commonTestScriptsParam p.Dir = "testscripts/withdeploy-off" testscript.Run(t, p) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/magefile.go
magefile.go
//go:build mage package main import ( "bytes" "cmp" "fmt" "os" "path" "path/filepath" "runtime" "strings" "sync" "time" "github.com/gohugoio/hugo/codegen" "github.com/gohugoio/hugo/resources/page/page_generate" "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" ) const ( packageName = "github.com/gohugoio/hugo" noGitLdflags = "-X github.com/gohugoio/hugo/common/hugo.vendorInfo=mage" ) var ldflags = noGitLdflags // allow user to override go executable by running as GOEXE=xxx make ... on unix-like systems var goexe = "go" func init() { if exe := os.Getenv("GOEXE"); exe != "" { goexe = exe } } func runWith(env map[string]string, cmd string, inArgs ...any) error { s := argsToStrings(inArgs...) return sh.RunWith(env, cmd, s...) } // Build hugo binary func Hugo() error { return runWith(flagEnv(), goexe, "build", "-ldflags", ldflags, buildFlags(), "-tags", buildTags(), packageName) } // Build hugo binary with race detector enabled func HugoRace() error { return runWith(flagEnv(), goexe, "build", "-race", "-ldflags", ldflags, buildFlags(), "-tags", buildTags(), packageName) } // Install hugo binary func Install() error { return runWith(flagEnv(), goexe, "install", "-ldflags", ldflags, buildFlags(), "-tags", buildTags(), packageName) } // Uninstall hugo binary func Uninstall() error { return sh.Run(goexe, "clean", "-i", packageName) } // Uninstall all installed binaries (including test binaries) func UninstallAll() error { return sh.Run(goexe, "clean", "-i", "./...") } func flagEnv() map[string]string { hash, _ := sh.Output("git", "rev-parse", "--short", "HEAD") return map[string]string{ "PACKAGE": packageName, "COMMIT_HASH": hash, "BUILD_DATE": time.Now().Format("2006-01-02T15:04:05Z0700"), } } func emptyEnv() map[string]string { return map[string]string{} } // Generate autogen packages func Generate() error { generatorPackages := []string{ "livereload/gen", } for _, pkg := range generatorPackages { if err := runWith(flagEnv(), goexe, "generate", path.Join(packageName, pkg)); err != nil { return err } } dir, _ := os.Getwd() c := codegen.NewInspector(dir) if err := page_generate.Generate(c); err != nil { return err } goFmtPatterns := []string{ // TODO(bep) check: stat ./resources/page/*autogen*: no such file or directory "./resources/page/page_marshaljson.autogen.go", "./resources/page/page_wrappers.autogen.go", "./resources/page/zero_file.autogen.go", } for _, pattern := range goFmtPatterns { if err := sh.Run("gofmt", "-w", filepath.FromSlash(pattern)); err != nil { return err } } return nil } // Generate docs helper func GenDocsHelper() error { return runCmd(flagEnv(), goexe, "run", "-tags", buildTags(), "main.go", "gen", "docshelper") } // Build hugo without git info func HugoNoGitInfo() error { ldflags = noGitLdflags return Hugo() } // Build hugo Docker container func Docker() error { docker := sh.RunCmd("docker") if err := docker("build", "-t", "hugo", "."); err != nil { return err } // yes ignore errors here docker("rm", "-f", "hugo-build") if err := docker("run", "--name", "hugo-build", "hugo ls /go/bin"); err != nil { return err } if err := docker("cp", "hugo-build:/go/bin/hugo", "."); err != nil { return err } return docker("rm", "hugo-build") } // Run tests and linters func Check() { if isCI() && isDarwin() { // Skip on macOS in CI (disk space issues) } else { mg.Deps(Fmt, Vet) } // don't run two tests in parallel, they saturate the CPUs anyway, and running two // causes memory issues in CI. mg.Deps(TestRace) } func testGoFlags() string { if isCI() { return "" } return "-timeout=1m" } // Clean Go's test cache. func CleanTest() error { return runCmd(emptyEnv(), goexe, "clean", "-testcache") } // Run tests in 32-bit mode // Note that we don't run with the extended tag. Currently not supported in 32 bit. func Test386() error { env := map[string]string{"GOARCH": "386", "GOFLAGS": testGoFlags()} return runCmd(env, goexe, "test", "-p", "2", "./...") } // Run tests func Test() error { env := map[string]string{"GOFLAGS": testGoFlags()} return runCmd(env, goexe, "test", "-p", "2", "./...", "-tags", buildTags()) } // Run tests with race detector func TestRace() error { env := map[string]string{"GOFLAGS": testGoFlags()} if isCI() { // We have space issues on GitHub Actions (lots tests, incresing usage of Go generics). // Test each package separately and clean up in between. pkgs, err := hugoPackages() if err != nil { return err } for _, pkg := range pkgs { slashCount := strings.Count(pkg, "/") if slashCount > 1 { continue } if pkg != "." { pkg += "/..." } if err := cmp.Or(CleanTest(), UninstallAll()); err != nil { return err } if err := runCmd(env, goexe, "test", "-p", "2", "-race", pkg, "-tags", buildTags()); err != nil { return err } } return nil } else { return runCmd(env, goexe, "test", "-p", "2", "-race", "./...", "-tags", buildTags()) } } // Run gofmt linter func Fmt() error { if !isGoLatest() && !isUnix() { return nil } s, err := sh.Output("./check_gofmt.sh") if err != nil { fmt.Println(s) return fmt.Errorf("gofmt needs to be run: %s", err) } return nil } const pkgPrefixLen = len("github.com/gohugoio/hugo") var hugoPackages = sync.OnceValues(func() ([]string, error) { s, err := sh.Output(goexe, "list", "./...") if err != nil { return nil, err } pkgs := strings.Split(s, "\n") for i := range pkgs { pkgs[i] = "." + pkgs[i][pkgPrefixLen:] } return pkgs, nil }) // Run go vet linter func Vet() error { if err := sh.Run(goexe, "vet", "./..."); err != nil { return fmt.Errorf("error running go vet: %v", err) } return nil } // Generate test coverage report func TestCoverHTML() error { const ( coverAll = "coverage-all.out" cover = "coverage.out" ) f, err := os.Create(coverAll) if err != nil { return err } defer f.Close() if _, err := f.WriteString("mode: count"); err != nil { return err } pkgs, err := hugoPackages() if err != nil { return err } for _, pkg := range pkgs { if err := sh.Run(goexe, "test", "-coverprofile="+cover, "-covermode=count", pkg); err != nil { return err } b, err := os.ReadFile(cover) if err != nil { if os.IsNotExist(err) { continue } return err } idx := bytes.Index(b, []byte{'\n'}) b = b[idx+1:] if _, err := f.Write(b); err != nil { return err } } if err := f.Close(); err != nil { return err } return sh.Run(goexe, "tool", "cover", "-html="+coverAll) } func runCmd(env map[string]string, cmd string, args ...any) error { if mg.Verbose() { return runWith(env, cmd, args...) } output, err := sh.OutputWith(env, cmd, argsToStrings(args...)...) if err != nil { fmt.Fprint(os.Stderr, output) } return err } func isGoLatest() bool { return strings.Contains(runtime.Version(), "1.21") } func isUnix() bool { return runtime.GOOS != "windows" } func isDarwin() bool { return runtime.GOOS == "darwin" } func isCI() bool { return os.Getenv("CI") != "" } func buildFlags() []string { if runtime.GOOS == "windows" { return []string{"-buildmode", "exe"} } return nil } func buildTags() string { // To build the extended Hugo SCSS/SASS enabled version, build with // HUGO_BUILD_TAGS=extended mage install etc. // To build with `hugo deploy`, use HUGO_BUILD_TAGS=withdeploy if envtags := os.Getenv("HUGO_BUILD_TAGS"); envtags != "" { return envtags } return "none" } func argsToStrings(v ...any) []string { var args []string for _, arg := range v { switch v := arg.(type) { case string: if v != "" { args = append(args, v) } case []string: if v != nil { args = append(args, v...) } default: panic("invalid type") } } return args }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/main.go
main.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "log" "os" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/commands" ) func main() { log.SetFlags(0) err := commands.Execute(os.Args[1:]) if err != nil { for _, e := range herrors.Errors(err) { loggers.Log().Errorf("%s", e) } os.Exit(1) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/releaser/releaser.go
releaser/releaser.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package releaser implements a set of utilities to help automate the // Hugo release process. package releaser import ( "fmt" "log" "os" "os/exec" "path/filepath" "regexp" "strings" "github.com/gohugoio/hugo/common/version" ) const commitPrefix = "releaser:" // New initializes a ReleaseHandler. // Note that version is only used for testig. In CI we derive the version from the branch name. func New(skipPush, try bool, step int, version string) (*ReleaseHandler, error) { if step < 1 || step > 2 { return nil, fmt.Errorf("step must be 1 or 2") } if version == "" { prefix := "release-" branch, err := git("rev-parse", "--abbrev-ref", "HEAD") if err != nil { return nil, err } branch = strings.TrimSpace(branch) if !strings.HasPrefix(branch, prefix) { return nil, fmt.Errorf("branch %q is not a release branch", branch) } version = strings.TrimPrefix(branch, prefix) } version = strings.TrimPrefix(version, "v") logf("Version: v%s\n", version) rh := &ReleaseHandler{version: version, skipPush: skipPush, try: try, step: step} if try { rh.git = func(args ...string) (string, error) { logln("git", strings.Join(args, " ")) return "", nil } } else { rh.git = git } return rh, nil } // ReleaseHandler provides functionality to release a new version of Hugo. // Test this locally without doing an actual release: // go run -tags release main.go release --skip-publish --try -r 0.90.0 // Or a variation of the above -- the skip-publish flag makes sure that any changes are performed to the local Git only. type ReleaseHandler struct { version string // 1 or 2. step int // No remote pushes. skipPush bool // Just simulate, no actual changes. try bool git func(args ...string) (string, error) } // Run creates a new release. func (r *ReleaseHandler) Run() error { newVersion, finalVersion := r.calculateVersions() version := newVersion.String() tag := "v" + version logf("New version %q (prerelease: %t), final version %q\n", newVersion, newVersion.IsAlphaBetaOrRC(), finalVersion) r.gitPull() defer r.gitPush() if r.step == 1 { if err := r.bumpVersions(newVersion); err != nil { return err } if _, err := r.git("commit", "-a", "-m", fmt.Sprintf("%s Bump versions for release of %s\n\n[ci skip]", commitPrefix, newVersion)); err != nil { return err } // The above commit will be the target for this release, so print it to the console in a env friendly way. sha, err := git("rev-parse", "HEAD") if err != nil { return err } // Hugoreleaser will do the actual release using these values. if err := r.replaceInFile("hugoreleaser.env", `HUGORELEASER_TAG=(\S*)`, "HUGORELEASER_TAG="+tag, `HUGORELEASER_COMMITISH=(\S*)`, "HUGORELEASER_COMMITISH="+sha, ); err != nil { return err } logf("HUGORELEASER_TAG=%s\n", tag) logf("HUGORELEASER_COMMITISH=%s\n", sha) return nil } if err := r.bumpVersions(finalVersion); err != nil { return err } if _, err := r.git("commit", "-a", "-m", fmt.Sprintf("%s Prepare repository for %s\n\n[ci skip]", commitPrefix, finalVersion)); err != nil { return err } return nil } func (r *ReleaseHandler) bumpVersions(ver version.Version) error { toDev := "" if ver.Suffix != "" { toDev = ver.Suffix } if err := r.replaceInFile("common/hugo/version_current.go", `Minor:(\s*)(\d*),`, fmt.Sprintf(`Minor:${1}%d,`, ver.Minor), `PatchLevel:(\s*)(\d*),`, fmt.Sprintf(`PatchLevel:${1}%d,`, ver.PatchLevel), `Suffix:(\s*)".*",`, fmt.Sprintf(`Suffix:${1}"%s",`, toDev)); err != nil { return err } var minVersion string if ver.Suffix != "" { // People use the DEV version in daily use, and we cannot create new themes // with the next version before it is released. minVersion = ver.Prev().String() } else { minVersion = ver.String() } if err := r.replaceInFile("commands/new.go", `min_version = "(.*)"`, fmt.Sprintf(`min_version = "%s"`, minVersion)); err != nil { return err } return nil } func (r ReleaseHandler) calculateVersions() (version.Version, version.Version) { newVersion := version.MustParseVersion(r.version) var finalVersion version.Version if newVersion.IsAlphaBetaOrRC() { finalVersion = newVersion } else { finalVersion = newVersion.Next() } finalVersion.PatchLevel = 0 finalVersion.Suffix = "-DEV" return newVersion, finalVersion } func (r *ReleaseHandler) gitPull() { if _, err := r.git("pull", "origin", "HEAD"); err != nil { log.Fatal("pull failed:", err) } } func (r *ReleaseHandler) gitPush() { if r.skipPush { return } if _, err := r.git("push", "origin", "HEAD"); err != nil { log.Fatal("push failed:", err) } } func (r *ReleaseHandler) replaceInFile(filename string, oldNew ...string) error { filename = filepath.FromSlash(filename) fi, err := os.Stat(filename) if err != nil { return err } if r.try { logf("Replace in %q: %q\n", filename, oldNew) return nil } b, err := os.ReadFile(filename) if err != nil { return err } newContent := string(b) for i := 0; i < len(oldNew); i += 2 { re := regexp.MustCompile(oldNew[i]) newContent = re.ReplaceAllString(newContent, oldNew[i+1]) } return os.WriteFile(filename, []byte(newContent), fi.Mode()) } func git(args ...string) (string, error) { cmd := exec.Command("git", args...) out, err := cmd.CombinedOutput() if err != nil { return "", fmt.Errorf("git failed: %q: %q (%q)", err, out, args) } return string(out), nil } func logf(format string, args ...any) { fmt.Fprintf(os.Stderr, format, args...) } func logln(args ...any) { fmt.Fprintln(os.Stderr, args...) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/scripts/fork_go_templates/main.go
scripts/fork_go_templates/main.go
package main import ( "fmt" "log" "os" "os/exec" "path/filepath" "regexp" "strings" "github.com/gohugoio/hugo/common/hugio" "github.com/spf13/afero" ) func main() { // The current is built with 3901409b5d [release-branch.go1.24] go1.24.0 // TODO(bep) preserve the staticcheck.conf file. fmt.Println("Forking ...") defer fmt.Println("Done ...") cleanFork() htmlRoot := filepath.Join(forkRoot, "htmltemplate") for _, pkg := range goPackages { copyGoPackage(pkg.dstPkg, pkg.srcPkg) } for _, pkg := range goPackages { doWithGoFiles(pkg.dstPkg, pkg.rewriter, pkg.replacer) } goimports(htmlRoot) gofmt(forkRoot) } const ( // TODO(bep) goSource = "/Users/bep/dev/go/misc/go/src" forkRoot = "../../tpl/internal/go_templates" ) type goPackage struct { srcPkg string dstPkg string replacer func(name, content string) string rewriter func(name string) } var ( textTemplateReplacers = strings.NewReplacer( `"text/template/`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/`, `"internal/fmtsort"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"`, `"internal/testenv"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`, "TestLinkerGC", "_TestLinkerGC", // Rename types and function that we want to overload. "type state struct", "type stateOld struct", "func (s *state) evalFunction", "func (s *state) evalFunctionOld", "func (s *state) evalField(", "func (s *state) evalFieldOld(", "func (s *state) evalCall(", "func (s *state) evalCallOld(", "func isTrue(val reflect.Value) (truth, ok bool) {", "func isTrueOld(val reflect.Value) (truth, ok bool) {", ) testEnvReplacers = strings.NewReplacer( `"internal/cfg"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`, ) htmlTemplateReplacers = strings.NewReplacer( `. "html/template"`, `. "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"`, `"html/template"`, `template "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"`, "\"text/template\"\n", "template \"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate\"\n", `"html/template"`, `htmltemplate "html/template"`, `"fmt"`, `htmltemplate "html/template"`, `t.Skip("this test currently fails with -race; see issue #39807")`, `// t.Skip("this test currently fails with -race; see issue #39807")`, ) ) func commonReplace(name, content string) string { if strings.HasSuffix(name, "_test.go") { content = strings.Replace(content, "package template\n", `// +build go1.13,!windows package template `, 1) content = strings.Replace(content, "package template_test\n", `// +build go1.13 package template_test `, 1) content = strings.Replace(content, "package parse\n", `// +build go1.13 package parse `, 1) } return content } var goPackages = []goPackage{ { srcPkg: "text/template", dstPkg: "texttemplate", replacer: func(name, content string) string { return textTemplateReplacers.Replace(commonReplace(name, content)) }, }, { srcPkg: "html/template", dstPkg: "htmltemplate", replacer: func(name, content string) string { if strings.HasSuffix(name, "content.go") { // Remove template.HTML types. We need to use the Go types. content = removeAll(`(?s)// Strings of content.*?\)\n`, content) } content = commonReplace(name, content) return htmlTemplateReplacers.Replace(content) }, rewriter: func(name string) { for _, s := range []string{"CSS", "HTML", "HTMLAttr", "JS", "JSStr", "URL", "Srcset"} { rewrite(name, fmt.Sprintf("%s -> htmltemplate.%s", s, s)) } rewrite(name, `"text/template/parse" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"`) }, }, {srcPkg: "internal/fmtsort", dstPkg: "fmtsort", rewriter: func(name string) { rewrite(name, `"internal/fmtsort" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"`) }}, { srcPkg: "internal/testenv", dstPkg: "testenv", replacer: func(name, content string) string { return testEnvReplacers.Replace(content) }, rewriter: func(name string) { rewrite(name, `"internal/testenv" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`) }, }, {srcPkg: "internal/cfg", dstPkg: "cfg", rewriter: func(name string) { rewrite(name, `"internal/cfg" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`) }}, } var fs = afero.NewOsFs() // Removes all non-Hugo files in the go_templates folder. func cleanFork() { must(filepath.Walk(filepath.Join(forkRoot), func(path string, info os.FileInfo, err error) error { if !info.IsDir() && len(path) > 10 && !strings.Contains(path, "hugo") { must(fs.Remove(path)) } return nil })) } func must(err error, what ...string) { if err != nil { log.Fatal(what, " ERROR: ", err) } } func copyGoPackage(dst, src string) { from := filepath.Join(goSource, src) to := filepath.Join(forkRoot, dst) fmt.Println("Copy", from, "to", to) must(hugio.CopyDir(fs, from, to, func(s string) bool { return true })) } func doWithGoFiles(dir string, rewrite func(name string), transform func(name, in string) string, ) { if rewrite == nil && transform == nil { return } must(filepath.Walk(filepath.Join(forkRoot, dir), func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } if !strings.HasSuffix(path, ".go") || strings.Contains(path, "hugo_") { return nil } fmt.Println("Handle", path) if rewrite != nil { rewrite(path) } if transform == nil { return nil } data, err := os.ReadFile(path) must(err) f, err := os.Create(path) must(err) defer f.Close() _, err = f.WriteString(transform(path, string(data))) must(err) return nil })) } func removeAll(expression, content string) string { re := regexp.MustCompile(expression) return re.ReplaceAllString(content, "") } func rewrite(filename, rule string) { cmf := exec.Command("gofmt", "-w", "-r", rule, filename) out, err := cmf.CombinedOutput() if err != nil { log.Fatal("gofmt failed:", string(out)) } } func goimports(dir string) { // Needs go install golang.org/x/tools/cmd/goimports@latest cmf := exec.Command("goimports", "-w", dir) out, err := cmf.CombinedOutput() if err != nil { log.Fatal("goimports failed:", string(out)) } } func gofmt(dir string) { cmf := exec.Command("gofmt", "-w", dir) out, err := cmf.CombinedOutput() if err != nil { log.Fatal("gofmt failed:", string(out)) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/bufferpool/bufpool_test.go
bufferpool/bufpool_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 bufferpool import ( "testing" qt "github.com/frankban/quicktest" ) func TestBufferPool(t *testing.T) { c := qt.New(t) buff := GetBuffer() buff.WriteString("do be do be do") c.Assert(buff.String(), qt.Equals, "do be do be do") PutBuffer(buff) c.Assert(buff.Len(), qt.Equals, 0) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/bufferpool/bufpool.go
bufferpool/bufpool.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 bufferpool provides a pool of bytes buffers. package bufferpool import ( "bytes" "sync" ) var bufferPool = &sync.Pool{ New: func() any { return &bytes.Buffer{} }, } // GetBuffer returns a buffer from the pool. func GetBuffer() (buf *bytes.Buffer) { return bufferPool.Get().(*bytes.Buffer) } // PutBuffer returns a buffer to the pool. // The buffer is reset before it is put back into circulation. func PutBuffer(buf *bytes.Buffer) { buf.Reset() bufferPool.Put(buf) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/related/inverted_index.go
related/inverted_index.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 related holds code to help finding related content. package related import ( "context" "errors" "fmt" "math" "sort" "strings" "sync" "time" xmaps "maps" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/compare" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/types" "github.com/mitchellh/mapstructure" ) const ( TypeBasic = "basic" TypeFragments = "fragments" ) var validTypes = map[string]bool{ TypeBasic: true, TypeFragments: true, } var ( _ Keyword = (*StringKeyword)(nil) zeroDate = time.Time{} // DefaultConfig is the default related config. DefaultConfig = Config{ Threshold: 80, Indices: IndicesConfig{ IndexConfig{Name: "keywords", Weight: 100, Type: TypeBasic}, IndexConfig{Name: "date", Weight: 10, Type: TypeBasic}, }, } ) // Config is the top level configuration element used to configure how to retrieve // related content in Hugo. type Config struct { // Only include matches >= threshold, a normalized rank between 0 and 100. Threshold int // To get stable "See also" sections we, by default, exclude newer related pages. IncludeNewer bool // Will lower case all string values and queries to the indices. // May get better results, but at a slight performance cost. ToLower bool Indices IndicesConfig } // Add adds a given index. func (c *Config) Add(index IndexConfig) { if c.ToLower { index.ToLower = true } c.Indices = append(c.Indices, index) } func (c *Config) HasType(s string) bool { for _, i := range c.Indices { if i.Type == s { return true } } return false } // IndicesConfig holds a set of index configurations. type IndicesConfig []IndexConfig // IndexConfig configures an index. type IndexConfig struct { // The index name. This directly maps to a field or Param name. Name string // The index type. Type string // Enable to apply a type specific filter to the results. // This is currently only used for the "fragments" type. ApplyFilter bool // Contextual pattern used to convert the Param value into a string. // Currently only used for dates. Can be used to, say, bump posts in the same // time frame when searching for related documents. // For dates it follows Go's time.Format patterns, i.e. // "2006" for YYYY and "200601" for YYYYMM. Pattern string // This field's weight when doing multi-index searches. Higher is "better". Weight int // A percentage (0-100) used to remove common keywords from the index. // As an example, setting this to 50 will remove all keywords that are // used in more than 50% of the documents in the index. CardinalityThreshold int // Will lower case all string values in and queries tothis index. // May get better accurate results, but at a slight performance cost. ToLower bool } // Document is the interface an indexable document in Hugo must fulfill. type Document interface { // RelatedKeywords returns a list of keywords for the given index config. RelatedKeywords(cfg IndexConfig) ([]Keyword, error) // When this document was or will be published. PublishDate() time.Time // Name is used as an tiebreaker if both Weight and PublishDate are // the same. Name() string } // FragmentProvider is an optional interface that can be implemented by a Document. type FragmentProvider interface { Fragments(context.Context) *tableofcontents.Fragments // For internal use. ApplyFilterToHeadings(context.Context, func(*tableofcontents.Heading) bool) Document } // InvertedIndex holds an inverted index, also sometimes named posting list, which // lists, for every possible search term, the documents that contain that term. type InvertedIndex struct { cfg Config index map[string]map[Keyword][]Document // Counts the number of documents added to each index. indexDocCount map[string]int minWeight int maxWeight int // No modifications after this is set. finalized bool } func (idx *InvertedIndex) getIndexCfg(name string) (IndexConfig, bool) { for _, conf := range idx.cfg.Indices { if conf.Name == name { return conf, true } } return IndexConfig{}, false } // NewInvertedIndex creates a new InvertedIndex. // Documents to index must be added in Add. func NewInvertedIndex(cfg Config) *InvertedIndex { idx := &InvertedIndex{index: make(map[string]map[Keyword][]Document), indexDocCount: make(map[string]int), cfg: cfg} for _, conf := range cfg.Indices { idx.index[conf.Name] = make(map[Keyword][]Document) if conf.Weight < idx.minWeight { // By default, the weight scale starts at 0, but we allow // negative weights. idx.minWeight = conf.Weight } if conf.Weight > idx.maxWeight { idx.maxWeight = conf.Weight } } return idx } // Add documents to the inverted index. // The value must support == and !=. func (idx *InvertedIndex) Add(ctx context.Context, docs ...Document) error { if idx.finalized { panic("index is finalized") } var err error for _, config := range idx.cfg.Indices { if config.Weight == 0 { // Disabled continue } setm := idx.index[config.Name] for _, doc := range docs { var added bool var words []Keyword words, err = doc.RelatedKeywords(config) if err != nil { continue } for _, keyword := range words { added = true setm[keyword] = append(setm[keyword], doc) } if config.Type == TypeFragments { if fp, ok := doc.(FragmentProvider); ok { for _, fragment := range fp.Fragments(ctx).Identifiers { added = true setm[FragmentKeyword(fragment)] = append(setm[FragmentKeyword(fragment)], doc) } } } if added { idx.indexDocCount[config.Name]++ } } } return err } func (idx *InvertedIndex) Finalize(ctx context.Context) error { if idx.finalized { return nil } for _, config := range idx.cfg.Indices { if config.CardinalityThreshold == 0 { continue } setm := idx.index[config.Name] if idx.indexDocCount[config.Name] == 0 { continue } // Remove high cardinality terms. numDocs := idx.indexDocCount[config.Name] for k, v := range setm { percentageWithKeyword := int(math.Ceil(float64(len(v)) / float64(numDocs) * 100)) if percentageWithKeyword > config.CardinalityThreshold { delete(setm, k) } } } idx.finalized = true return nil } // queryElement holds the index name and keywords that can be used to compose a // search for related content. type queryElement struct { Index string Keywords []Keyword } func newQueryElement(index string, keywords ...Keyword) queryElement { return queryElement{Index: index, Keywords: keywords} } type ranks []*rank type rank struct { Doc Document Weight int Matches int } func (r *rank) addWeight(w int) { r.Weight += w r.Matches++ } var rankPool = sync.Pool{ New: func() any { return &rank{} }, } func getRank(doc Document, weight int) *rank { r := rankPool.Get().(*rank) r.Doc = doc r.Weight = weight r.Matches = 1 return r } func putRank(r *rank) { rankPool.Put(r) } func (r ranks) Len() int { return len(r) } func (r ranks) Swap(i, j int) { r[i], r[j] = r[j], r[i] } func (r ranks) Less(i, j int) bool { if r[i].Weight == r[j].Weight { if r[i].Doc.PublishDate() == r[j].Doc.PublishDate() { return r[i].Doc.Name() < r[j].Doc.Name() } return r[i].Doc.PublishDate().After(r[j].Doc.PublishDate()) } return r[i].Weight > r[j].Weight } // SearchOpts holds the options for a related search. type SearchOpts struct { // The Document to search for related content for. Document Document // The keywords to search for. NamedSlices []types.KeyValues // The indices to search in. Indices []string // Fragments holds a a list of special keywords that is used // for indices configured as type "fragments". // This will match the fragment identifiers of the documents. Fragments []string } // Search finds the documents matching any of the keywords in the given indices // against query options in opts. // The resulting document set will be sorted according to number of matches // and the index weights, and any matches with a rank below the configured // threshold (normalize to 0..100) will be removed. // If an index name is provided, only that index will be queried. func (idx *InvertedIndex) Search(ctx context.Context, opts SearchOpts) ([]Document, error) { var ( queryElements []queryElement configs IndicesConfig ) if len(opts.Indices) == 0 { configs = idx.cfg.Indices } else { configs = make(IndicesConfig, len(opts.Indices)) for i, indexName := range opts.Indices { cfg, found := idx.getIndexCfg(indexName) if !found { return nil, fmt.Errorf("index %q not found", indexName) } configs[i] = cfg } } for _, cfg := range configs { var keywords []Keyword if opts.Document != nil { k, err := opts.Document.RelatedKeywords(cfg) if err != nil { return nil, err } keywords = append(keywords, k...) } if cfg.Type == TypeFragments { for _, fragment := range opts.Fragments { keywords = append(keywords, FragmentKeyword(fragment)) } if opts.Document != nil { if fp, ok := opts.Document.(FragmentProvider); ok { for _, fragment := range fp.Fragments(ctx).Identifiers { keywords = append(keywords, FragmentKeyword(fragment)) } } } } queryElements = append(queryElements, newQueryElement(cfg.Name, keywords...)) } for _, slice := range opts.NamedSlices { var keywords []Keyword key := slice.KeyString() if key == "" { return nil, fmt.Errorf("index %q not valid", slice.Key) } conf, found := idx.getIndexCfg(key) if !found { return nil, fmt.Errorf("index %q not found", key) } for _, val := range slice.Values { k, err := conf.ToKeywords(val) if err != nil { return nil, err } keywords = append(keywords, k...) } queryElements = append(queryElements, newQueryElement(conf.Name, keywords...)) } if opts.Document != nil { return idx.searchDate(ctx, opts.Document, opts.Document.PublishDate(), queryElements...) } return idx.search(ctx, queryElements...) } func (cfg IndexConfig) stringToKeyword(s string) Keyword { if cfg.ToLower { s = strings.ToLower(s) } if cfg.Type == TypeFragments { return FragmentKeyword(s) } return StringKeyword(s) } // ToKeywords returns a Keyword slice of the given input. func (cfg IndexConfig) ToKeywords(v any) ([]Keyword, error) { var keywords []Keyword switch vv := v.(type) { case string: keywords = append(keywords, cfg.stringToKeyword(vv)) case []string: vvv := make([]Keyword, len(vv)) for i := range vvv { vvv[i] = cfg.stringToKeyword(vv[i]) } keywords = append(keywords, vvv...) case []any: return cfg.ToKeywords(cast.ToStringSlice(vv)) case time.Time: layout := "2006" if cfg.Pattern != "" { layout = cfg.Pattern } keywords = append(keywords, StringKeyword(vv.Format(layout))) case nil: return keywords, nil default: return keywords, fmt.Errorf("indexing currently not supported for index %q and type %T", cfg.Name, vv) } return keywords, nil } func (idx *InvertedIndex) search(ctx context.Context, query ...queryElement) ([]Document, error) { return idx.searchDate(ctx, nil, zeroDate, query...) } func (idx *InvertedIndex) searchDate(ctx context.Context, self Document, upperDate time.Time, query ...queryElement) ([]Document, error) { matchm := make(map[Document]*rank, 200) defer func() { for _, r := range matchm { putRank(r) } }() applyDateFilter := !idx.cfg.IncludeNewer && !upperDate.IsZero() var fragmentsFilter collections.SortedStringSlice for _, el := range query { setm, found := idx.index[el.Index] if !found { return []Document{}, fmt.Errorf("index for %q not found", el.Index) } config, found := idx.getIndexCfg(el.Index) if !found { return []Document{}, fmt.Errorf("index config for %q not found", el.Index) } for _, kw := range el.Keywords { if docs, found := setm[kw]; found { for _, doc := range docs { if compare.Eq(doc, self) { continue } if applyDateFilter { // Exclude newer than the limit given if doc.PublishDate().After(upperDate) { continue } } if config.Type == TypeFragments && config.ApplyFilter { if fkw, ok := kw.(FragmentKeyword); ok { fragmentsFilter = append(fragmentsFilter, string(fkw)) } } r, found := matchm[doc] if !found { r = getRank(doc, config.Weight) matchm[doc] = r } else { r.addWeight(config.Weight) } } } } } if len(matchm) == 0 { return []Document{}, nil } matches := make(ranks, 0, 100) for _, v := range matchm { avgWeight := v.Weight / v.Matches weight := norm(avgWeight, idx.minWeight, idx.maxWeight) threshold := idx.cfg.Threshold / v.Matches if weight >= threshold { matches = append(matches, v) } } sort.Stable(matches) sort.Strings(fragmentsFilter) result := make([]Document, len(matches)) for i, m := range matches { result[i] = m.Doc if len(fragmentsFilter) > 0 { if dp, ok := result[i].(FragmentProvider); ok { result[i] = dp.ApplyFilterToHeadings(ctx, func(h *tableofcontents.Heading) bool { return fragmentsFilter.Contains(h.ID) }) } } } return result, nil } // normalizes num to a number between 0 and 100. func norm(num, min, max int) int { if min > max { panic("min > max") } return int(math.Floor((float64(num-min) / float64(max-min) * 100) + 0.5)) } // DecodeConfig decodes a slice of map into Config. func DecodeConfig(m maps.Params) (Config, error) { if m == nil { return Config{}, errors.New("no related config provided") } if len(m) == 0 { return Config{}, errors.New("empty related config provided") } var c Config if err := mapstructure.WeakDecode(m, &c); err != nil { return c, err } if c.Threshold < 0 || c.Threshold > 100 { return Config{}, errors.New("related threshold must be between 0 and 100") } if c.ToLower { for i := range c.Indices { c.Indices[i].ToLower = true } } for i := range c.Indices { // Lower case name. c.Indices[i].Name = strings.ToLower(c.Indices[i].Name) icfg := c.Indices[i] if icfg.Type == "" { c.Indices[i].Type = TypeBasic } if !validTypes[c.Indices[i].Type] { return c, fmt.Errorf("invalid index type %q. Must be one of %v", c.Indices[i].Type, xmaps.Keys(validTypes)) } if icfg.CardinalityThreshold < 0 || icfg.CardinalityThreshold > 100 { return Config{}, errors.New("cardinalityThreshold threshold must be between 0 and 100") } } return c, nil } // StringKeyword is a string search keyword. type StringKeyword string func (s StringKeyword) String() string { return string(s) } // FragmentKeyword represents a document fragment. type FragmentKeyword string func (f FragmentKeyword) String() string { return string(f) } // Keyword is the interface a keyword in the search index must implement. type Keyword interface { String() string } // StringsToKeywords converts the given slice of strings to a slice of Keyword. func (cfg IndexConfig) StringsToKeywords(s ...string) []Keyword { kw := make([]Keyword, len(s)) for i := range s { kw[i] = cfg.stringToKeyword(s[i]) } return kw }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/related/inverted_index_test.go
related/inverted_index_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 related import ( "context" "fmt" "math/rand" "testing" "time" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" ) type testDoc struct { keywords map[string][]Keyword date time.Time name string } func (d *testDoc) String() string { s := "\n" for k, v := range d.keywords { s += k + ":\t\t" for _, vv := range v { s += " " + vv.String() } s += "\n" } return s } func (d *testDoc) Name() string { return d.name } func newTestDoc(name string, keywords ...string) *testDoc { time.Sleep(1 * time.Millisecond) return newTestDocWithDate(name, time.Now(), keywords...) } func newTestDocWithDate(name string, date time.Time, keywords ...string) *testDoc { km := make(map[string][]Keyword) kw := &testDoc{keywords: km, date: date} kw.addKeywords(name, keywords...) return kw } func (d *testDoc) addKeywords(name string, keywords ...string) *testDoc { keywordm := createTestKeywords(name, keywords...) for k, v := range keywordm { keywords := make([]Keyword, len(v)) for i := range v { keywords[i] = StringKeyword(v[i]) } d.keywords[k] = keywords } return d } func createTestKeywords(name string, keywords ...string) map[string][]string { return map[string][]string{ name: keywords, } } func (d *testDoc) RelatedKeywords(cfg IndexConfig) ([]Keyword, error) { return d.keywords[cfg.Name], nil } func (d *testDoc) PublishDate() time.Time { return d.date } func TestCardinalityThreshold(t *testing.T) { c := qt.New(t) config := Config{ Threshold: 90, IncludeNewer: false, Indices: IndicesConfig{ IndexConfig{Name: "tags", Weight: 50, CardinalityThreshold: 79}, IndexConfig{Name: "keywords", Weight: 65, CardinalityThreshold: 90}, }, } idx := NewInvertedIndex(config) hasKeyword := func(index, keyword string) bool { _, found := idx.index[index][StringKeyword(keyword)] return found } docs := []Document{ newTestDoc("tags", "a", "b", "c", "d"), newTestDoc("tags", "b", "d", "g"), newTestDoc("tags", "b", "d", "g"), newTestDoc("tags", "b", "h").addKeywords("keywords", "a"), newTestDoc("tags", "g", "h").addKeywords("keywords", "a", "b", "z"), } idx.Add(context.Background(), docs...) c.Assert(idx.Finalize(context.Background()), qt.IsNil) // Only tags=b should be removed. c.Assert(hasKeyword("tags", "a"), qt.Equals, true) c.Assert(hasKeyword("tags", "b"), qt.Equals, false) c.Assert(hasKeyword("tags", "d"), qt.Equals, true) c.Assert(hasKeyword("keywords", "b"), qt.Equals, true) } func TestSearch(t *testing.T) { config := Config{ Threshold: 90, IncludeNewer: false, Indices: IndicesConfig{ IndexConfig{Name: "tags", Weight: 50}, IndexConfig{Name: "keywords", Weight: 65}, }, } idx := NewInvertedIndex(config) // idx.debug = true docs := []Document{ newTestDoc("tags", "a", "b", "c", "d"), newTestDoc("tags", "b", "d", "g"), newTestDoc("tags", "b", "h").addKeywords("keywords", "a"), newTestDoc("tags", "g", "h").addKeywords("keywords", "a", "b"), } idx.Add(context.Background(), docs...) t.Run("count", func(t *testing.T) { c := qt.New(t) c.Assert(len(idx.index), qt.Equals, 2) set1, found := idx.index["tags"] c.Assert(found, qt.Equals, true) // 6 tags c.Assert(len(set1), qt.Equals, 6) set2, found := idx.index["keywords"] c.Assert(found, qt.Equals, true) c.Assert(len(set2), qt.Equals, 2) }) t.Run("search-tags", func(t *testing.T) { c := qt.New(t) var cfg IndexConfig m, err := idx.search(context.Background(), newQueryElement("tags", cfg.StringsToKeywords("a", "b", "d", "z")...)) c.Assert(err, qt.IsNil) c.Assert(len(m), qt.Equals, 2) c.Assert(m[0], qt.Equals, docs[0]) c.Assert(m[1], qt.Equals, docs[1]) }) t.Run("search-tags-and-keywords", func(t *testing.T) { c := qt.New(t) var cfg IndexConfig m, err := idx.search(context.Background(), newQueryElement("tags", cfg.StringsToKeywords("a", "b", "z")...), newQueryElement("keywords", cfg.StringsToKeywords("a", "b")...)) c.Assert(err, qt.IsNil) c.Assert(len(m), qt.Equals, 3) c.Assert(m[0], qt.Equals, docs[3]) c.Assert(m[1], qt.Equals, docs[2]) c.Assert(m[2], qt.Equals, docs[0]) }) t.Run("searchdoc-all", func(t *testing.T) { c := qt.New(t) doc := newTestDoc("tags", "a").addKeywords("keywords", "a") m, err := idx.Search(context.Background(), SearchOpts{Document: doc}) c.Assert(err, qt.IsNil) c.Assert(len(m), qt.Equals, 2) c.Assert(m[0], qt.Equals, docs[3]) c.Assert(m[1], qt.Equals, docs[2]) }) t.Run("searchdoc-tags", func(t *testing.T) { c := qt.New(t) doc := newTestDoc("tags", "a", "b", "d", "z").addKeywords("keywords", "a", "b") m, err := idx.Search(context.Background(), SearchOpts{Document: doc, Indices: []string{"tags"}}) c.Assert(err, qt.IsNil) c.Assert(len(m), qt.Equals, 2) c.Assert(m[0], qt.Equals, docs[0]) c.Assert(m[1], qt.Equals, docs[1]) }) t.Run("searchdoc-keywords-date", func(t *testing.T) { c := qt.New(t) doc := newTestDoc("tags", "a", "b", "d", "z").addKeywords("keywords", "a", "b") // This will get a date newer than the others. newDoc := newTestDoc("keywords", "a", "b") idx.Add(context.Background(), newDoc) m, err := idx.Search(context.Background(), SearchOpts{Document: doc, Indices: []string{"keywords"}}) c.Assert(err, qt.IsNil) c.Assert(len(m), qt.Equals, 2) c.Assert(m[0], qt.Equals, docs[3]) }) t.Run("searchdoc-keywords-same-date", func(t *testing.T) { c := qt.New(t) idx := NewInvertedIndex(config) date := time.Now() doc := newTestDocWithDate("keywords", date, "a", "b") doc.name = "thedoc" for i := range 10 { docc := *doc docc.name = fmt.Sprintf("doc%d", i) idx.Add(context.Background(), &docc) } m, err := idx.Search(context.Background(), SearchOpts{Document: doc, Indices: []string{"keywords"}}) c.Assert(err, qt.IsNil) c.Assert(len(m), qt.Equals, 10) for i := range 10 { c.Assert(m[i].Name(), qt.Equals, fmt.Sprintf("doc%d", i)) } }) } func TestToKeywordsToLower(t *testing.T) { c := qt.New(t) slice := []string{"A", "B", "C"} config := IndexConfig{ToLower: true} keywords, err := config.ToKeywords(slice) c.Assert(err, qt.IsNil) c.Assert(slice, qt.DeepEquals, []string{"A", "B", "C"}) c.Assert(keywords, qt.DeepEquals, []Keyword{ StringKeyword("a"), StringKeyword("b"), StringKeyword("c"), }) } func TestDecodeConfig(t *testing.T) { c := qt.New(t) configToml := ` [related] includeNewer = true threshold = 32 toLower = false [[related.indices]] applyFilter = false cardinalityThreshold = 0 name = 'KeyworDs' pattern = '' toLower = false type = 'basic' weight = 100 [[related.indices]] applyFilter = true cardinalityThreshold = 32 name = 'date' pattern = '' toLower = false type = 'basic' weight = 10 [[related.indices]] applyFilter = false cardinalityThreshold = 0 name = 'tags' pattern = '' toLower = false type = 'fragments' weight = 80 ` m, err := config.FromConfigString(configToml, "toml") c.Assert(err, qt.IsNil) conf, err := DecodeConfig(m.GetParams("related")) c.Assert(err, qt.IsNil) c.Assert(conf.IncludeNewer, qt.IsTrue) first := conf.Indices[0] c.Assert(first.Name, qt.Equals, "keywords") } func TestToKeywordsAnySlice(t *testing.T) { c := qt.New(t) var config IndexConfig slice := []any{"A", 32, "C"} keywords, err := config.ToKeywords(slice) c.Assert(err, qt.IsNil) c.Assert(keywords, qt.DeepEquals, []Keyword{ StringKeyword("A"), StringKeyword("32"), StringKeyword("C"), }) } func BenchmarkRelatedNewIndex(b *testing.B) { pages := make([]*testDoc, 100) numkeywords := 30 allKeywords := make([]string, numkeywords) for i := range numkeywords { allKeywords[i] = fmt.Sprintf("keyword%d", i+1) } for i := range pages { start := rand.Intn(len(allKeywords)) end := start + 3 if end >= len(allKeywords) { end = start + 1 } kw := newTestDoc("tags", allKeywords[start:end]...) if i%5 == 0 { start := rand.Intn(len(allKeywords)) end := start + 3 if end >= len(allKeywords) { end = start + 1 } kw.addKeywords("keywords", allKeywords[start:end]...) } pages[i] = kw } cfg := Config{ Threshold: 50, Indices: IndicesConfig{ IndexConfig{Name: "tags", Weight: 100}, IndexConfig{Name: "keywords", Weight: 200}, }, } b.Run("singles", func(b *testing.B) { for b.Loop() { idx := NewInvertedIndex(cfg) for _, doc := range pages { idx.Add(context.Background(), doc) } } }) b.Run("all", func(b *testing.B) { for b.Loop() { idx := NewInvertedIndex(cfg) docs := make([]Document, len(pages)) for i := range pages { docs[i] = pages[i] } idx.Add(context.Background(), docs...) } }) } func BenchmarkRelatedMatchesIn(b *testing.B) { var icfg IndexConfig q1 := newQueryElement("tags", icfg.StringsToKeywords("keyword2", "keyword5", "keyword32", "asdf")...) q2 := newQueryElement("keywords", icfg.StringsToKeywords("keyword3", "keyword4")...) docs := make([]*testDoc, 1000) numkeywords := 20 allKeywords := make([]string, numkeywords) for i := range numkeywords { allKeywords[i] = fmt.Sprintf("keyword%d", i+1) } cfg := Config{ Threshold: 20, Indices: IndicesConfig{ IndexConfig{Name: "tags", Weight: 100}, IndexConfig{Name: "keywords", Weight: 200}, }, } idx := NewInvertedIndex(cfg) for i := range docs { start := rand.Intn(len(allKeywords)) end := start + 3 if end >= len(allKeywords) { end = start + 1 } index := "tags" if i%5 == 0 { index = "keywords" } idx.Add(context.Background(), newTestDoc(index, allKeywords[start:end]...)) } ctx := context.Background() for i := 0; b.Loop(); i++ { if i%10 == 0 { idx.search(ctx, q2) } else { idx.search(ctx, q1) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/related/related_integration_test.go
related/related_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package related_test import ( "fmt" "math/rand" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestRelatedFragments(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT"] [related] includeNewer = false threshold = 80 toLower = false [[related.indices]] name = 'pagerefs' type = 'fragments' applyFilter = true weight = 90 [[related.indices]] name = 'keywords' weight = 80 -- content/p1.md -- --- title: p1 pagerefs: ['ref1'] --- {{< see-also >}} ## P1 title -- content/p2.md -- --- title: p2 --- ## P2 title 1 ## P2 title 2 ## First title {#ref1} {{< see-also "ref1" >}} -- content/p3.md -- --- title: p3 keywords: ['foo'] --- ## P3 title 1 ## P3 title 2 ## Common p3, p4, p5 -- content/p4.md -- --- title: p4 --- ## Common p3, p4, p5 ## P4 title 1 -- content/p5.md -- --- title: p5 keywords: ['foo'] --- ## P5 title 1 ## Common p3, p4, p5 -- layouts/_shortcodes/see-also.html -- {{ $p1 := site.GetPage "p1" }} {{ $p2 := site.GetPage "p2" }} {{ $p3 := site.GetPage "p3" }} P1 Fragments: {{ $p1.Fragments.Identifiers }} P2 Fragments: {{ $p2.Fragments.Identifiers }} Contains ref1: {{ $p2.Fragments.Identifiers.Contains "ref1" }} Count ref1: {{ $p2.Fragments.Identifiers.Count "ref1" }} {{ $opts := dict "document" .Page "fragments" $.Params }} {{ $related1 := site.RegularPages.Related $opts }} {{ $related2 := site.RegularPages.Related $p3 }} Len Related 1: {{ len $related1 }} Len Related 2: {{ len $related2 }} Related 1: {{ template "list-related" $related1 }} Related 2: {{ template "list-related" $related2 }} {{ define "list-related" }}{{ range $i, $e := . }} {{ $i }}: {{ .Title }}: {{ with .HeadingsFiltered}}{{ range $i, $e := .}}h{{ $i }}: {{ .Title }}|{{ .ID }}|{{ end }}{{ end }}::END{{ end }}{{ end }} -- layouts/single.html -- Content: {{ .Content }} ` b := hugolib.Test(t, files) expect := ` P1 Fragments: [p1-title] P2 Fragments: [p2-title-1 p2-title-2 ref1] Len Related 1: 1 Related 2: 2 ` for _, p := range []string{"p1", "p2"} { b.AssertFileContent("public/"+p+"/index.html", expect) } b.AssertFileContent("public/p1/index.html", "Related 1: 0: p2: h0: First title|ref1|::END", "Related 2: 0: p5: h0: Common p3, p4, p5|common-p3-p4-p5|::END 1: p4: h0: Common p3, p4, p5|common-p3-p4-p5|::END", ) } func BenchmarkRelatedSite(b *testing.B) { files := ` -- hugo.toml -- baseURL = "http://example.com/" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT"] [related] includeNewer = false threshold = 80 toLower = false [[related.indices]] name = 'keywords' weight = 70 [[related.indices]] name = 'pagerefs' type = 'fragments' weight = 30 -- layouts/single.html -- Len related: {{ site.RegularPages.Related . | len }} ` createContent := func(n int) string { base := `--- title: "Page %d" keywords: ['k%d'] --- ` for range 32 { base += fmt.Sprintf("\n## Title %d", rand.Intn(100)) } return fmt.Sprintf(base, n, rand.Intn(32)) } for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+createContent(i+1), i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } for b.Loop() { b.StopTimer() bb := hugolib.NewIntegrationTestBuilder(cfg) b.StartTimer() bb.Build() } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/minifiers/minifiers.go
minifiers/minifiers.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 minifiers contains minifiers mapped to MIME types. This package is used // in both the resource transformation, i.e. resources.Minify, and in the publishing // chain. package minifiers import ( "io" "regexp" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/transform" "github.com/gohugoio/hugo/media" "github.com/tdewolff/minify/v2" ) // Client wraps a minifier. type Client struct { // Whether output minification is enabled (HTML in /public) MinifyOutput bool m *minify.M } // Transformer returns a func that can be used in the transformer publishing chain. // TODO(bep) minify config etc func (m Client) Transformer(mediatype media.Type) transform.Transformer { _, params, min := m.m.Match(mediatype.Type) if min == nil { // No minifier for this MIME type return nil } return func(ft transform.FromTo) error { // Note that the source io.Reader will already be buffered, but it implements // the Bytes() method, which is recognized by the Minify library. return min.Minify(m.m, ft.To(), ft.From(), params) } } // Minify tries to minify the src into dst given a MIME type. func (m Client) Minify(mediatype media.Type, dst io.Writer, src io.Reader) error { return m.m.Minify(mediatype.Type, dst, src) } // noopMinifier implements minify.Minifier [1], but doesn't minify content. This means // that we can avoid missing minifiers for any MIME types in our minify.M, which // causes minify to return errors, while still allowing minification to be // disabled for specific types. // // [1]: https://pkg.go.dev/github.com/tdewolff/minify#Minifier type noopMinifier struct{} // Minify copies r into w without transformation. func (m noopMinifier) Minify(_ *minify.M, w io.Writer, r io.Reader, _ map[string]string) error { _, err := io.Copy(w, r) return err } // New creates a new Client with the provided MIME types as the mapping foundation. // The HTML minifier is also registered for additional HTML types (AMP etc.) in the // provided list of output formats. func New(mediaTypes media.Types, outputFormats output.Formats, cfg config.AllProvider) (Client, error) { conf := cfg.GetConfigSection("minify").(MinifyConfig) m := minify.New() // We use the Type definition of the media types defined in the site if found. addMinifier(m, mediaTypes, "css", getMinifier(conf, "css")) addMinifier(m, mediaTypes, "js", getMinifier(conf, "js")) m.AddRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"), getMinifier(conf, "js")) addMinifier(m, mediaTypes, "json", getMinifier(conf, "json")) m.AddRegexp(regexp.MustCompile(`^(application|text)/(x-|(ld|manifest)\+)?json$`), getMinifier(conf, "json")) addMinifier(m, mediaTypes, "svg", getMinifier(conf, "svg")) addMinifier(m, mediaTypes, "xml", getMinifier(conf, "xml")) // HTML addMinifier(m, mediaTypes, "html", getMinifier(conf, "html")) for _, of := range outputFormats { if of.IsHTML { m.Add(of.MediaType.Type, getMinifier(conf, "html")) } } return Client{m: m, MinifyOutput: conf.MinifyOutput}, nil } // getMinifier returns the appropriate minify.MinifierFunc for the MIME // type suffix s, given the config c. func getMinifier(c MinifyConfig, s string) minify.Minifier { switch { case s == "css" && !c.DisableCSS: return &c.Tdewolff.CSS case s == "js" && !c.DisableJS: return &c.Tdewolff.JS case s == "json" && !c.DisableJSON: return &c.Tdewolff.JSON case s == "svg" && !c.DisableSVG: return &c.Tdewolff.SVG case s == "xml" && !c.DisableXML: return &c.Tdewolff.XML case s == "html" && !c.DisableHTML: return &c.Tdewolff.HTML default: return noopMinifier{} } } func addMinifier(m *minify.M, mt media.Types, suffix string, min minify.Minifier) { types := mt.BySuffix(suffix) for _, t := range types { m.Add(t.Type, min) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/minifiers/config.go
minifiers/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 minifiers import ( "fmt" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/maps" "github.com/spf13/cast" "github.com/mitchellh/mapstructure" "github.com/tdewolff/minify/v2/css" "github.com/tdewolff/minify/v2/html" "github.com/tdewolff/minify/v2/js" "github.com/tdewolff/minify/v2/json" "github.com/tdewolff/minify/v2/svg" "github.com/tdewolff/minify/v2/xml" ) var defaultTdewolffConfig = TdewolffConfig{ HTML: html.Minifier{ KeepDocumentTags: true, KeepSpecialComments: true, KeepEndTags: true, KeepDefaultAttrVals: true, KeepWhitespace: false, }, CSS: css.Minifier{ Precision: 0, // 0 means no trimming Version: 0, // 0 means the latest CSS version }, JS: js.Minifier{ Version: 2022, }, JSON: json.Minifier{}, SVG: svg.Minifier{ KeepComments: false, Precision: 0, // 0 means no trimming }, XML: xml.Minifier{ KeepWhitespace: false, }, } type TdewolffConfig struct { HTML html.Minifier CSS css.Minifier JS js.Minifier JSON json.Minifier SVG svg.Minifier XML xml.Minifier } type MinifyConfig struct { // Whether to minify the published output (the HTML written to /public). MinifyOutput bool DisableHTML bool DisableCSS bool DisableJS bool DisableJSON bool DisableSVG bool DisableXML bool Tdewolff TdewolffConfig } var defaultConfig = MinifyConfig{ Tdewolff: defaultTdewolffConfig, } func DecodeConfig(v any) (conf MinifyConfig, err error) { conf = defaultConfig if v == nil { return } m := maps.ToStringMap(v) // Handle deprecations. if td, found := m["tdewolff"]; found { tdm := maps.ToStringMap(td) // Decimals was renamed to Precision in tdewolff/minify v2.7.0. // https://github.com/tdewolff/minify/commit/2fed4401348ce36bd6c20e77335a463e69d94386 for _, key := range []string{"css", "svg"} { if v, found := tdm[key]; found { vm := maps.ToStringMap(v) ko := "decimals" kn := "precision" if vv, found := vm[ko]; found { hugo.Deprecate( fmt.Sprintf("site config key minify.tdewolff.%s.%s", key, ko), fmt.Sprintf("Use config key minify.tdewolff.%s.%s instead.", key, kn), "v0.150.0", ) if _, found = vm[kn]; !found { vvi := cast.ToInt(vv) if vvi > 0 { vm[kn] = vvi } } delete(vm, ko) } } } // KeepConditionalComments was renamed to KeepSpecialComments in tdewolff/minify v2.20.13. // https://github.com/tdewolff/minify/commit/342cbc1974162db0ad3327f7a42a623b2cd3ebbc if v, found := tdm["html"]; found { vm := maps.ToStringMap(v) ko := "keepconditionalcomments" kn := "keepspecialcomments" if vv, found := vm[ko]; found { hugo.Deprecate( fmt.Sprintf("site config key minify.tdewolff.html.%s", ko), fmt.Sprintf("Use config key minify.tdewolff.html.%s instead.", kn), "v0.150.0", ) if _, found := vm[kn]; !found { vm[kn] = cast.ToBool(vv) } delete(vm, ko) } } // KeepCSS2 was deprecated in favor of Version in tdewolff/minify v2.24.1. // https://github.com/tdewolff/minify/commit/57e3ebe0e6914b82c9ab0849a14f86bc29cd2ebf if v, found := tdm["css"]; found { vm := maps.ToStringMap(v) ko := "keepcss2" kn := "version" if vv, found := vm[ko]; found { hugo.Deprecate( fmt.Sprintf("site config key minify.tdewolff.css.%s", ko), fmt.Sprintf("Use config key minify.tdewolff.css.%s instead.", kn), "v0.150.0", ) if _, found := vm[kn]; !found { if cast.ToBool(vv) { vm[kn] = 2 } } delete(vm, ko) } } } err = mapstructure.WeakDecode(m, &conf) if err != nil { return } return }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/minifiers/config_test.go
minifiers/config_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package minifiers_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/testconfig" ) func TestConfig(t *testing.T) { c := qt.New(t) v := config.New() v.Set("minify", map[string]any{ "disablexml": true, "tdewolff": map[string]any{ "html": map[string]any{ "keepwhitespace": false, }, }, }) conf := testconfig.GetTestConfigs(nil, v).Base.Minify c.Assert(conf.MinifyOutput, qt.Equals, false) // explicitly set value c.Assert(conf.Tdewolff.HTML.KeepWhitespace, qt.Equals, false) // default value c.Assert(conf.Tdewolff.HTML.KeepEndTags, qt.Equals, true) c.Assert(conf.Tdewolff.CSS.Version, qt.Equals, 0) // `enable` flags c.Assert(conf.DisableHTML, qt.Equals, false) c.Assert(conf.DisableXML, qt.Equals, true) } func TestConfigDeprecations(t *testing.T) { c := qt.New(t) // Test default values of deprecated root keys. v := config.New() v.Set("minify", false) conf := testconfig.GetTestConfigs(nil, v).Base.Minify c.Assert(conf.MinifyOutput, qt.Equals, false) v = config.New() v.Set("minifyoutput", false) conf = testconfig.GetTestConfigs(nil, v).Base.Minify c.Assert(conf.MinifyOutput, qt.Equals, false) // Test non-default values of deprecated root keys. v = config.New() v.Set("minify", true) conf = testconfig.GetTestConfigs(nil, v).Base.Minify c.Assert(conf.MinifyOutput, qt.Equals, true) v = config.New() v.Set("minifyoutput", true) conf = testconfig.GetTestConfigs(nil, v).Base.Minify c.Assert(conf.MinifyOutput, qt.Equals, true) } func TestConfigUpstreamDeprecations(t *testing.T) { c := qt.New(t) // Test default values of deprecated keys. v := config.New() v.Set("minify", map[string]any{ "tdewolff": map[string]any{ "css": map[string]any{ "decimals": 0, "keepcss2": true, }, "html": map[string]any{ "keepconditionalcomments": true, }, "svg": map[string]any{ "decimals": 0, }, }, }) conf := testconfig.GetTestConfigs(nil, v).Base.Minify c.Assert(conf.Tdewolff.CSS.Precision, qt.Equals, 0) c.Assert(conf.Tdewolff.CSS.Version, qt.Equals, 2) c.Assert(conf.Tdewolff.HTML.KeepSpecialComments, qt.Equals, true) c.Assert(conf.Tdewolff.SVG.Precision, qt.Equals, 0) // Test non-default values of deprecated keys. v = config.New() v.Set("minify", map[string]any{ "tdewolff": map[string]any{ "css": map[string]any{ "decimals": 6, "keepcss2": false, }, "html": map[string]any{ "keepconditionalcomments": false, }, "svg": map[string]any{ "decimals": 7, }, }, }) conf = testconfig.GetTestConfigs(nil, v).Base.Minify c.Assert(conf.Tdewolff.CSS.Precision, qt.Equals, 6) c.Assert(conf.Tdewolff.CSS.Version, qt.Equals, 0) c.Assert(conf.Tdewolff.HTML.KeepSpecialComments, qt.Equals, false) c.Assert(conf.Tdewolff.SVG.Precision, qt.Equals, 7) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/minifiers/minifiers_test.go
minifiers/minifiers_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package minifiers_test import ( "bytes" "encoding/json" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/minifiers" "github.com/gohugoio/hugo/output" "github.com/spf13/afero" ) func TestNew(t *testing.T) { c := qt.New(t) m, _ := minifiers.New(media.DefaultTypes, output.DefaultFormats, testconfig.GetTestConfig(afero.NewMemMapFs(), nil)) var rawJS string var minJS string rawJS = " var foo =1 ; foo ++ ; " minJS = "var foo=1;foo++" var rawJSON string var minJSON string rawJSON = " { \"a\" : 123 , \"b\":2, \"c\": 5 } " minJSON = "{\"a\":123,\"b\":2,\"c\":5}" for _, test := range []struct { tp media.Type rawString string expectedMinString string }{ {media.Builtin.CSSType, " body { color: blue; } ", "body{color:blue}"}, {media.Builtin.RSSType, " <hello> Hugo! </hello> ", "<hello>Hugo!</hello>"}, // RSS should be handled as XML {media.Builtin.JSONType, rawJSON, minJSON}, {media.Builtin.JavascriptType, rawJS, minJS}, // JS Regex minifiers {media.Type{Type: "application/ecmascript", MainType: "application", SubType: "ecmascript"}, rawJS, minJS}, {media.Type{Type: "application/javascript", MainType: "application", SubType: "javascript"}, rawJS, minJS}, {media.Type{Type: "application/x-javascript", MainType: "application", SubType: "x-javascript"}, rawJS, minJS}, {media.Type{Type: "application/x-ecmascript", MainType: "application", SubType: "x-ecmascript"}, rawJS, minJS}, {media.Type{Type: "text/ecmascript", MainType: "text", SubType: "ecmascript"}, rawJS, minJS}, {media.Type{Type: "application/javascript", MainType: "text", SubType: "javascript"}, rawJS, minJS}, // JSON Regex minifiers {media.Type{Type: "application/json", MainType: "application", SubType: "json"}, rawJSON, minJSON}, {media.Type{Type: "application/x-json", MainType: "application", SubType: "x-json"}, rawJSON, minJSON}, {media.Type{Type: "application/ld+json", MainType: "application", SubType: "ld+json"}, rawJSON, minJSON}, {media.Type{Type: "application/json", MainType: "text", SubType: "json"}, rawJSON, minJSON}, } { var b bytes.Buffer c.Assert(m.Minify(test.tp, &b, strings.NewReader(test.rawString)), qt.IsNil) c.Assert(b.String(), qt.Equals, test.expectedMinString) } } func TestConfigureMinify(t *testing.T) { c := qt.New(t) v := config.New() v.Set("minify", map[string]any{ "disablexml": true, "tdewolff": map[string]any{ "html": map[string]any{ "keepwhitespace": true, }, }, }) m, _ := minifiers.New(media.DefaultTypes, output.DefaultFormats, testconfig.GetTestConfig(afero.NewMemMapFs(), v)) for _, test := range []struct { tp media.Type rawString string expectedMinString string errorExpected bool }{ {media.Builtin.HTMLType, "<hello> Hugo! </hello>", "<hello> Hugo! </hello>", false}, // configured minifier {media.Builtin.CSSType, " body { color: blue; } ", "body{color:blue}", false}, // default minifier {media.Builtin.XMLType, " <hello> Hugo! </hello> ", " <hello> Hugo! </hello> ", false}, // disable Xml minification } { var b bytes.Buffer if !test.errorExpected { c.Assert(m.Minify(test.tp, &b, strings.NewReader(test.rawString)), qt.IsNil) c.Assert(b.String(), qt.Equals, test.expectedMinString) } else { err := m.Minify(test.tp, &b, strings.NewReader(test.rawString)) c.Assert(err, qt.ErrorMatches, "minifier does not exist for mimetype") } } } func TestJSONRoundTrip(t *testing.T) { c := qt.New(t) m, _ := minifiers.New(media.DefaultTypes, output.DefaultFormats, testconfig.GetTestConfig(nil, nil)) for _, test := range []string{`{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }`} { var b bytes.Buffer m1 := make(map[string]any) m2 := make(map[string]any) c.Assert(json.Unmarshal([]byte(test), &m1), qt.IsNil) c.Assert(m.Minify(media.Builtin.JSONType, &b, strings.NewReader(test)), qt.IsNil) c.Assert(json.Unmarshal(b.Bytes(), &m2), qt.IsNil) c.Assert(m1, qt.DeepEquals, m2) } } func TestBugs(t *testing.T) { c := qt.New(t) v := config.New() m, _ := minifiers.New(media.DefaultTypes, output.DefaultFormats, testconfig.GetTestConfig(nil, v)) for _, test := range []struct { tp media.Type rawString string expectedMinString string }{ // Issue 5506 {media.Builtin.CSSType, " body { color: rgba(000, 000, 000, 0.7); }", "body{color:rgba(0,0,0,.7)}"}, // Issue 8332 {media.Builtin.HTMLType, "<i class='fas fa-tags fa-fw'></i> Tags", `<i class='fas fa-tags fa-fw'></i> Tags`}, // Issue #13082 {media.Builtin.HTMLType, "<gcse:searchresults-only></gcse:searchresults-only>", `<gcse:searchresults-only></gcse:searchresults-only>`}, } { var b bytes.Buffer c.Assert(m.Minify(test.tp, &b, strings.NewReader(test.rawString)), qt.IsNil) c.Assert(b.String(), qt.Equals, test.expectedMinString) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/codegen/methods2_test.go
codegen/methods2_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 codegen type IEmbed interface { MethodEmbed3(s string) string MethodEmbed1() string MethodEmbed2() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/codegen/methods_test.go
codegen/methods_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 codegen import ( "fmt" "net" "os" "reflect" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/herrors" ) func TestMethods(t *testing.T) { var ( zeroIE = reflect.TypeOf((*IEmbed)(nil)).Elem() zeroIEOnly = reflect.TypeOf((*IEOnly)(nil)).Elem() zeroI = reflect.TypeOf((*I)(nil)).Elem() ) dir, _ := os.Getwd() insp := NewInspector(dir) t.Run("MethodsFromTypes", func(t *testing.T) { c := qt.New(t) methods := insp.MethodsFromTypes([]reflect.Type{zeroI}, nil) methodsStr := fmt.Sprint(methods) c.Assert(methodsStr, qt.Contains, "Method1(arg0 herrors.ErrorContext)") c.Assert(methodsStr, qt.Contains, "Method7() interface {}") c.Assert(methodsStr, qt.Contains, "Method0() string\n Method4() string") c.Assert(methodsStr, qt.Contains, "MethodEmbed3(arg0 string) string\n MethodEmbed1() string") c.Assert(methods.Imports(), qt.Contains, "github.com/gohugoio/hugo/common/herrors") }) t.Run("EmbedOnly", func(t *testing.T) { c := qt.New(t) methods := insp.MethodsFromTypes([]reflect.Type{zeroIEOnly}, nil) methodsStr := fmt.Sprint(methods) c.Assert(methodsStr, qt.Contains, "MethodEmbed3(arg0 string) string") }) t.Run("ToMarshalJSON", func(t *testing.T) { c := qt.New(t) m, pkg := insp.MethodsFromTypes( []reflect.Type{zeroI}, []reflect.Type{zeroIE}).ToMarshalJSON("*page", "page") c.Assert(m, qt.Contains, "method6 := p.Method6()") c.Assert(m, qt.Contains, "Method0: method0,") c.Assert(m, qt.Contains, "return json.Marshal(&s)") c.Assert(pkg, qt.Contains, "github.com/gohugoio/hugo/common/herrors") c.Assert(pkg, qt.Contains, "encoding/json") fmt.Println(pkg) }) } type I interface { IEmbed Method0() string Method4() string Method1(myerr herrors.ErrorContext) Method3(myint int, mystring string) Method5() (string, error) Method6() *net.IP Method7() any Method8() herrors.ErrorContext method2() method9() os.FileInfo } type IEOnly interface { IEmbed }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/codegen/methods.go
codegen/methods.go
// Copyright 2019 The Hugo Authors. All rights reserved. // Some functions in this file (see comments) is based on the Go source code, // copyright The Go Authors and governed by a BSD-style license. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package codegen contains helpers for code generation. package codegen import ( "fmt" "go/ast" "go/parser" "go/token" "os" "path" "path/filepath" "reflect" "regexp" "slices" "sort" "strings" "sync" ) // Make room for insertions const weightWidth = 1000 // NewInspector creates a new Inspector given a source root. func NewInspector(root string) *Inspector { return &Inspector{ProjectRootDir: root} } // Inspector provides methods to help code generation. It uses a combination // of reflection and source code AST to do the heavy lifting. type Inspector struct { ProjectRootDir string init sync.Once // Determines method order. Go's reflect sorts lexicographically, so // we must parse the source to preserve this order. methodWeight map[string]map[string]int } // MethodsFromTypes create a method set from the include slice, excluding any // method in exclude. func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.Type) Methods { c.parseSource() var methods Methods excludes := make(map[string]bool) if len(exclude) > 0 { for _, m := range c.MethodsFromTypes(exclude, nil) { excludes[m.Name] = true } } // There may be overlapping interfaces in types. Do a simple check for now. seen := make(map[string]bool) nameAndPackage := func(t reflect.Type) (string, string) { var name, pkg string isPointer := t.Kind() == reflect.Ptr if isPointer { t = t.Elem() } pkgPrefix := "" if pkgPath := t.PkgPath(); pkgPath != "" { pkgPath = strings.TrimSuffix(pkgPath, "/") _, shortPath := path.Split(pkgPath) pkgPrefix = shortPath + "." pkg = pkgPath } name = t.Name() if name == "" { // interface{} name = t.String() } if isPointer { pkgPrefix = "*" + pkgPrefix } name = pkgPrefix + name return name, pkg } for _, t := range include { for i := range t.NumMethod() { m := t.Method(i) if excludes[m.Name] || seen[m.Name] { continue } seen[m.Name] = true if m.PkgPath != "" { // Not exported continue } numIn := m.Type.NumIn() ownerName, _ := nameAndPackage(t) method := Method{Owner: t, OwnerName: ownerName, Name: m.Name} for i := range numIn { in := m.Type.In(i) name, pkg := nameAndPackage(in) if pkg != "" { method.Imports = append(method.Imports, pkg) } method.In = append(method.In, name) } numOut := m.Type.NumOut() if numOut > 0 { for i := range numOut { out := m.Type.Out(i) name, pkg := nameAndPackage(out) if pkg != "" { method.Imports = append(method.Imports, pkg) } method.Out = append(method.Out, name) } } methods = append(methods, method) } } sort.SliceStable(methods, func(i, j int) bool { mi, mj := methods[i], methods[j] wi := c.methodWeight[mi.OwnerName][mi.Name] wj := c.methodWeight[mj.OwnerName][mj.Name] if wi == wj { return mi.Name < mj.Name } return wi < wj }) return methods } func (c *Inspector) parseSource() { c.init.Do(func() { if !strings.Contains(c.ProjectRootDir, "hugo") { panic("dir must be set to the Hugo root") } c.methodWeight = make(map[string]map[string]int) dirExcludes := regexp.MustCompile("docs|examples") fileExcludes := regexp.MustCompile("autogen") var filenames []string filepath.Walk(c.ProjectRootDir, func(path string, info os.FileInfo, err error) error { if info.IsDir() { if dirExcludes.MatchString(info.Name()) { return filepath.SkipDir } } if !strings.HasSuffix(path, ".go") || fileExcludes.MatchString(path) { return nil } filenames = append(filenames, path) return nil }) for _, filename := range filenames { pkg := c.packageFromPath(filename) fset := token.NewFileSet() node, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) if err != nil { panic(err) } ast.Inspect(node, func(n ast.Node) bool { switch t := n.(type) { case *ast.TypeSpec: if t.Name.IsExported() { switch it := t.Type.(type) { case *ast.InterfaceType: iface := pkg + "." + t.Name.Name methodNames := collectMethodsRecursive(pkg, it.Methods.List) weights := make(map[string]int) weight := weightWidth for _, name := range methodNames { weights[name] = weight weight += weightWidth } c.methodWeight[iface] = weights } } } return true }) } // Complement for _, v1 := range c.methodWeight { for k2, w := range v1 { if v, found := c.methodWeight[k2]; found { for k3, v3 := range v { v1[k3] = (v3 / weightWidth) + w } } } } }) } func (c *Inspector) packageFromPath(p string) string { p = filepath.ToSlash(p) base := path.Base(p) if !strings.Contains(base, ".") { return base } return path.Base(strings.TrimSuffix(p, base)) } // Method holds enough information about it to recreate it. type Method struct { // The interface we extracted this method from. Owner reflect.Type // String version of the above, on the form PACKAGE.NAME, e.g. // page.Page OwnerName string // Method name. Name string // Imports needed to satisfy the method signature. Imports []string // Argument types, including any package prefix, e.g. string, int, interface{}, // net.Url In []string // Return types. Out []string } // Declaration creates a method declaration (without any body) for the given receiver. func (m Method) Declaration(receiver string) string { return fmt.Sprintf("func (%s %s) %s%s %s", receiverShort(receiver), receiver, m.Name, m.inStr(), m.outStr()) } // DeclarationNamed creates a method declaration (without any body) for the given receiver // with named return values. func (m Method) DeclarationNamed(receiver string) string { return fmt.Sprintf("func (%s %s) %s%s %s", receiverShort(receiver), receiver, m.Name, m.inStr(), m.outStrNamed()) } // Delegate creates a delegate call string. func (m Method) Delegate(receiver, delegate string) string { ret := "" if len(m.Out) > 0 { ret = "return " } return fmt.Sprintf("%s%s.%s.%s%s", ret, receiverShort(receiver), delegate, m.Name, m.inOutStr()) } func (m Method) String() string { return m.Name + m.inStr() + " " + m.outStr() + "\n" } func (m Method) inOutStr() string { if len(m.In) == 0 { return "()" } args := make([]string, len(m.In)) for i := range args { args[i] = fmt.Sprintf("arg%d", i) } return "(" + strings.Join(args, ", ") + ")" } func (m Method) inStr() string { if len(m.In) == 0 { return "()" } args := make([]string, len(m.In)) for i := range args { args[i] = fmt.Sprintf("arg%d %s", i, m.In[i]) } return "(" + strings.Join(args, ", ") + ")" } func (m Method) outStr() string { if len(m.Out) == 0 { return "" } if len(m.Out) == 1 { return m.Out[0] } return "(" + strings.Join(m.Out, ", ") + ")" } func (m Method) outStrNamed() string { if len(m.Out) == 0 { return "" } outs := make([]string, len(m.Out)) for i := range outs { outs[i] = fmt.Sprintf("o%d %s", i, m.Out[i]) } return "(" + strings.Join(outs, ", ") + ")" } // Methods represents a list of methods for one or more interfaces. // The order matches the defined order in their source file(s). type Methods []Method // Imports returns a sorted list of package imports needed to satisfy the // signatures of all methods. func (m Methods) Imports() []string { var pkgImports []string for _, method := range m { pkgImports = append(pkgImports, method.Imports...) } if len(pkgImports) > 0 { pkgImports = uniqueNonEmptyStrings(pkgImports) sort.Strings(pkgImports) } return pkgImports } // ToMarshalJSON creates a MarshalJSON method for these methods. Any method name // matching any of the regexps in excludes will be ignored. func (m Methods) ToMarshalJSON(receiver, pkgPath string, excludes ...string) (string, []string) { var sb strings.Builder r := receiverShort(receiver) what := firstToUpper(trimAsterisk(receiver)) pgkName := path.Base(pkgPath) fmt.Fprintf(&sb, "func Marshal%sToJSON(%s %s) ([]byte, error) {\n", what, r, receiver) var methods Methods excludeRes := make([]*regexp.Regexp, len(excludes)) for i, exclude := range excludes { excludeRes[i] = regexp.MustCompile(exclude) } for _, method := range m { // Exclude methods with arguments and incompatible return values if len(method.In) > 0 || len(method.Out) == 0 || len(method.Out) > 2 { continue } if len(method.Out) == 2 { if method.Out[1] != "error" { continue } } for _, re := range excludeRes { if re.MatchString(method.Name) { continue } } methods = append(methods, method) } for _, method := range methods { varn := varName(method.Name) if len(method.Out) == 1 { fmt.Fprintf(&sb, "\t%s := %s.%s()\n", varn, r, method.Name) } else { fmt.Fprintf(&sb, "\t%s, err := %s.%s()\n", varn, r, method.Name) fmt.Fprint(&sb, "\tif err != nil {\n\t\treturn nil, err\n\t}\n") } } fmt.Fprint(&sb, "\n\ts := struct {\n") for _, method := range methods { fmt.Fprintf(&sb, "\t\t%s %s\n", method.Name, typeName(method.Out[0], pgkName)) } fmt.Fprint(&sb, "\n\t}{\n") for _, method := range methods { varn := varName(method.Name) fmt.Fprintf(&sb, "\t\t%s: %s,\n", method.Name, varn) } fmt.Fprint(&sb, "\n\t}\n\n") fmt.Fprint(&sb, "\treturn json.Marshal(&s)\n}") pkgImports := append(methods.Imports(), "encoding/json") if pkgPath != "" { // Exclude self for i, pkgImp := range pkgImports { if pkgImp == pkgPath { pkgImports = slices.Delete(pkgImports, i, i+1) } } } return sb.String(), pkgImports } func collectMethodsRecursive(pkg string, f []*ast.Field) []string { var methodNames []string for _, m := range f { if m.Names != nil { methodNames = append(methodNames, m.Names[0].Name) continue } if ident, ok := m.Type.(*ast.Ident); ok && ident.Obj != nil { switch tt := ident.Obj.Decl.(*ast.TypeSpec).Type.(type) { case *ast.InterfaceType: // Embedded interface methodNames = append( methodNames, collectMethodsRecursive( pkg, tt.Methods.List)...) } } else { // Embedded, but in a different file/package. Return the // package.Name and deal with that later. name := packageName(m.Type) if !strings.Contains(name, ".") { // Assume current package name = pkg + "." + name } methodNames = append(methodNames, name) } } return methodNames } func firstToLower(name string) string { return strings.ToLower(name[:1]) + name[1:] } func firstToUpper(name string) string { return strings.ToUpper(name[:1]) + name[1:] } func packageName(e ast.Expr) string { switch tp := e.(type) { case *ast.Ident: return tp.Name case *ast.SelectorExpr: return fmt.Sprintf("%s.%s", packageName(tp.X), packageName(tp.Sel)) } return "" } func receiverShort(receiver string) string { return strings.ToLower(trimAsterisk(receiver))[:1] } func trimAsterisk(name string) string { return strings.TrimPrefix(name, "*") } func typeName(name, pkg string) string { return strings.TrimPrefix(name, pkg+".") } func uniqueNonEmptyStrings(s []string) []string { var unique []string set := map[string]any{} for _, val := range s { if val == "" { continue } if _, ok := set[val]; !ok { unique = append(unique, val) set[val] = val } } return unique } func varName(name string) string { name = firstToLower(name) // Adjust some reserved keywords, see https://golang.org/ref/spec#Keywords switch name { case "type": name = "typ" case "package": name = "pkg" // Not reserved, but syntax highlighters has it as a keyword. case "len": name = "length" } return name }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/watcher/batcher.go
watcher/batcher.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 watcher import ( "time" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/watcher/filenotify" ) // Batcher batches file watch events in a given interval. type Batcher struct { filenotify.FileWatcher ticker *time.Ticker done chan struct{} Events chan []fsnotify.Event // Events are returned on this channel } // New creates and starts a Batcher with the given time interval. // It will fall back to a poll based watcher if native isn't supported. // To always use polling, set poll to true. func New(intervalBatcher, intervalPoll time.Duration, poll bool) (*Batcher, error) { var err error var watcher filenotify.FileWatcher if poll { watcher = filenotify.NewPollingWatcher(intervalPoll) } else { watcher, err = filenotify.New(intervalPoll) } if err != nil { return nil, err } batcher := &Batcher{} batcher.FileWatcher = watcher batcher.ticker = time.NewTicker(intervalBatcher) batcher.done = make(chan struct{}, 1) batcher.Events = make(chan []fsnotify.Event, 1) go batcher.run() return batcher, nil } func (b *Batcher) run() { evs := make([]fsnotify.Event, 0) OuterLoop: for { select { case ev := <-b.FileWatcher.Events(): evs = append(evs, ev) case <-b.ticker.C: if len(evs) == 0 { continue } b.Events <- evs evs = make([]fsnotify.Event, 0) case <-b.done: break OuterLoop } } close(b.done) } // Close stops the watching of the files. func (b *Batcher) Close() { b.done <- struct{}{} b.FileWatcher.Close() b.ticker.Stop() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/watcher/filenotify/fsnotify.go
watcher/filenotify/fsnotify.go
package filenotify import "github.com/fsnotify/fsnotify" // fsNotifyWatcher wraps the fsnotify package to satisfy the FileNotifier interface type fsNotifyWatcher struct { *fsnotify.Watcher } // Events returns the fsnotify event channel receiver func (w *fsNotifyWatcher) Events() <-chan fsnotify.Event { return w.Watcher.Events } // Errors returns the fsnotify error channel receiver func (w *fsNotifyWatcher) Errors() <-chan error { return w.Watcher.Errors }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/watcher/filenotify/filenotify.go
watcher/filenotify/filenotify.go
// Package filenotify provides a mechanism for watching file(s) for changes. // Generally leans on fsnotify, but provides a poll-based notifier which fsnotify does not support. // These are wrapped up in a common interface so that either can be used interchangeably in your code. // // This package is adapted from https://github.com/moby/moby/tree/master/pkg/filenotify, Apache-2.0 License. // Hopefully this can be replaced with an external package sometime in the future, see https://github.com/fsnotify/fsnotify/issues/9 package filenotify import ( "time" "github.com/fsnotify/fsnotify" ) // FileWatcher is an interface for implementing file notification watchers type FileWatcher interface { Events() <-chan fsnotify.Event Errors() <-chan error Add(name string) error Remove(name string) error Close() error } // New tries to use an fs-event watcher, and falls back to the poller if there is an error func New(interval time.Duration) (FileWatcher, error) { if watcher, err := NewEventWatcher(); err == nil { return watcher, nil } return NewPollingWatcher(interval), nil } // NewPollingWatcher returns a poll-based file watcher func NewPollingWatcher(interval time.Duration) FileWatcher { return &filePoller{ interval: interval, done: make(chan struct{}), events: make(chan fsnotify.Event), errors: make(chan error), } } // NewEventWatcher returns an fs-event based file watcher func NewEventWatcher() (FileWatcher, error) { watcher, err := fsnotify.NewWatcher() if err != nil { return nil, err } return &fsNotifyWatcher{watcher}, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/watcher/filenotify/poller_test.go
watcher/filenotify/poller_test.go
package filenotify import ( "fmt" "os" "path/filepath" "runtime" "testing" "time" qt "github.com/frankban/quicktest" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/htesting" ) const ( subdir1 = "subdir1" subdir2 = "subdir2" watchWaitTime = 200 * time.Millisecond ) var ( isMacOs = runtime.GOOS == "darwin" isCI = htesting.IsCI() ) func TestPollerAddRemove(t *testing.T) { c := qt.New(t) w := NewPollingWatcher(watchWaitTime) c.Assert(w.Add("foo"), qt.Not(qt.IsNil)) c.Assert(w.Remove("foo"), qt.Not(qt.IsNil)) f, err := os.CreateTemp("", "asdf") if err != nil { t.Fatal(err) } c.Cleanup(func() { c.Assert(w.Close(), qt.IsNil) os.Remove(f.Name()) }) c.Assert(w.Add(f.Name()), qt.IsNil) c.Assert(w.Remove(f.Name()), qt.IsNil) } func TestPollerEvent(t *testing.T) { t.Skip("flaky test") // TODO(bep) c := qt.New(t) for _, poll := range []bool{true, false} { if !(poll || isMacOs) || isCI { // Only run the fsnotify tests on MacOS locally. continue } method := "fsnotify" if poll { method = "poll" } c.Run(fmt.Sprintf("%s, Watch dir", method), func(c *qt.C) { dir, w := preparePollTest(c, poll) subdir := filepath.Join(dir, subdir1) c.Assert(w.Add(subdir), qt.IsNil) filename := filepath.Join(subdir, "file1") // Write to one file. c.Assert(os.WriteFile(filename, []byte("changed"), 0o600), qt.IsNil) var expected []fsnotify.Event if poll { expected = append(expected, fsnotify.Event{Name: filename, Op: fsnotify.Write}) assertEvents(c, w, expected...) } else { // fsnotify sometimes emits Chmod before Write, // which is hard to test, so skip it here. drainEvents(c, w) } // Remove one file. filename = filepath.Join(subdir, "file2") c.Assert(os.Remove(filename), qt.IsNil) assertEvents(c, w, fsnotify.Event{Name: filename, Op: fsnotify.Remove}) // Add one file. filename = filepath.Join(subdir, "file3") c.Assert(os.WriteFile(filename, []byte("new"), 0o600), qt.IsNil) assertEvents(c, w, fsnotify.Event{Name: filename, Op: fsnotify.Create}) // Remove entire directory. subdir = filepath.Join(dir, subdir2) c.Assert(w.Add(subdir), qt.IsNil) c.Assert(os.RemoveAll(subdir), qt.IsNil) expected = expected[:0] // This looks like a bug in fsnotify on MacOS. There are // 3 files in this directory, yet we get Remove events // for one of them + the directory. if !poll { expected = append(expected, fsnotify.Event{Name: filepath.Join(subdir, "file2"), Op: fsnotify.Remove}) } expected = append(expected, fsnotify.Event{Name: subdir, Op: fsnotify.Remove}) assertEvents(c, w, expected...) }) c.Run(fmt.Sprintf("%s, Add should not trigger event", method), func(c *qt.C) { dir, w := preparePollTest(c, poll) subdir := filepath.Join(dir, subdir1) w.Add(subdir) assertEvents(c, w) // Create a new sub directory and add it to the watcher. subdir = filepath.Join(dir, subdir1, subdir2) c.Assert(os.Mkdir(subdir, 0o777), qt.IsNil) w.Add(subdir) // This should create only one event. assertEvents(c, w, fsnotify.Event{Name: subdir, Op: fsnotify.Create}) }) } } func TestPollerClose(t *testing.T) { c := qt.New(t) w := NewPollingWatcher(watchWaitTime) f1, err := os.CreateTemp("", "f1") c.Assert(err, qt.IsNil) defer os.Remove(f1.Name()) f2, err := os.CreateTemp("", "f2") c.Assert(err, qt.IsNil) filename1 := f1.Name() filename2 := f2.Name() f1.Close() f2.Close() c.Assert(w.Add(filename1), qt.IsNil) c.Assert(w.Add(filename2), qt.IsNil) c.Assert(w.Close(), qt.IsNil) c.Assert(w.Close(), qt.IsNil) c.Assert(os.WriteFile(filename1, []byte("new"), 0o600), qt.IsNil) c.Assert(os.WriteFile(filename2, []byte("new"), 0o600), qt.IsNil) // No more event as the watchers are closed. assertEvents(c, w) f2, err = os.CreateTemp("", "f2") c.Assert(err, qt.IsNil) defer os.Remove(f2.Name()) c.Assert(w.Add(f2.Name()), qt.Not(qt.IsNil)) } func TestCheckChange(t *testing.T) { c := qt.New(t) dir := prepareTestDirWithSomeFiles(c, "check-change") stat := func(s ...string) os.FileInfo { fi, err := os.Stat(filepath.Join(append([]string{dir}, s...)...)) c.Assert(err, qt.IsNil) return fi } f0, f1, f2 := stat(subdir2, "file0"), stat(subdir2, "file1"), stat(subdir2, "file2") d1 := stat(subdir1) // Note that on Windows, only the 0200 bit (owner writable) of mode is used. c.Assert(os.Chmod(filepath.Join(filepath.Join(dir, subdir2, "file1")), 0o400), qt.IsNil) f1_2 := stat(subdir2, "file1") c.Assert(os.WriteFile(filepath.Join(filepath.Join(dir, subdir2, "file2")), []byte("changed"), 0o600), qt.IsNil) f2_2 := stat(subdir2, "file2") c.Assert(checkChange(f0, nil), qt.Equals, fsnotify.Remove) c.Assert(checkChange(nil, f0), qt.Equals, fsnotify.Create) c.Assert(checkChange(f1, f1_2), qt.Equals, fsnotify.Chmod) c.Assert(checkChange(f2, f2_2), qt.Equals, fsnotify.Write) c.Assert(checkChange(nil, nil), qt.Equals, fsnotify.Op(0)) c.Assert(checkChange(d1, f1), qt.Equals, fsnotify.Op(0)) c.Assert(checkChange(f1, d1), qt.Equals, fsnotify.Op(0)) } func BenchmarkPoller(b *testing.B) { runBench := func(b *testing.B, item *itemToWatch) { b.ResetTimer() for b.Loop() { evs, err := item.checkForChanges() if err != nil { b.Fatal(err) } if len(evs) != 0 { b.Fatal("got events") } } } b.Run("Check for changes in dir", func(b *testing.B) { c := qt.New(b) dir := prepareTestDirWithSomeFiles(c, "bench-check") item, err := newItemToWatch(dir) c.Assert(err, qt.IsNil) runBench(b, item) }) b.Run("Check for changes in file", func(b *testing.B) { c := qt.New(b) dir := prepareTestDirWithSomeFiles(c, "bench-check-file") filename := filepath.Join(dir, subdir1, "file1") item, err := newItemToWatch(filename) c.Assert(err, qt.IsNil) runBench(b, item) }) } func prepareTestDirWithSomeFiles(c *qt.C, id string) string { dir := c.TB.TempDir() c.Assert(os.MkdirAll(filepath.Join(dir, subdir1), 0o777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(dir, subdir2), 0o777), qt.IsNil) for i := range 3 { c.Assert(os.WriteFile(filepath.Join(dir, subdir1, fmt.Sprintf("file%d", i)), []byte("hello1"), 0o600), qt.IsNil) } for i := range 3 { c.Assert(os.WriteFile(filepath.Join(dir, subdir2, fmt.Sprintf("file%d", i)), []byte("hello2"), 0o600), qt.IsNil) } c.Cleanup(func() { os.RemoveAll(dir) }) return dir } func preparePollTest(c *qt.C, poll bool) (string, FileWatcher) { var w FileWatcher if poll { w = NewPollingWatcher(watchWaitTime) } else { var err error w, err = NewEventWatcher() c.Assert(err, qt.IsNil) } dir := prepareTestDirWithSomeFiles(c, fmt.Sprint(poll)) c.Cleanup(func() { w.Close() }) return dir, w } func assertEvents(c *qt.C, w FileWatcher, evs ...fsnotify.Event) { c.Helper() i := 0 check := func() error { for { select { case got := <-w.Events(): if i > len(evs)-1 { return fmt.Errorf("got too many event(s): %q", got) } expected := evs[i] i++ if expected.Name != got.Name { return fmt.Errorf("got wrong filename, expected %q: %v", expected.Name, got.Name) } else if got.Op&expected.Op != expected.Op { return fmt.Errorf("got wrong event type, expected %q: %v", expected.Op, got.Op) } case e := <-w.Errors(): return fmt.Errorf("got unexpected error waiting for events %v", e) case <-time.After(watchWaitTime + (watchWaitTime / 2)): return nil } } } c.Assert(check(), qt.IsNil) c.Assert(i, qt.Equals, len(evs)) } func drainEvents(c *qt.C, w FileWatcher) { c.Helper() check := func() error { for { select { case <-w.Events(): case e := <-w.Errors(): return fmt.Errorf("got unexpected error waiting for events %v", e) case <-time.After(watchWaitTime * 2): return nil } } } c.Assert(check(), qt.IsNil) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/watcher/filenotify/poller.go
watcher/filenotify/poller.go
package filenotify import ( "errors" "fmt" "os" "path/filepath" "sync" "time" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/common/herrors" ) var ( // errPollerClosed is returned when the poller is closed errPollerClosed = errors.New("poller is closed") // errNoSuchWatch is returned when trying to remove a watch that doesn't exist errNoSuchWatch = errors.New("watch does not exist") ) // filePoller is used to poll files for changes, especially in cases where fsnotify // can't be run (e.g. when inotify handles are exhausted) // filePoller satisfies the FileWatcher interface type filePoller struct { // the duration between polls. interval time.Duration // watches is the list of files currently being polled, close the associated channel to stop the watch watches map[string]struct{} // Will be closed when done. done chan struct{} // events is the channel to listen to for watch events events chan fsnotify.Event // errors is the channel to listen to for watch errors errors chan error // mu locks the poller for modification mu sync.Mutex // closed is used to specify when the poller has already closed closed bool } // Add adds a filename to the list of watches // once added the file is polled for changes in a separate goroutine func (w *filePoller) Add(name string) error { w.mu.Lock() defer w.mu.Unlock() if w.closed { return errPollerClosed } item, err := newItemToWatch(name) if err != nil { return err } if item.left.FileInfo == nil { return os.ErrNotExist } if w.watches == nil { w.watches = make(map[string]struct{}) } if _, exists := w.watches[name]; exists { return fmt.Errorf("watch exists") } w.watches[name] = struct{}{} go w.watch(item) return nil } // Remove stops and removes watch with the specified name func (w *filePoller) Remove(name string) error { w.mu.Lock() defer w.mu.Unlock() return w.remove(name) } func (w *filePoller) remove(name string) error { if w.closed { return errPollerClosed } _, exists := w.watches[name] if !exists { return errNoSuchWatch } delete(w.watches, name) return nil } // Events returns the event channel // This is used for notifications on events about watched files func (w *filePoller) Events() <-chan fsnotify.Event { return w.events } // Errors returns the errors channel // This is used for notifications about errors on watched files func (w *filePoller) Errors() <-chan error { return w.errors } // Close closes the poller // All watches are stopped, removed, and the poller cannot be added to func (w *filePoller) Close() error { w.mu.Lock() defer w.mu.Unlock() if w.closed { return nil } w.closed = true close(w.done) for name := range w.watches { w.remove(name) } return nil } // sendEvent publishes the specified event to the events channel func (w *filePoller) sendEvent(e fsnotify.Event) error { select { case w.events <- e: case <-w.done: return fmt.Errorf("closed") } return nil } // sendErr publishes the specified error to the errors channel func (w *filePoller) sendErr(e error) error { select { case w.errors <- e: case <-w.done: return fmt.Errorf("closed") } return nil } // watch watches item for changes until done is closed. func (w *filePoller) watch(item *itemToWatch) { ticker := time.NewTicker(w.interval) defer ticker.Stop() for { select { case <-ticker.C: case <-w.done: return } evs, err := item.checkForChanges() if err != nil { if err := w.sendErr(err); err != nil { return } } item.left, item.right = item.right, item.left for _, ev := range evs { if err := w.sendEvent(ev); err != nil { return } } } } // recording records the state of a file or a dir. type recording struct { os.FileInfo // Set if FileInfo is a dir. entries map[string]os.FileInfo } func (r *recording) clear() { r.FileInfo = nil if r.entries != nil { for k := range r.entries { delete(r.entries, k) } } } func (r *recording) record(filename string) error { r.clear() fi, err := os.Stat(filename) if err != nil && !herrors.IsNotExist(err) { return err } if fi == nil { return nil } r.FileInfo = fi // If fi is a dir, we watch the files inside that directory (not recursively). // This matches the behavior of fsnotity. if fi.IsDir() { f, err := os.Open(filename) if err != nil { if herrors.IsNotExist(err) { return nil } return err } defer f.Close() fis, err := f.Readdir(-1) if err != nil { if herrors.IsNotExist(err) { return nil } return err } for _, fi := range fis { r.entries[fi.Name()] = fi } } return nil } // itemToWatch may be a file or a dir. type itemToWatch struct { // Full path to the filename. filename string // Snapshots of the stat state of this file or dir. left *recording right *recording } func newItemToWatch(filename string) (*itemToWatch, error) { r := &recording{ entries: make(map[string]os.FileInfo), } err := r.record(filename) if err != nil { return nil, err } return &itemToWatch{filename: filename, left: r}, nil } func (item *itemToWatch) checkForChanges() ([]fsnotify.Event, error) { if item.right == nil { item.right = &recording{ entries: make(map[string]os.FileInfo), } } err := item.right.record(item.filename) if err != nil && !herrors.IsNotExist(err) { return nil, err } dirOp := checkChange(item.left.FileInfo, item.right.FileInfo) if dirOp != 0 { evs := []fsnotify.Event{{Op: dirOp, Name: item.filename}} return evs, nil } if item.left.FileInfo == nil || !item.left.IsDir() { // Done. return nil, nil } leftIsIn := false left, right := item.left.entries, item.right.entries if len(right) > len(left) { left, right = right, left leftIsIn = true } var evs []fsnotify.Event for name, fi1 := range left { fi2 := right[name] fil, fir := fi1, fi2 if leftIsIn { fil, fir = fir, fil } op := checkChange(fil, fir) if op != 0 { evs = append(evs, fsnotify.Event{Op: op, Name: filepath.Join(item.filename, name)}) } } return evs, nil } func checkChange(fi1, fi2 os.FileInfo) fsnotify.Op { if fi1 == nil && fi2 != nil { return fsnotify.Create } if fi1 != nil && fi2 == nil { return fsnotify.Remove } if fi1 == nil && fi2 == nil { return 0 } if fi1.IsDir() || fi2.IsDir() { return 0 } if fi1.Mode() != fi2.Mode() { return fsnotify.Chmod } if fi1.ModTime() != fi2.ModTime() || fi1.Size() != fi2.Size() { return fsnotify.Write } return 0 }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/docs.go
cache/docs.go
// Package cache contains the different cache implementations. package cache
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/filecache/filecache_test.go
cache/filecache/filecache_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package filecache_test import ( "errors" "fmt" "io" "strings" "sync" "testing" "time" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/spf13/afero" qt "github.com/frankban/quicktest" ) func TestFileCache(t *testing.T) { t.Parallel() c := qt.New(t) tempWorkingDir := t.TempDir() tempCacheDir := t.TempDir() osfs := afero.NewOsFs() for _, test := range []struct { cacheDir string workingDir string }{ // Run with same dirs twice to make sure that works. {tempCacheDir, tempWorkingDir}, {tempCacheDir, tempWorkingDir}, } { configStr := ` workingDir = "WORKING_DIR" resourceDir = "resources" cacheDir = "CACHEDIR" contentDir = "content" dataDir = "data" i18nDir = "i18n" layoutDir = "layouts" assetDir = "assets" archeTypedir = "archetypes" [caches] [caches.getJSON] maxAge = "10h" dir = ":cacheDir/c" ` winPathSep := "\\\\" replacer := strings.NewReplacer("CACHEDIR", test.cacheDir, "WORKING_DIR", test.workingDir) configStr = replacer.Replace(configStr) configStr = strings.Replace(configStr, "\\", winPathSep, -1) p := newPathsSpec(t, osfs, configStr) caches, err := filecache.NewCaches(p) c.Assert(err, qt.IsNil) cache := caches.Get("GetJSON") c.Assert(cache, qt.Not(qt.IsNil)) cache = caches.Get("Images") c.Assert(cache, qt.Not(qt.IsNil)) rf := func(s string) func() (io.ReadCloser, error) { return func() (io.ReadCloser, error) { return struct { io.ReadSeeker io.Closer }{ strings.NewReader(s), io.NopCloser(nil), }, nil } } bf := func() ([]byte, error) { return []byte("bcd"), nil } for _, ca := range []*filecache.Cache{caches.ImageCache(), caches.AssetsCache(), caches.GetJSONCache(), caches.GetCSVCache()} { for range 2 { info, r, err := ca.GetOrCreate("a", rf("abc")) c.Assert(err, qt.IsNil) c.Assert(r, qt.Not(qt.IsNil)) c.Assert(info.Name, qt.Equals, "a") b, _ := io.ReadAll(r) r.Close() c.Assert(string(b), qt.Equals, "abc") info, b, err = ca.GetOrCreateBytes("b", bf) c.Assert(err, qt.IsNil) c.Assert(r, qt.Not(qt.IsNil)) c.Assert(info.Name, qt.Equals, "b") c.Assert(string(b), qt.Equals, "bcd") _, b, err = ca.GetOrCreateBytes("a", bf) c.Assert(err, qt.IsNil) c.Assert(string(b), qt.Equals, "abc") _, r, err = ca.GetOrCreate("a", rf("bcd")) c.Assert(err, qt.IsNil) b, _ = io.ReadAll(r) r.Close() c.Assert(string(b), qt.Equals, "abc") } } c.Assert(caches.Get("getJSON"), qt.Not(qt.IsNil)) info, w, err := caches.ImageCache().WriteCloser("mykey") c.Assert(err, qt.IsNil) c.Assert(info.Name, qt.Equals, "mykey") io.WriteString(w, "Hugo is great!") w.Close() c.Assert(caches.ImageCache().GetString("mykey"), qt.Equals, "Hugo is great!") info, r, err := caches.ImageCache().Get("mykey") c.Assert(err, qt.IsNil) c.Assert(r, qt.Not(qt.IsNil)) c.Assert(info.Name, qt.Equals, "mykey") b, _ := io.ReadAll(r) r.Close() c.Assert(string(b), qt.Equals, "Hugo is great!") info, b, err = caches.ImageCache().GetBytes("mykey") c.Assert(err, qt.IsNil) c.Assert(info.Name, qt.Equals, "mykey") c.Assert(string(b), qt.Equals, "Hugo is great!") } } func TestFileCacheConcurrent(t *testing.T) { t.Parallel() c := qt.New(t) configStr := ` resourceDir = "myresources" contentDir = "content" dataDir = "data" i18nDir = "i18n" layoutDir = "layouts" assetDir = "assets" archeTypedir = "archetypes" [caches] [caches.getjson] maxAge = "1s" dir = "/cache/c" ` p := newPathsSpec(t, afero.NewMemMapFs(), configStr) caches, err := filecache.NewCaches(p) c.Assert(err, qt.IsNil) const cacheName = "getjson" filenameData := func(i int) (string, string) { data := fmt.Sprintf("data: %d", i) filename := fmt.Sprintf("file%d", i) return filename, data } var wg sync.WaitGroup for i := range 50 { wg.Add(1) go func(i int) { defer wg.Done() for range 20 { ca := caches.Get(cacheName) c.Assert(ca, qt.Not(qt.IsNil)) filename, data := filenameData(i) _, r, err := ca.GetOrCreate(filename, func() (io.ReadCloser, error) { return hugio.ToReadCloser(strings.NewReader(data)), nil }) c.Assert(err, qt.IsNil) b, _ := io.ReadAll(r) r.Close() c.Assert(string(b), qt.Equals, data) // Trigger some expiration. time.Sleep(50 * time.Millisecond) } }(i) } wg.Wait() } func TestFileCacheReadOrCreateErrorInRead(t *testing.T) { t.Parallel() c := qt.New(t) var result string rf := func(failLevel int) func(info filecache.ItemInfo, r io.ReadSeeker) error { return func(info filecache.ItemInfo, r io.ReadSeeker) error { if failLevel > 0 { if failLevel > 1 { return filecache.ErrFatal } return errors.New("fail") } b, _ := io.ReadAll(r) result = string(b) return nil } } bf := func(s string) func(info filecache.ItemInfo, w io.WriteCloser) error { return func(info filecache.ItemInfo, w io.WriteCloser) error { defer w.Close() result = s _, err := w.Write([]byte(s)) return err } } cache := filecache.NewCache(afero.NewMemMapFs(), 100*time.Hour, "") const id = "a32" _, err := cache.ReadOrCreate(id, rf(0), bf("v1")) c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, "v1") _, err = cache.ReadOrCreate(id, rf(0), bf("v2")) c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, "v1") _, err = cache.ReadOrCreate(id, rf(1), bf("v3")) c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, "v3") _, err = cache.ReadOrCreate(id, rf(2), bf("v3")) c.Assert(err, qt.Equals, filecache.ErrFatal) } func newPathsSpec(t *testing.T, fs afero.Fs, configStr string) *helpers.PathSpec { c := qt.New(t) cfg, err := config.FromConfigString(configStr, "toml") c.Assert(err, qt.IsNil) acfg := testconfig.GetTestConfig(fs, cfg) p, err := helpers.NewPathSpec(hugofs.NewFrom(fs, acfg.BaseConfig()), acfg, nil, nil) c.Assert(err, qt.IsNil) return p }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/filecache/filecache_integration_test.go
cache/filecache/filecache_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package filecache_test import ( "path/filepath" "testing" "time" "github.com/bep/logg" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugolib" ) // See issue #10781. That issue wouldn't have been triggered if we kept // the empty root directories (e.g. _resources/gen/images). // It's still an upstream Go issue that we also need to handle, but // this is a test for the first part. func TestPruneShouldPreserveEmptyCacheRoots(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" -- content/_index.md -- --- title: "Home" --- ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t, TxtarString: files, RunGC: true, NeedsOsFS: true}, ).Build() _, err := b.H.BaseFs.ResourcesCache.Stat(filepath.Join("_gen", "images")) b.Assert(err, qt.IsNil) } func TestPruneImages(t *testing.T) { if htesting.IsCI() { // TODO(bep) t.Skip("skip flaky test on CI server") } t.Skip("skip flaky test") files := ` -- hugo.toml -- baseURL = "https://example.com" [caches] [caches.images] maxAge = "200ms" dir = ":resourceDir/_gen" -- content/_index.md -- --- title: "Home" --- -- assets/a/pixel.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- layouts/home.html -- {{ warnf "HOME!" }} {{ $img := resources.GetMatch "**.png" }} {{ $img = $img.Resize "3x3" }} {{ $img.RelPermalink }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t, TxtarString: files, Running: true, RunGC: true, NeedsOsFS: true, LogLevel: logg.LevelInfo}, ).Build() b.Assert(b.GCCount, qt.Equals, 0) b.Assert(b.H, qt.IsNotNil) imagesCacheDir := filepath.Join("_gen", "images") _, err := b.H.BaseFs.ResourcesCache.Stat(imagesCacheDir) b.Assert(err, qt.IsNil) // TODO(bep) we need a way to test full rebuilds. // For now, just sleep a little so the cache elements expires. time.Sleep(500 * time.Millisecond) b.RenameFile("assets/a/pixel.png", "assets/b/pixel2.png").Build() b.Assert(b.GCCount, qt.Equals, 1) // Build it again to GC the empty a dir. b.Build() _, err = b.H.BaseFs.ResourcesCache.Stat(filepath.Join(imagesCacheDir, "a")) b.Assert(err, qt.Not(qt.IsNil)) _, err = b.H.BaseFs.ResourcesCache.Stat(imagesCacheDir) b.Assert(err, qt.IsNil) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/filecache/filecache_config_test.go
cache/filecache/filecache_config_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package filecache_test import ( "path/filepath" "runtime" "testing" "time" "github.com/spf13/afero" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/testconfig" qt "github.com/frankban/quicktest" ) func TestDecodeConfig(t *testing.T) { t.Parallel() c := qt.New(t) configStr := ` resourceDir = "myresources" contentDir = "content" dataDir = "data" i18nDir = "i18n" layoutDir = "layouts" assetDir = "assets" archetypeDir = "archetypes" [caches] [caches.getJSON] maxAge = "10m" dir = "/path/to/c1" [caches.getCSV] maxAge = "11h" dir = "/path/to/c2" [caches.images] dir = "/path/to/c3" [caches.getResource] dir = "/path/to/c4" ` cfg, err := config.FromConfigString(configStr, "toml") c.Assert(err, qt.IsNil) fs := afero.NewMemMapFs() decoded := testconfig.GetTestConfigs(fs, cfg).Base.Caches c.Assert(len(decoded), qt.Equals, 7) c2 := decoded["getcsv"] c.Assert(c2.MaxAge.String(), qt.Equals, "11h0m0s") c.Assert(c2.DirCompiled, qt.Equals, filepath.FromSlash("/path/to/c2/filecache/getcsv")) c3 := decoded["images"] c.Assert(c3.MaxAge, qt.Equals, time.Duration(-1)) c.Assert(c3.DirCompiled, qt.Equals, filepath.FromSlash("/path/to/c3/filecache/images")) c4 := decoded["getresource"] c.Assert(c4.MaxAge, qt.Equals, time.Duration(-1)) c.Assert(c4.DirCompiled, qt.Equals, filepath.FromSlash("/path/to/c4/filecache/getresource")) } func TestDecodeConfigIgnoreCache(t *testing.T) { t.Parallel() c := qt.New(t) configStr := ` resourceDir = "myresources" contentDir = "content" dataDir = "data" i18nDir = "i18n" layoutDir = "layouts" assetDir = "assets" archeTypedir = "archetypes" ignoreCache = true [caches] [caches.getJSON] maxAge = 1234 dir = "/path/to/c1" [caches.getCSV] maxAge = 3456 dir = "/path/to/c2" [caches.images] dir = "/path/to/c3" [caches.getResource] dir = "/path/to/c4" ` cfg, err := config.FromConfigString(configStr, "toml") c.Assert(err, qt.IsNil) fs := afero.NewMemMapFs() decoded := testconfig.GetTestConfigs(fs, cfg).Base.Caches c.Assert(len(decoded), qt.Equals, 7) for _, v := range decoded { c.Assert(v.MaxAge, qt.Equals, time.Duration(0)) } } func TestDecodeConfigDefault(t *testing.T) { c := qt.New(t) cfg := config.New() if runtime.GOOS == "windows" { cfg.Set("resourceDir", "c:\\cache\\resources") cfg.Set("cacheDir", "c:\\cache\\thecache") } else { cfg.Set("resourceDir", "/cache/resources") cfg.Set("cacheDir", "/cache/thecache") } cfg.Set("workingDir", filepath.FromSlash("/my/cool/hugoproject")) fs := afero.NewMemMapFs() decoded := testconfig.GetTestConfigs(fs, cfg).Base.Caches c.Assert(len(decoded), qt.Equals, 7) imgConfig := decoded[filecache.CacheKeyImages] jsonConfig := decoded[filecache.CacheKeyGetJSON] if runtime.GOOS == "windows" { c.Assert(imgConfig.DirCompiled, qt.Equals, filepath.FromSlash("_gen/images")) } else { c.Assert(imgConfig.DirCompiled, qt.Equals, "_gen/images") c.Assert(jsonConfig.DirCompiled, qt.Equals, "/cache/thecache/hugoproject/filecache/getjson") } c.Assert(imgConfig.IsResourceDir, qt.Equals, true) c.Assert(jsonConfig.IsResourceDir, qt.Equals, false) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/filecache/filecache_config.go
cache/filecache/filecache_config.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 filecache provides a file based cache for Hugo. package filecache import ( "errors" "fmt" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config" "github.com/mitchellh/mapstructure" "github.com/spf13/afero" ) const ( resourcesGenDir = ":resourceDir/_gen" cacheDirProject = ":cacheDir/:project" ) var defaultCacheConfig = FileCacheConfig{ MaxAge: -1, // Never expire Dir: cacheDirProject, } const ( CacheKeyGetJSON = "getjson" CacheKeyGetCSV = "getcsv" CacheKeyImages = "images" CacheKeyAssets = "assets" CacheKeyModules = "modules" CacheKeyGetResource = "getresource" CacheKeyMisc = "misc" ) type Configs map[string]FileCacheConfig // CacheDirModules returns the compiled path to the modules cache. // For internal use. func (c Configs) CacheDirModules() string { return c[CacheKeyModules].DirCompiled } // CacheDirMisc returns the compiled path to the misc cache. // For internal use. func (c Configs) CacheDirMisc() string { return c[CacheKeyMisc].DirCompiled } var defaultCacheConfigs = Configs{ CacheKeyModules: { MaxAge: -1, Dir: ":cacheDir/modules", }, CacheKeyGetJSON: defaultCacheConfig, CacheKeyGetCSV: defaultCacheConfig, CacheKeyImages: { MaxAge: -1, Dir: resourcesGenDir, }, CacheKeyAssets: { MaxAge: -1, Dir: resourcesGenDir, }, CacheKeyGetResource: { MaxAge: -1, // Never expire Dir: cacheDirProject, }, CacheKeyMisc: { MaxAge: -1, Dir: cacheDirProject, }, } type FileCacheConfig struct { // Max age of cache entries in this cache. Any items older than this will // be removed and not returned from the cache. // A negative value means forever, 0 means cache is disabled. // Hugo is lenient with what types it accepts here, but we recommend using // a duration string, a sequence of decimal numbers, each with optional fraction and a unit suffix, // such as "300ms", "1.5h" or "2h45m". // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". MaxAge time.Duration // The directory where files are stored. Dir string DirCompiled string `json:"-"` // Will resources/_gen will get its own composite filesystem that // also checks any theme. IsResourceDir bool `json:"-"` } // GetJSONCache gets the file cache for getJSON. func (f Caches) GetJSONCache() *Cache { return f[CacheKeyGetJSON] } // GetCSVCache gets the file cache for getCSV. func (f Caches) GetCSVCache() *Cache { return f[CacheKeyGetCSV] } // ImageCache gets the file cache for processed images. func (f Caches) ImageCache() *Cache { return f[CacheKeyImages] } // ModulesCache gets the file cache for Hugo Modules. func (f Caches) ModulesCache() *Cache { return f[CacheKeyModules] } // AssetsCache gets the file cache for assets (processed resources, SCSS etc.). func (f Caches) AssetsCache() *Cache { return f[CacheKeyAssets] } // MiscCache gets the file cache for miscellaneous stuff. func (f Caches) MiscCache() *Cache { return f[CacheKeyMisc] } // GetResourceCache gets the file cache for remote resources. func (f Caches) GetResourceCache() *Cache { return f[CacheKeyGetResource] } func DecodeConfig(fs afero.Fs, bcfg config.BaseConfig, m map[string]any) (Configs, error) { c := make(Configs) valid := make(map[string]bool) // Add defaults for k, v := range defaultCacheConfigs { c[k] = v valid[k] = true } _, isOsFs := fs.(*afero.OsFs) for k, v := range m { if _, ok := v.(maps.Params); !ok { continue } cc := defaultCacheConfig dc := &mapstructure.DecoderConfig{ Result: &cc, DecodeHook: mapstructure.StringToTimeDurationHookFunc(), WeaklyTypedInput: true, } decoder, err := mapstructure.NewDecoder(dc) if err != nil { return c, err } if err := decoder.Decode(v); err != nil { return nil, fmt.Errorf("failed to decode filecache config: %w", err) } if cc.Dir == "" { return c, errors.New("must provide cache Dir") } name := strings.ToLower(k) if !valid[name] { return nil, fmt.Errorf("%q is not a valid cache name", name) } c[name] = cc } for k, v := range c { dir := filepath.ToSlash(filepath.Clean(v.Dir)) hadSlash := strings.HasPrefix(dir, "/") parts := strings.Split(dir, "/") for i, part := range parts { if strings.HasPrefix(part, ":") { resolved, isResource, err := resolveDirPlaceholder(fs, bcfg, part) if err != nil { return c, err } if isResource { v.IsResourceDir = true } parts[i] = resolved } } dir = path.Join(parts...) if hadSlash { dir = "/" + dir } v.DirCompiled = filepath.Clean(filepath.FromSlash(dir)) if !v.IsResourceDir { if isOsFs && !filepath.IsAbs(v.DirCompiled) { return c, fmt.Errorf("%q must resolve to an absolute directory", v.DirCompiled) } // Avoid cache in root, e.g. / (Unix) or c:\ (Windows) if len(strings.TrimPrefix(v.DirCompiled, filepath.VolumeName(v.DirCompiled))) == 1 { return c, fmt.Errorf("%q is a root folder and not allowed as cache dir", v.DirCompiled) } } if !strings.HasPrefix(v.DirCompiled, "_gen") { // We do cache eviction (file removes) and since the user can set // his/hers own cache directory, we really want to make sure // we do not delete any files that do not belong to this cache. // We do add the cache name as the root, but this is an extra safe // guard. We skip the files inside /resources/_gen/ because // that would be breaking. v.DirCompiled = filepath.Join(v.DirCompiled, FilecacheRootDirname, k) } else { v.DirCompiled = filepath.Join(v.DirCompiled, k) } c[k] = v } return c, nil } // Resolves :resourceDir => /myproject/resources etc., :cacheDir => ... func resolveDirPlaceholder(fs afero.Fs, bcfg config.BaseConfig, placeholder string) (cacheDir string, isResource bool, err error) { switch strings.ToLower(placeholder) { case ":resourcedir": return "", true, nil case ":cachedir": return bcfg.CacheDir, false, nil case ":project": return filepath.Base(bcfg.WorkingDir), false, nil } return "", false, fmt.Errorf("%q is not a valid placeholder (valid values are :cacheDir or :resourceDir)", placeholder) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/filecache/filecache_pruner_test.go
cache/filecache/filecache_pruner_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package filecache_test import ( "fmt" "testing" "time" "github.com/gohugoio/hugo/cache/filecache" "github.com/spf13/afero" qt "github.com/frankban/quicktest" ) func TestPrune(t *testing.T) { t.Parallel() c := qt.New(t) configStr := ` resourceDir = "myresources" contentDir = "content" dataDir = "data" i18nDir = "i18n" layoutDir = "layouts" assetDir = "assets" archeTypedir = "archetypes" [caches] [caches.getjson] maxAge = "200ms" dir = "/cache/c" [caches.getcsv] maxAge = "200ms" dir = "/cache/d" [caches.assets] maxAge = "200ms" dir = ":resourceDir/_gen" [caches.images] maxAge = "200ms" dir = ":resourceDir/_gen" ` for _, name := range []string{filecache.CacheKeyGetCSV, filecache.CacheKeyGetJSON, filecache.CacheKeyAssets, filecache.CacheKeyImages} { msg := qt.Commentf("cache: %s", name) p := newPathsSpec(t, afero.NewMemMapFs(), configStr) caches, err := filecache.NewCaches(p) c.Assert(err, qt.IsNil) cache := caches[name] for i := range 10 { id := fmt.Sprintf("i%d", i) cache.GetOrCreateBytes(id, func() ([]byte, error) { return []byte("abc"), nil }) if i == 4 { // This will expire the first 5 time.Sleep(201 * time.Millisecond) } } count, err := caches.Prune() c.Assert(err, qt.IsNil) c.Assert(count, qt.Equals, 5, msg) for i := range 10 { id := fmt.Sprintf("i%d", i) v := cache.GetString(id) if i < 5 { c.Assert(v, qt.Equals, "") } else { c.Assert(v, qt.Equals, "abc") } } caches, err = filecache.NewCaches(p) c.Assert(err, qt.IsNil) cache = caches[name] // Touch one and then prune. cache.GetOrCreateBytes("i5", func() ([]byte, error) { return []byte("abc"), nil }) count, err = caches.Prune() c.Assert(err, qt.IsNil) c.Assert(count, qt.Equals, 4) // Now only the i5 should be left. for i := range 10 { id := fmt.Sprintf("i%d", i) v := cache.GetString(id) if i != 5 { c.Assert(v, qt.Equals, "") } else { c.Assert(v, qt.Equals, "abc") } } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/filecache/filecache.go
cache/filecache/filecache.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package filecache import ( "bytes" "errors" "io" "os" "path/filepath" "strings" "sync" "time" "github.com/gohugoio/httpcache" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/helpers" "github.com/BurntSushi/locker" "github.com/spf13/afero" ) // ErrFatal can be used to signal an unrecoverable error. var ErrFatal = errors.New("fatal filecache error") const ( FilecacheRootDirname = "filecache" ) // Cache caches a set of files in a directory. This is usually a file on // disk, but since this is backed by an Afero file system, it can be anything. type Cache struct { Fs afero.Fs // Max age for items in this cache. Negative duration means forever, // 0 is effectively turning this cache off. maxAge time.Duration // When set, we just remove this entire root directory on expiration. pruneAllRootDir string nlocker *lockTracker initOnce sync.Once initErr error } type lockTracker struct { seenMu sync.RWMutex seen map[string]struct{} *locker.Locker } // Lock tracks the ids in use. We use this information to do garbage collection // after a Hugo build. func (l *lockTracker) Lock(id string) { l.seenMu.RLock() if _, seen := l.seen[id]; !seen { l.seenMu.RUnlock() l.seenMu.Lock() l.seen[id] = struct{}{} l.seenMu.Unlock() } else { l.seenMu.RUnlock() } l.Locker.Lock(id) } // ItemInfo contains info about a cached file. type ItemInfo struct { // This is the file's name relative to the cache's filesystem. Name string } // NewCache creates a new file cache with the given filesystem and max age. func NewCache(fs afero.Fs, maxAge time.Duration, pruneAllRootDir string) *Cache { return &Cache{ Fs: fs, nlocker: &lockTracker{Locker: locker.NewLocker(), seen: make(map[string]struct{})}, maxAge: maxAge, pruneAllRootDir: pruneAllRootDir, } } // lockedFile is a file with a lock that is released on Close. type lockedFile struct { afero.File unlock func() } func (l *lockedFile) Close() error { defer l.unlock() return l.File.Close() } func (c *Cache) init() error { c.initOnce.Do(func() { // Create the base dir if it does not exist. if err := c.Fs.MkdirAll("", 0o777); err != nil && !os.IsExist(err) { c.initErr = err } }) return c.initErr } // WriteCloser returns a transactional writer into the cache. // It's important that it's closed when done. func (c *Cache) WriteCloser(id string) (ItemInfo, io.WriteCloser, error) { if err := c.init(); err != nil { return ItemInfo{}, nil, err } id = cleanID(id) c.nlocker.Lock(id) info := ItemInfo{Name: id} f, err := helpers.OpenFileForWriting(c.Fs, id) if err != nil { c.nlocker.Unlock(id) return info, nil, err } return info, &lockedFile{ File: f, unlock: func() { c.nlocker.Unlock(id) }, }, nil } // ReadOrCreate tries to lookup the file in cache. // If found, it is passed to read and then closed. // If not found a new file is created and passed to create, which should close // it when done. func (c *Cache) ReadOrCreate(id string, read func(info ItemInfo, r io.ReadSeeker) error, create func(info ItemInfo, w io.WriteCloser) error, ) (info ItemInfo, err error) { if err := c.init(); err != nil { return ItemInfo{}, err } id = cleanID(id) c.nlocker.Lock(id) defer c.nlocker.Unlock(id) info = ItemInfo{Name: id} if r := c.getOrRemove(id); r != nil { err = read(info, r) defer r.Close() if err == nil || err == ErrFatal { // See https://github.com/gohugoio/hugo/issues/6401 // To recover from file corruption we handle read errors // as the cache item was not found. // Any file permission issue will also fail in the next step. return } } f, err := helpers.OpenFileForWriting(c.Fs, id) if err != nil { return } err = create(info, f) return } // NamedLock locks the given id. The lock is released when the returned function is called. func (c *Cache) NamedLock(id string) func() { id = cleanID(id) c.nlocker.Lock(id) return func() { c.nlocker.Unlock(id) } } // GetOrCreate tries to get the file with the given id from cache. If not found or expired, create will // be invoked and the result cached. // This method is protected by a named lock using the given id as identifier. func (c *Cache) GetOrCreate(id string, create func() (io.ReadCloser, error)) (ItemInfo, io.ReadCloser, error) { if err := c.init(); err != nil { return ItemInfo{}, nil, err } id = cleanID(id) c.nlocker.Lock(id) defer c.nlocker.Unlock(id) info := ItemInfo{Name: id} if r := c.getOrRemove(id); r != nil { return info, r, nil } var ( r io.ReadCloser err error ) r, err = create() if err != nil { return info, nil, err } if c.maxAge == 0 { // No caching. return info, hugio.ToReadCloser(r), nil } var buff bytes.Buffer return info, hugio.ToReadCloser(&buff), c.writeReader(id, io.TeeReader(r, &buff)) } func (c *Cache) writeReader(id string, r io.Reader) error { dir := filepath.Dir(id) if dir != "" { _ = c.Fs.MkdirAll(dir, 0o777) } f, err := c.Fs.Create(id) if err != nil { return err } defer f.Close() _, _ = io.Copy(f, r) return nil } // GetOrCreateBytes is the same as GetOrCreate, but produces a byte slice. func (c *Cache) GetOrCreateBytes(id string, create func() ([]byte, error)) (ItemInfo, []byte, error) { if err := c.init(); err != nil { return ItemInfo{}, nil, err } id = cleanID(id) c.nlocker.Lock(id) defer c.nlocker.Unlock(id) info := ItemInfo{Name: id} if r := c.getOrRemove(id); r != nil { defer r.Close() b, err := io.ReadAll(r) return info, b, err } var ( b []byte err error ) b, err = create() if err != nil { return info, nil, err } if c.maxAge == 0 { return info, b, nil } if err := c.writeReader(id, bytes.NewReader(b)); err != nil { return info, nil, err } return info, b, nil } // GetBytes gets the file content with the given id from the cache, nil if none found. func (c *Cache) GetBytes(id string) (ItemInfo, []byte, error) { if err := c.init(); err != nil { return ItemInfo{}, nil, err } id = cleanID(id) c.nlocker.Lock(id) defer c.nlocker.Unlock(id) info := ItemInfo{Name: id} if r := c.getOrRemove(id); r != nil { defer r.Close() b, err := io.ReadAll(r) return info, b, err } return info, nil, nil } // Get gets the file with the given id from the cache, nil if none found. func (c *Cache) Get(id string) (ItemInfo, io.ReadCloser, error) { if err := c.init(); err != nil { return ItemInfo{}, nil, err } id = cleanID(id) c.nlocker.Lock(id) defer c.nlocker.Unlock(id) info := ItemInfo{Name: id} r := c.getOrRemove(id) return info, r, nil } // getOrRemove gets the file with the given id. If it's expired, it will // be removed. func (c *Cache) getOrRemove(id string) hugio.ReadSeekCloser { if c.maxAge == 0 { // No caching. return nil } if removed, err := c.removeIfExpired(id); err != nil || removed { return nil } f, err := c.Fs.Open(id) if err != nil { return nil } return f } func (c *Cache) getBytesAndRemoveIfExpired(id string) ([]byte, bool) { if c.maxAge == 0 { // No caching. return nil, false } f, err := c.Fs.Open(id) if err != nil { return nil, false } defer f.Close() b, err := io.ReadAll(f) if err != nil { return nil, false } removed, err := c.removeIfExpired(id) if err != nil { return nil, false } return b, removed } func (c *Cache) removeIfExpired(id string) (bool, error) { if c.maxAge <= 0 { return false, nil } fi, err := c.Fs.Stat(id) if err != nil { return false, err } if c.isExpired(fi.ModTime()) { c.Fs.Remove(id) return true, nil } return false, nil } func (c *Cache) isExpired(modTime time.Time) bool { if c.maxAge < 0 { return false } // Note the use of time.Since here. // We cannot use Hugo's global Clock for this. return c.maxAge == 0 || time.Since(modTime) > c.maxAge } // For testing func (c *Cache) GetString(id string) string { id = cleanID(id) c.nlocker.Lock(id) defer c.nlocker.Unlock(id) f, err := c.Fs.Open(id) if err != nil { return "" } defer f.Close() b, _ := io.ReadAll(f) return string(b) } // Caches is a named set of caches. type Caches map[string]*Cache // Get gets a named cache, nil if none found. func (f Caches) Get(name string) *Cache { return f[strings.ToLower(name)] } // NewCaches creates a new set of file caches from the given // configuration. func NewCaches(p *helpers.PathSpec) (Caches, error) { dcfg := p.Cfg.GetConfigSection("caches").(Configs) fs := p.Fs.Source m := make(Caches) for k, v := range dcfg { var cfs afero.Fs if v.IsResourceDir { cfs = p.BaseFs.ResourcesCache } else { cfs = fs } if cfs == nil { panic("nil fs") } baseDir := v.DirCompiled bfs := hugofs.NewBasePathFs(cfs, baseDir) var pruneAllRootDir string if k == CacheKeyModules { pruneAllRootDir = "pkg" } m[k] = NewCache(bfs, v.MaxAge, pruneAllRootDir) } return m, nil } func cleanID(name string) string { return strings.TrimPrefix(filepath.Clean(name), helpers.FilePathSeparator) } // AsHTTPCache returns an httpcache.Cache implementation for this file cache. // Note that none of the methods are protected by named locks, so you need to make sure // to do that in your own code. func (c *Cache) AsHTTPCache() httpcache.Cache { return &httpCache{c: c} } type httpCache struct { c *Cache } func (h *httpCache) Get(id string) (resp []byte, ok bool) { id = cleanID(id) b, removed := h.c.getBytesAndRemoveIfExpired(id) return b, !removed } func (h *httpCache) Set(id string, resp []byte) { if h.c.maxAge == 0 { return } id = cleanID(id) if err := h.c.writeReader(id, bytes.NewReader(resp)); err != nil { panic(err) } } func (h *httpCache) Delete(key string) { h.c.Fs.Remove(key) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/filecache/filecache_pruner.go
cache/filecache/filecache_pruner.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 filecache import ( "fmt" "io" "os" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/hugofs" "github.com/spf13/afero" ) // Prune removes expired and unused items from this cache. // The last one requires a full build so the cache usage can be tracked. // Note that we operate directly on the filesystem here, so this is not // thread safe. func (c Caches) Prune() (int, error) { counter := 0 for k, cache := range c { count, err := cache.Prune(false) counter += count if err != nil { if herrors.IsNotExist(err) { continue } return counter, fmt.Errorf("failed to prune cache %q: %w", k, err) } } return counter, nil } // Prune removes expired and unused items from this cache. // If force is set, everything will be removed not considering expiry time. func (c *Cache) Prune(force bool) (int, error) { if c.pruneAllRootDir != "" { return c.pruneRootDir(force) } if err := c.init(); err != nil { return 0, err } counter := 0 err := afero.Walk(c.Fs, "", func(name string, info os.FileInfo, err error) error { if info == nil { return nil } name = cleanID(name) if info.IsDir() { f, err := c.Fs.Open(name) if err != nil { // This cache dir may not exist. return nil } _, err = f.Readdirnames(1) f.Close() if err == io.EOF { // Empty dir. if name == "." { // e.g. /_gen/images -- keep it even if empty. err = nil } else { err = c.Fs.Remove(name) } } if err != nil && !herrors.IsNotExist(err) { return err } return nil } shouldRemove := force || c.isExpired(info.ModTime()) if !shouldRemove && len(c.nlocker.seen) > 0 { // Remove it if it's not been touched/used in the last build. _, seen := c.nlocker.seen[name] shouldRemove = !seen } if shouldRemove { err := c.Fs.Remove(name) if err == nil { counter++ } if err != nil && !herrors.IsNotExist(err) { return err } } return nil }) return counter, err } func (c *Cache) pruneRootDir(force bool) (int, error) { if err := c.init(); err != nil { return 0, err } info, err := c.Fs.Stat(c.pruneAllRootDir) if err != nil { if herrors.IsNotExist(err) { return 0, nil } return 0, err } if !force && !c.isExpired(info.ModTime()) { return 0, nil } return hugofs.MakeReadableAndRemoveAllModulePkgDir(c.Fs, c.pruneAllRootDir) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/httpcache/httpcache.go
cache/httpcache/httpcache.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package httpcache import ( "encoding/json" "time" "github.com/gobwas/glob" "github.com/gohugoio/hugo/common/predicate" "github.com/gohugoio/hugo/config" "github.com/mitchellh/mapstructure" ) // DefaultConfig holds the default configuration for the HTTP cache. var DefaultConfig = Config{ RespectCacheControlNoStoreInRequest: true, RespectCacheControlNoStoreInResponse: false, Cache: Cache{ For: GlobMatcher{ Excludes: []string{"**"}, }, }, Polls: []PollConfig{ { For: GlobMatcher{ Includes: []string{"**"}, }, Disable: true, }, }, } // Config holds the configuration for the HTTP cache. type Config struct { // When enabled and there's a Cache-Control: no-store directive in the request, response will never be stored in disk cache. RespectCacheControlNoStoreInRequest bool // When enabled and there's a Cache-Control: no-store directive in the response, response will never be stored in disk cache. RespectCacheControlNoStoreInResponse bool // Enables HTTP cache behavior (RFC 9111) for these resources. // When this is not enabled for a resource, Hugo will go straight to the file cache. Cache Cache // Polls holds a list of configurations for polling remote resources to detect changes in watch mode. // This can be disabled for some resources, typically if they are known to not change. Polls []PollConfig } type Cache struct { // Enable HTTP cache behavior (RFC 9111) for these resources. For GlobMatcher } func (c *Config) Compile() (ConfigCompiled, error) { cc := ConfigCompiled{ Base: *c, } p, err := c.Cache.For.CompilePredicate() if err != nil { return cc, err } cc.For = p for _, pc := range c.Polls { p, err := pc.For.CompilePredicate() if err != nil { return cc, err } cc.PollConfigs = append(cc.PollConfigs, PollConfigCompiled{ For: p, Config: pc, }) } return cc, nil } // PollConfig holds the configuration for polling remote resources to detect changes in watch mode. type PollConfig struct { // What remote resources to apply this configuration to. For GlobMatcher // Disable polling for this configuration. Disable bool // Low is the lower bound for the polling interval. // This is the starting point when the resource has recently changed, // if that resource stops changing, the polling interval will gradually increase towards High. Low time.Duration // High is the upper bound for the polling interval. // This is the interval used when the resource is stable. High time.Duration } func (c PollConfig) MarshalJSON() (b []byte, err error) { // Marshal the durations as strings. type Alias PollConfig return json.Marshal(&struct { Low string High string Alias }{ Low: c.Low.String(), High: c.High.String(), Alias: (Alias)(c), }) } type GlobMatcher struct { // Excludes holds a list of glob patterns that will be excluded. Excludes []string // Includes holds a list of glob patterns that will be included. Includes []string } func (gm GlobMatcher) IsZero() bool { return len(gm.Includes) == 0 && len(gm.Excludes) == 0 } type ConfigCompiled struct { Base Config For predicate.P[string] PollConfigs []PollConfigCompiled } func (c *ConfigCompiled) PollConfigFor(s string) PollConfigCompiled { for _, pc := range c.PollConfigs { if pc.For(s) { return pc } } return PollConfigCompiled{} } func (c *ConfigCompiled) IsPollingDisabled() bool { for _, pc := range c.PollConfigs { if !pc.Config.Disable { return false } } return true } type PollConfigCompiled struct { For predicate.P[string] Config PollConfig } func (p PollConfigCompiled) IsZero() bool { return p.For == nil } func (gm *GlobMatcher) CompilePredicate() (func(string) bool, error) { if gm.IsZero() { panic("no includes or excludes") } var b predicate.PR[string] for _, include := range gm.Includes { g, err := glob.Compile(include, '/') if err != nil { return nil, err } fn := func(s string) predicate.Match { return predicate.BoolMatch(g.Match(s)) } b = b.Or(fn) } for _, exclude := range gm.Excludes { g, err := glob.Compile(exclude, '/') if err != nil { return nil, err } fn := func(s string) predicate.Match { return predicate.BoolMatch(!g.Match(s)) } b = b.And(fn) } return b.BoolFunc(), nil } func DecodeConfig(_ config.BaseConfig, m map[string]any) (Config, error) { if len(m) == 0 { return DefaultConfig, nil } var c Config dc := &mapstructure.DecoderConfig{ Result: &c, DecodeHook: mapstructure.StringToTimeDurationHookFunc(), WeaklyTypedInput: true, } decoder, err := mapstructure.NewDecoder(dc) if err != nil { return c, err } if err := decoder.Decode(m); err != nil { return c, err } if c.Cache.For.IsZero() { c.Cache.For = DefaultConfig.Cache.For } for pci := range c.Polls { if c.Polls[pci].For.IsZero() { c.Polls[pci].For = DefaultConfig.Cache.For c.Polls[pci].Disable = true } } if len(c.Polls) == 0 { c.Polls = DefaultConfig.Polls } return c, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/httpcache/httpcache_integration_test.go
cache/httpcache/httpcache_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package httpcache_test import ( "testing" "time" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestConfigCustom(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [httpcache] [httpcache.cache.for] includes = ["**gohugo.io**"] [[httpcache.polls]] low = "5s" high = "32s" [httpcache.polls.for] includes = ["**gohugo.io**"] ` b := hugolib.Test(t, files) httpcacheConf := b.H.Configs.Base.HTTPCache compiled := b.H.Configs.Base.C.HTTPCache b.Assert(httpcacheConf.Cache.For.Includes, qt.DeepEquals, []string{"**gohugo.io**"}) b.Assert(httpcacheConf.Cache.For.Excludes, qt.IsNil) pc := compiled.PollConfigFor("https://gohugo.io/foo.jpg") b.Assert(pc.Config.Low, qt.Equals, 5*time.Second) b.Assert(pc.Config.High, qt.Equals, 32*time.Second) b.Assert(compiled.PollConfigFor("https://example.com/foo.jpg").IsZero(), qt.IsTrue) } func TestConfigDefault(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- ` b := hugolib.Test(t, files) compiled := b.H.Configs.Base.C.HTTPCache b.Assert(compiled.For("https://gohugo.io/posts.json"), qt.IsFalse) b.Assert(compiled.For("https://gohugo.io/foo.jpg"), qt.IsFalse) b.Assert(compiled.PollConfigFor("https://gohugo.io/foo.jpg").Config.Disable, qt.IsTrue) } func TestConfigPollsOnly(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [httpcache] [[httpcache.polls]] low = "5s" high = "32s" [httpcache.polls.for] includes = ["**gohugo.io**"] ` b := hugolib.Test(t, files) compiled := b.H.Configs.Base.C.HTTPCache b.Assert(compiled.For("https://gohugo.io/posts.json"), qt.IsFalse) b.Assert(compiled.For("https://gohugo.io/foo.jpg"), qt.IsFalse) pc := compiled.PollConfigFor("https://gohugo.io/foo.jpg") b.Assert(pc.Config.Low, qt.Equals, 5*time.Second) b.Assert(pc.Config.High, qt.Equals, 32*time.Second) b.Assert(compiled.PollConfigFor("https://example.com/foo.jpg").IsZero(), qt.IsTrue) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/httpcache/httpcache_test.go
cache/httpcache/httpcache_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package httpcache import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" ) func TestGlobMatcher(t *testing.T) { c := qt.New(t) g := GlobMatcher{ Includes: []string{"**/*.jpg", "**.png", "**/bar/**"}, Excludes: []string{"**/foo.jpg", "**.css"}, } p, err := g.CompilePredicate() c.Assert(err, qt.IsNil) c.Assert(p("foo.jpg"), qt.IsFalse) c.Assert(p("foo.png"), qt.IsTrue) c.Assert(p("foo/bar.jpg"), qt.IsTrue) c.Assert(p("foo/bar.png"), qt.IsTrue) c.Assert(p("foo/bar/foo.jpg"), qt.IsFalse) c.Assert(p("foo/bar/foo.css"), qt.IsFalse) c.Assert(p("foo.css"), qt.IsFalse) c.Assert(p("foo/bar/foo.css"), qt.IsFalse) c.Assert(p("foo/bar/foo.xml"), qt.IsTrue) } func TestDefaultConfig(t *testing.T) { c := qt.New(t) _, err := DefaultConfig.Compile() c.Assert(err, qt.IsNil) } func TestDecodeConfigInjectsDefaultAndCompiles(t *testing.T) { c := qt.New(t) cfg, err := DecodeConfig(config.BaseConfig{}, map[string]any{}) c.Assert(err, qt.IsNil) c.Assert(cfg, qt.DeepEquals, DefaultConfig) _, err = cfg.Compile() c.Assert(err, qt.IsNil) cfg, err = DecodeConfig(config.BaseConfig{}, map[string]any{ "cache": map[string]any{ "polls": []map[string]any{ {"disable": true}, }, }, }) c.Assert(err, qt.IsNil) _, err = cfg.Compile() c.Assert(err, qt.IsNil) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/dynacache/dynacache.go
cache/dynacache/dynacache.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dynacache import ( "context" "fmt" "math" "path" "regexp" "runtime" "sync" "time" "github.com/bep/lazycache" "github.com/bep/logg" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/rungroup" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources/resource" ) const minMaxSize = 10 type KeyIdentity struct { Key any Identity identity.Identity } // New creates a new cache. func New(opts Options) *Cache { if opts.CheckInterval == 0 { opts.CheckInterval = time.Second * 2 } if opts.MaxSize == 0 { opts.MaxSize = 100000 } if opts.Log == nil { panic("nil Log") } if opts.MinMaxSize == 0 { opts.MinMaxSize = 30 } stats := &stats{ opts: opts, adjustmentFactor: 1.0, currentMaxSize: opts.MaxSize, availableMemory: config.GetMemoryLimit(), } infol := opts.Log.InfoCommand("dynacache") evictedIdentities := collections.NewStackThreadSafe[KeyIdentity]() onEvict := func(k, v any) { if !opts.Watching { return } identity.WalkIdentitiesShallow(v, func(level int, id identity.Identity) bool { evictedIdentities.Push(KeyIdentity{Key: k, Identity: id}) return false }) resource.MarkStale(v) } c := &Cache{ partitions: make(map[string]PartitionManager), onEvict: onEvict, evictedIdentities: evictedIdentities, opts: opts, stats: stats, infol: infol, } c.stop = c.start() return c } // Options for the cache. type Options struct { Log loggers.Logger CheckInterval time.Duration MaxSize int MinMaxSize int Watching bool } // Options for a partition. type OptionsPartition struct { // When to clear the this partition. ClearWhen ClearWhen // Weight is a number between 1 and 100 that indicates how, in general, how big this partition may get. Weight int } func (o OptionsPartition) WeightFraction() float64 { return float64(o.Weight) / 100 } func (o OptionsPartition) CalculateMaxSize(maxSizePerPartition int) int { return int(math.Floor(float64(maxSizePerPartition) * o.WeightFraction())) } // A dynamic partitioned cache. type Cache struct { mu sync.RWMutex partitions map[string]PartitionManager onEvict func(k, v any) evictedIdentities *collections.StackThreadSafe[KeyIdentity] opts Options infol logg.LevelLogger stats *stats stopOnce sync.Once stop func() } // DrainEvictedIdentities drains the evicted identities from the cache. func (c *Cache) DrainEvictedIdentities() []KeyIdentity { return c.evictedIdentities.Drain() } // DrainEvictedIdentitiesMatching drains the evicted identities from the cache that match the given predicate. func (c *Cache) DrainEvictedIdentitiesMatching(predicate func(KeyIdentity) bool) []KeyIdentity { return c.evictedIdentities.DrainMatching(predicate) } // ClearMatching clears all partition for which the predicate returns true. 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(predicateValue) return nil }, }) for k, p := range c.partitions { if !predicatePartition(k, p) { continue } g.Enqueue(p) } g.Wait() } // ClearOnRebuild prepares the cache for a new rebuild taking the given changeset into account. // predicate is optional and will clear any entry for which it returns true. func (c *Cache) ClearOnRebuild(predicate func(k, v any) bool, changeset ...identity.Identity) { g := rungroup.Run[PartitionManager](context.Background(), rungroup.Config[PartitionManager]{ NumWorkers: len(c.partitions), Handle: func(ctx context.Context, partition PartitionManager) error { partition.clearOnRebuild(predicate, changeset...) return nil }, }) for _, p := range c.partitions { g.Enqueue(p) } g.Wait() // Clear any entries marked as stale above. g = rungroup.Run[PartitionManager](context.Background(), rungroup.Config[PartitionManager]{ NumWorkers: len(c.partitions), Handle: func(ctx context.Context, partition PartitionManager) error { partition.clearStale() return nil }, }) for _, p := range c.partitions { g.Enqueue(p) } g.Wait() } type keysProvider interface { Keys() []string } // Keys returns a list of keys in all partitions. func (c *Cache) Keys(predicate func(s string) bool) []string { if predicate == nil { predicate = func(s string) bool { return true } } var keys []string for pn, g := range c.partitions { pkeys := g.(keysProvider).Keys() for _, k := range pkeys { p := path.Join(pn, k) if predicate(p) { keys = append(keys, p) } } } return keys } func calculateMaxSizePerPartition(maxItemsTotal, totalWeightQuantity, numPartitions int) int { if numPartitions == 0 { panic("numPartitions must be > 0") } if totalWeightQuantity == 0 { panic("totalWeightQuantity must be > 0") } avgWeight := float64(totalWeightQuantity) / float64(numPartitions) return int(math.Floor(float64(maxItemsTotal) / float64(numPartitions) * (100.0 / avgWeight))) } // Stop stops the cache. func (c *Cache) Stop() { c.stopOnce.Do(func() { c.stop() }) } func (c *Cache) adjustCurrentMaxSize() { c.mu.RLock() defer c.mu.RUnlock() if len(c.partitions) == 0 { return } var m runtime.MemStats runtime.ReadMemStats(&m) s := c.stats s.memstatsCurrent = m // fmt.Printf("\n\nAvailable = %v\nAlloc = %v\nTotalAlloc = %v\nSys = %v\nNumGC = %v\nMaxSize = %d\nAdjustmentFactor=%f\n\n", helpers.FormatByteCount(s.availableMemory), helpers.FormatByteCount(m.Alloc), helpers.FormatByteCount(m.TotalAlloc), helpers.FormatByteCount(m.Sys), m.NumGC, c.stats.currentMaxSize, s.adjustmentFactor) if s.availableMemory >= s.memstatsCurrent.Alloc { if s.adjustmentFactor <= 1.0 { s.adjustmentFactor += 0.2 } } else { // We're low on memory. s.adjustmentFactor -= 0.4 } if s.adjustmentFactor <= 0 { s.adjustmentFactor = 0.05 } if !s.adjustCurrentMaxSize() { return } totalWeight := 0 for _, pm := range c.partitions { totalWeight += pm.getOptions().Weight } maxSizePerPartition := calculateMaxSizePerPartition(c.stats.currentMaxSize, totalWeight, len(c.partitions)) evicted := 0 for _, p := range c.partitions { evicted += p.adjustMaxSize(p.getOptions().CalculateMaxSize(maxSizePerPartition)) } if evicted > 0 { c.infol. WithFields( logg.Fields{ {Name: "evicted", Value: evicted}, {Name: "numGC", Value: m.NumGC}, {Name: "limit", Value: helpers.FormatByteCount(c.stats.availableMemory)}, {Name: "alloc", Value: helpers.FormatByteCount(m.Alloc)}, {Name: "totalAlloc", Value: helpers.FormatByteCount(m.TotalAlloc)}, }, ).Logf("adjusted partitions' max size") } } func (c *Cache) start() func() { ticker := time.NewTicker(c.opts.CheckInterval) quit := make(chan struct{}) go func() { for { select { case <-ticker.C: c.adjustCurrentMaxSize() // Reset the ticker to avoid drift. ticker.Reset(c.opts.CheckInterval) case <-quit: ticker.Stop() return } } }() return func() { close(quit) } } var partitionNameRe = regexp.MustCompile(`^\/[a-zA-Z0-9]{4}(\/[a-zA-Z0-9]+)?(\/[a-zA-Z0-9]+)?`) // GetOrCreatePartition gets or creates a partition with the given name. func GetOrCreatePartition[K comparable, V any](c *Cache, name string, opts OptionsPartition) *Partition[K, V] { if c == nil { panic("nil Cache") } if opts.Weight < 1 || opts.Weight > 100 { panic("invalid Weight, must be between 1 and 100") } if !partitionNameRe.MatchString(name) { panic(fmt.Sprintf("invalid partition name %q", name)) } c.mu.RLock() p, found := c.partitions[name] c.mu.RUnlock() if found { return p.(*Partition[K, V]) } c.mu.Lock() defer c.mu.Unlock() // Double check. p, found = c.partitions[name] if found { return p.(*Partition[K, V]) } // At this point, we don't know the number of partitions or their configuration, but // this will be re-adjusted later. const numberOfPartitionsEstimate = 10 maxSize := opts.CalculateMaxSize(c.opts.MaxSize / numberOfPartitionsEstimate) onEvict := func(k K, v V) { c.onEvict(k, v) } // Create a new partition and cache it. partition := &Partition[K, V]{ c: lazycache.New(lazycache.Options[K, V]{MaxEntries: maxSize, OnEvict: onEvict}), maxSize: maxSize, trace: c.opts.Log.Logger().WithLevel(logg.LevelTrace).WithField("partition", name), opts: opts, } c.partitions[name] = partition return partition } // Partition is a partition in the cache. type Partition[K comparable, V any] struct { c *lazycache.Cache[K, V] zero V trace logg.LevelLogger opts OptionsPartition maxSize int } // GetOrCreate gets or creates a value for the given key. func (p *Partition[K, V]) GetOrCreate(key K, create func(key K) (V, error)) (V, error) { v, err := p.doGetOrCreate(key, create) if err != nil { return p.zero, err } if resource.StaleVersion(v) > 0 { p.c.Delete(key) return p.doGetOrCreate(key, create) } return v, err } func (p *Partition[K, V]) doGetOrCreate(key K, create func(key K) (V, error)) (V, error) { v, _, err := p.c.GetOrCreate(key, create) return v, err } func (p *Partition[K, V]) GetOrCreateWitTimeout(key K, duration time.Duration, create func(key K) (V, error)) (V, error) { v, err := p.doGetOrCreateWitTimeout(key, duration, create) if err != nil { return p.zero, err } if resource.StaleVersion(v) > 0 { p.c.Delete(key) return p.doGetOrCreateWitTimeout(key, duration, create) } return v, err } // GetOrCreateWitTimeout gets or creates a value for the given key and times out if the create function // takes too long. func (p *Partition[K, V]) doGetOrCreateWitTimeout(key K, duration time.Duration, create func(key K) (V, error)) (V, error) { resultch := make(chan V, 1) errch := make(chan error, 1) go func() { var ( v V err error ) defer func() { if r := recover(); r != nil { if rerr, ok := r.(error); ok { err = rerr } else { err = fmt.Errorf("panic: %v", r) } } if err != nil { errch <- err } else { resultch <- v } }() v, _, err = p.c.GetOrCreate(key, create) }() select { case v := <-resultch: return v, nil case err := <-errch: return p.zero, err case <-time.After(duration): return p.zero, &herrors.TimeoutError{ Duration: duration, } } } func (p *Partition[K, V]) clearMatching(predicate func(k, v any) bool) { p.c.DeleteFunc(func(key K, v V) bool { if predicate(key, v) { p.trace.Log( logg.StringFunc( func() string { return fmt.Sprintf("clearing cache key %v", key) }, ), ) return true } return false }) } func (p *Partition[K, V]) clearOnRebuild(predicate func(k, v any) bool, changeset ...identity.Identity) { if predicate == nil { predicate = func(k, v any) bool { return false } } opts := p.getOptions() if opts.ClearWhen == ClearNever { return } if opts.ClearWhen == ClearOnRebuild { // Clear all. p.Clear() return } depsFinder := identity.NewFinder(identity.FinderConfig{}) shouldDelete := func(key K, v V) bool { // We always clear elements marked as stale. if resource.StaleVersion(v) > 0 { return true } // Now check if this entry has changed based on the changeset // based on filesystem events. if len(changeset) == 0 { // Nothing changed. return false } var probablyDependent bool identity.WalkIdentitiesShallow(v, func(level int, id2 identity.Identity) bool { for _, id := range changeset { if r := depsFinder.Contains(id, id2, -1); r > 0 { // It's probably dependent, evict from cache. probablyDependent = true return true } } return false }) return probablyDependent } // First pass. // Second pass needs to be done in a separate loop to catch any // elements marked as stale in the other partitions. p.c.DeleteFunc(func(key K, v V) bool { if predicate(key, v) || shouldDelete(key, v) { p.trace.Log( logg.StringFunc( func() string { return fmt.Sprintf("first pass: clearing cache key %v", key) }, ), ) return true } return false }) } func (p *Partition[K, V]) Keys() []K { var keys []K p.c.DeleteFunc(func(key K, v V) bool { keys = append(keys, key) return false }) return keys } func (p *Partition[K, V]) clearStale() { p.c.DeleteFunc(func(key K, v V) bool { staleVersion := resource.StaleVersion(v) if staleVersion > 0 { p.trace.Log( logg.StringFunc( func() string { return fmt.Sprintf("second pass: clearing cache key %v", key) }, ), ) } return staleVersion > 0 }) } // adjustMaxSize adjusts the max size of the and returns the number of items evicted. func (p *Partition[K, V]) adjustMaxSize(newMaxSize int) int { if newMaxSize < minMaxSize { newMaxSize = minMaxSize } oldMaxSize := p.maxSize if newMaxSize == oldMaxSize { return 0 } p.maxSize = newMaxSize // fmt.Println("Adjusting max size of partition from", oldMaxSize, "to", newMaxSize) return p.c.Resize(newMaxSize) } func (p *Partition[K, V]) getMaxSize() int { return p.maxSize } func (p *Partition[K, V]) getOptions() OptionsPartition { return p.opts } func (p *Partition[K, V]) Clear() { p.c.DeleteFunc(func(key K, v V) bool { return true }) } func (p *Partition[K, V]) Get(ctx context.Context, key K) (V, bool) { return p.c.Get(key) } type PartitionManager interface { adjustMaxSize(addend int) int getMaxSize() int getOptions() OptionsPartition clearOnRebuild(predicate func(k, v any) bool, changeset ...identity.Identity) clearMatching(predicate func(k, v any) bool) clearStale() } const ( ClearOnRebuild ClearWhen = iota + 1 ClearOnChange ClearNever ) type ClearWhen int type stats struct { opts Options memstatsCurrent runtime.MemStats currentMaxSize int availableMemory uint64 adjustmentFactor float64 } func (s *stats) adjustCurrentMaxSize() bool { newCurrentMaxSize := int(math.Floor(float64(s.opts.MaxSize) * s.adjustmentFactor)) if newCurrentMaxSize < s.opts.MinMaxSize { newCurrentMaxSize = int(s.opts.MinMaxSize) } changed := newCurrentMaxSize != s.currentMaxSize s.currentMaxSize = newCurrentMaxSize return changed } // CleanKey turns s into a format suitable for a cache key for this package. // The key will be a Unix-styled path with a leading slash but no trailing slash. func CleanKey(s string) string { return path.Clean(paths.ToSlashPreserveLeading(s)) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/cache/dynacache/dynacache_test.go
cache/dynacache/dynacache_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dynacache import ( "errors" "fmt" "path/filepath" "testing" "time" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources/resource" ) var ( _ resource.StaleInfo = (*testItem)(nil) _ identity.Identity = (*testItem)(nil) ) type testItem struct { name string staleVersion uint32 } func (t testItem) StaleVersion() uint32 { return t.staleVersion } func (t testItem) IdentifierBase() string { return t.name } func TestCache(t *testing.T) { t.Parallel() c := qt.New(t) cache := New(Options{ Log: loggers.NewDefault(), }) c.Cleanup(func() { cache.Stop() }) opts := OptionsPartition{Weight: 30} c.Assert(cache, qt.Not(qt.IsNil)) p1 := GetOrCreatePartition[string, testItem](cache, "/aaaa/bbbb", opts) c.Assert(p1, qt.Not(qt.IsNil)) p2 := GetOrCreatePartition[string, testItem](cache, "/aaaa/bbbb", opts) c.Assert(func() { GetOrCreatePartition[string, testItem](cache, "foo bar", opts) }, qt.PanicMatches, ".*invalid partition name.*") c.Assert(func() { GetOrCreatePartition[string, testItem](cache, "/aaaa/cccc", OptionsPartition{Weight: 1234}) }, qt.PanicMatches, ".*invalid Weight.*") c.Assert(p2, qt.Equals, p1) p3 := GetOrCreatePartition[string, testItem](cache, "/aaaa/cccc", opts) c.Assert(p3, qt.Not(qt.IsNil)) c.Assert(p3, qt.Not(qt.Equals), p1) c.Assert(func() { New(Options{}) }, qt.PanicMatches, ".*nil Log.*") } func TestCalculateMaxSizePerPartition(t *testing.T) { t.Parallel() c := qt.New(t) c.Assert(calculateMaxSizePerPartition(1000, 500, 5), qt.Equals, 200) c.Assert(calculateMaxSizePerPartition(1000, 250, 5), qt.Equals, 400) c.Assert(func() { calculateMaxSizePerPartition(1000, 250, 0) }, qt.PanicMatches, ".*must be > 0.*") c.Assert(func() { calculateMaxSizePerPartition(1000, 0, 1) }, qt.PanicMatches, ".*must be > 0.*") } func TestCleanKey(t *testing.T) { c := qt.New(t) c.Assert(CleanKey("a/b/c"), qt.Equals, "/a/b/c") c.Assert(CleanKey("/a/b/c"), qt.Equals, "/a/b/c") c.Assert(CleanKey("a/b/c/"), qt.Equals, "/a/b/c") c.Assert(CleanKey(filepath.FromSlash("/a/b/c/")), qt.Equals, "/a/b/c") } func newTestCache(t *testing.T) *Cache { cache := New( Options{ Log: loggers.NewDefault(), }, ) p1 := GetOrCreatePartition[string, testItem](cache, "/aaaa/bbbb", OptionsPartition{Weight: 30, ClearWhen: ClearOnRebuild}) p2 := GetOrCreatePartition[string, testItem](cache, "/aaaa/cccc", OptionsPartition{Weight: 30, ClearWhen: ClearOnChange}) p1.GetOrCreate("clearOnRebuild", func(string) (testItem, error) { return testItem{}, nil }) p2.GetOrCreate("clearBecauseStale", func(string) (testItem, error) { return testItem{ staleVersion: 32, }, nil }) p2.GetOrCreate("clearBecauseIdentityChanged", func(string) (testItem, error) { return testItem{ name: "changed", }, nil }) p2.GetOrCreate("clearNever", func(string) (testItem, error) { return testItem{ staleVersion: 0, }, nil }) t.Cleanup(func() { cache.Stop() }) return cache } func TestClear(t *testing.T) { t.Parallel() c := qt.New(t) predicateAll := func(string) bool { return true } cache := newTestCache(t) c.Assert(cache.Keys(predicateAll), qt.HasLen, 4) cache.ClearOnRebuild(nil) // Stale items are always cleared. c.Assert(cache.Keys(predicateAll), qt.HasLen, 2) cache = newTestCache(t) cache.ClearOnRebuild(nil, identity.StringIdentity("changed")) c.Assert(cache.Keys(nil), qt.HasLen, 1) cache = newTestCache(t) cache.ClearMatching(nil, func(k, v any) bool { return k.(string) == "clearOnRebuild" }) c.Assert(cache.Keys(predicateAll), qt.HasLen, 3) cache.adjustCurrentMaxSize() } func TestPanicInCreate(t *testing.T) { t.Parallel() c := qt.New(t) cache := newTestCache(t) p1 := GetOrCreatePartition[string, testItem](cache, "/aaaa/bbbb", OptionsPartition{Weight: 30, ClearWhen: ClearOnRebuild}) willPanic := func(i int) func() { return func() { p1.GetOrCreate(fmt.Sprintf("panic-%d", i), func(key string) (testItem, error) { panic(errors.New(key)) }) } } // GetOrCreateWitTimeout needs to recover from panics in the create func. willErr := func(i int) error { _, err := p1.GetOrCreateWitTimeout(fmt.Sprintf("error-%d", i), 10*time.Second, func(key string) (testItem, error) { return testItem{}, errors.New(key) }) return err } for i := range 3 { for range 3 { c.Assert(willPanic(i), qt.PanicMatches, fmt.Sprintf("panic-%d", i)) c.Assert(willErr(i), qt.ErrorMatches, fmt.Sprintf("error-%d", i)) } } // Test the same keys again without the panic. for i := range 3 { for range 3 { v, err := p1.GetOrCreate(fmt.Sprintf("panic-%d", i), func(key string) (testItem, error) { return testItem{ name: key, }, nil }) c.Assert(err, qt.IsNil) c.Assert(v.name, qt.Equals, fmt.Sprintf("panic-%d", i)) v, err = p1.GetOrCreateWitTimeout(fmt.Sprintf("error-%d", i), 10*time.Second, func(key string) (testItem, error) { return testItem{ name: key, }, nil }) c.Assert(err, qt.IsNil) c.Assert(v.name, qt.Equals, fmt.Sprintf("error-%d", i)) } } } func TestAdjustCurrentMaxSize(t *testing.T) { t.Parallel() c := qt.New(t) cache := newTestCache(t) alloc := cache.stats.memstatsCurrent.Alloc cache.adjustCurrentMaxSize() c.Assert(cache.stats.memstatsCurrent.Alloc, qt.Not(qt.Equals), alloc) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/template_test.go
tpl/template_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tpl import ( "testing" ) func TestStripHTML(t *testing.T) { type test struct { input, expected string } data := []test{ {"<h1>strip h1 tag <h1>", "strip h1 tag "}, {"<p> strip p tag </p>", " strip p tag "}, {"</br> strip br<br>", " strip br\n"}, {"</br> strip br2<br />", " strip br2\n"}, {"This <strong>is</strong> a\nnewline", "This is a newline"}, {"No Tags", "No Tags"}, {`<p>Summary Next Line. <figure > <img src="/not/real" /> </figure> . More text here.</p> <p>Some more text</p>`, "Summary Next Line. . More text here.\nSome more text\n"}, // Issue 9199 {"<div data-action='click->my-controller#doThing'>qwe</div>", "qwe"}, {"Hello, World!", "Hello, World!"}, {"foo&amp;bar", "foo&amp;bar"}, {`Hello <a href="www.example.com/">World</a>!`, "Hello World!"}, {"Foo <textarea>Bar</textarea> Baz", "Foo Bar Baz"}, {"Foo <!-- Bar --> Baz", "Foo Baz"}, } for i, d := range data { output := StripHTML(d.input) if d.expected != output { t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, output) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/template.go
tpl/template.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package tpl contains template functions and related types. package tpl import ( "context" "slices" "strings" "sync" "unicode" "github.com/bep/helpers/contexthelpers" bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/langs" htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate" texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) // Template is the common interface between text/template and html/template. type Template interface { Name() string Prepare() (*texttemplate.Template, error) } // RenderingContext represents the currently rendered site/language. type RenderingContext struct { Site site SiteOutIdx int } type ( contextKey uint8 ) const ( contextKeyDependencyManagerScopedProvider contextKey = iota contextKeyDependencyScope contextKeyPage contextKeyIsInGoldmark cntextKeyCurrentTemplateInfo contextKeyPartialDecoratorIDStack ) // Context manages values passed in the context to templates. var Context = struct { DependencyManagerScopedProvider contexthelpers.ContextDispatcher[identity.DependencyManagerScopedProvider] GetDependencyManagerInCurrentScope func(context.Context) identity.Manager DependencyScope contexthelpers.ContextDispatcher[int] Page contexthelpers.ContextDispatcher[page] IsInGoldmark contexthelpers.ContextDispatcher[bool] CurrentTemplate contexthelpers.ContextDispatcher[*CurrentTemplateInfo] PartialDecoratorIDStack contexthelpers.ContextDispatcher[*collections.Stack[*StringBool]] }{ DependencyManagerScopedProvider: contexthelpers.NewContextDispatcher[identity.DependencyManagerScopedProvider](contextKeyDependencyManagerScopedProvider), DependencyScope: contexthelpers.NewContextDispatcher[int](contextKeyDependencyScope), Page: contexthelpers.NewContextDispatcher[page](contextKeyPage), IsInGoldmark: contexthelpers.NewContextDispatcher[bool](contextKeyIsInGoldmark), CurrentTemplate: contexthelpers.NewContextDispatcher[*CurrentTemplateInfo](cntextKeyCurrentTemplateInfo), PartialDecoratorIDStack: contexthelpers.NewContextDispatcher[*collections.Stack[*StringBool]](contextKeyPartialDecoratorIDStack), } func init() { Context.GetDependencyManagerInCurrentScope = func(ctx context.Context) identity.Manager { idmsp := Context.DependencyManagerScopedProvider.Get(ctx) if idmsp != nil { return idmsp.GetDependencyManagerForScope(Context.DependencyScope.Get(ctx)) } return nil } } // StringBool is a helper struct to hold a string and a bool value. type StringBool struct { Str string Bool bool } type page interface { IsNode() bool } type site interface { Language() *langs.Language } const ( // HugoDeferredTemplatePrefix is the prefix for placeholders for deferred templates. HugoDeferredTemplatePrefix = "__hdeferred/" // HugoDeferredTemplateSuffix is the suffix for placeholders for deferred templates. HugoDeferredTemplateSuffix = "__d=" ) const hugoNewLinePlaceholder = "___hugonl_" var stripHTMLReplacerPre = strings.NewReplacer("\n", " ", "</p>", hugoNewLinePlaceholder, "<br>", hugoNewLinePlaceholder, "<br />", hugoNewLinePlaceholder) // StripHTML strips out all HTML tags in s. func StripHTML(s string) string { // Shortcut strings with no tags in them if !strings.ContainsAny(s, "<>") { return s } pre := stripHTMLReplacerPre.Replace(s) preReplaced := pre != s s = htmltemplate.StripTags(pre) if preReplaced { s = strings.ReplaceAll(s, hugoNewLinePlaceholder, "\n") } var wasSpace bool b := bp.GetBuffer() defer bp.PutBuffer(b) for _, r := range s { isSpace := unicode.IsSpace(r) if !(isSpace && wasSpace) { b.WriteRune(r) } wasSpace = isSpace } if b.Len() > 0 { s = b.String() } return s } // DeferredExecution holds the template and data for a deferred execution. type DeferredExecution struct { Mu sync.Mutex Ctx context.Context TemplatePath string Data any Executed bool Result string } type CurrentTemplateInfoOps interface { CurrentTemplateInfoCommonOps Base() CurrentTemplateInfoCommonOps } type CurrentTemplateInfoCommonOps interface { // Template name. Name() string // Template source filename. // Will be empty for internal templates. Filename() string } // CurrentTemplateInfo as returned in templates.Current. type CurrentTemplateInfo struct { Parent *CurrentTemplateInfo Level int Key string CurrentTemplateInfoOps } // CurrentTemplateInfos is a slice of CurrentTemplateInfo. type CurrentTemplateInfos []*CurrentTemplateInfo // Reverse creates a copy of the slice and reverses it. func (c CurrentTemplateInfos) Reverse() CurrentTemplateInfos { if len(c) == 0 { return c } r := make(CurrentTemplateInfos, len(c)) copy(r, c) slices.Reverse(r) return r } // Ancestors returns the ancestors of the current template. func (ti *CurrentTemplateInfo) Ancestors() CurrentTemplateInfos { var ancestors []*CurrentTemplateInfo for ti.Parent != nil { ti = ti.Parent ancestors = append(ancestors, ti) } return ancestors }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/cast/init.go
tpl/cast/init.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 cast import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const name = "cast" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New() ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.ToFloat, []string{"float"}, [][2]string{ {`{{ "1234" | float | printf "%T" }}`, `float64`}, }, ) ns.AddMethodMapping(ctx.ToInt, []string{"int"}, [][2]string{ {`{{ "1234" | int | printf "%T" }}`, `int`}, }, ) ns.AddMethodMapping(ctx.ToString, []string{"string"}, [][2]string{ {`{{ 1234 | string | printf "%T" }}`, `string`}, }, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/cast/cast_test.go
tpl/cast/cast_test.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 cast import ( "html/template" "testing" "github.com/bep/imagemeta" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/htesting/hqt" ) func TestToInt(t *testing.T) { t.Parallel() c := qt.New(t) ns := New() for i, test := range []struct { v any expect any }{ {"1", 1}, {template.HTML("2"), 2}, {template.CSS("3"), 3}, {template.HTMLAttr("4"), 4}, {template.JS("5"), 5}, {template.JSStr("6"), 6}, {"a", false}, {t, false}, } { errMsg := qt.Commentf("[%d] %v", i, test.v) result, err := ns.ToInt(test.v) if b, ok := test.expect.(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 TestToString(t *testing.T) { t.Parallel() c := qt.New(t) ns := New() for i, test := range []struct { v any expect any }{ {1, "1"}, {template.HTML("2"), "2"}, {"a", "a"}, {t, false}, } { errMsg := qt.Commentf("[%d] %v", i, test.v) result, err := ns.ToString(test.v) if b, ok := test.expect.(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 TestToFloat(t *testing.T) { t.Parallel() c := qt.New(t) ns := New() oneThird, _ := imagemeta.NewRat[uint32](1, 3) for i, test := range []struct { v any expect any }{ {"1", 1.0}, {template.HTML("2"), 2.0}, {template.CSS("3"), 3.0}, {template.HTMLAttr("4"), 4.0}, {template.JS("-5.67"), -5.67}, {template.JSStr("6"), 6.0}, {"1.23", 1.23}, {"-1.23", -1.23}, {"0", 0.0}, {float64(2.12), 2.12}, {int64(123), 123.0}, {oneThird, 0.3333333333333333}, {2, 2.0}, {t, false}, } { errMsg := qt.Commentf("[%d] %v", i, test.v) result, err := ns.ToFloat(test.v) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil, errMsg) c.Assert(result, hqt.IsSameFloat64, test.expect, errMsg) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/cast/cast.go
tpl/cast/cast.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 cast provides template functions for data type conversions. package cast import ( "html/template" _cast "github.com/spf13/cast" ) // New returns a new instance of the cast-namespaced template functions. func New() *Namespace { return &Namespace{} } // Namespace provides template functions for the "cast" namespace. type Namespace struct{} // ToInt converts v to an int. func (ns *Namespace) ToInt(v any) (int, error) { v = convertTemplateToString(v) return _cast.ToIntE(v) } // ToString converts v to a string. func (ns *Namespace) ToString(v any) (string, error) { return _cast.ToStringE(v) } // ToFloat converts v to a float. func (ns *Namespace) ToFloat(v any) (float64, error) { v = convertTemplateToString(v) return _cast.ToFloat64E(v) } func convertTemplateToString(v any) any { switch vv := v.(type) { case template.HTML: v = string(vv) case template.CSS: v = string(vv) case template.HTMLAttr: v = string(vv) case template.JS: v = string(vv) case template.JSStr: v = string(vv) } return v }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/cast/docshelper.go
tpl/cast/docshelper.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 cast import ( "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/docshelper" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/tpl/internal" ) // This file provides documentation support and is randomly put into this package. func init() { docsProvider := func() docshelper.DocProvider { d := &deps.Deps{Conf: testconfig.GetTestConfig(nil, nil)} if err := d.Init(); err != nil { panic(err) } conf := testconfig.GetTestConfig(nil, newTestConfig()) d.Site = page.NewDummyHugoSite(conf) var namespaces internal.TemplateFuncsNamespaces for _, nsf := range internal.TemplateFuncsNamespaceRegistry { nf := nsf(d) namespaces = append(namespaces, nf) } return docshelper.DocProvider{"tpl": map[string]any{"funcs": namespaces}} } docshelper.AddDocProviderFunc(docsProvider) } func newTestConfig() config.Provider { v := config.New() v.Set("contentDir", "content") return v }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/site/init.go
tpl/site/init.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package site provides template functions for accessing the Site object. package site import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/tpl/internal" ) const name = "site" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { s := page.WrapSite(d.Site) ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return s, nil }, } // We just add the Site as the namespace here. No method mappings. return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/lang/init.go
tpl/lang/init.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 lang import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/tpl/internal" ) const name = "lang" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New(d, langs.GetTranslator(d.Conf.Language().(*langs.Language))) ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.FormatAccounting, nil, [][2]string{ {`{{ 512.5032 | lang.FormatAccounting 2 "NOK" }}`, `NOK512.50`}, }, ) ns.AddMethodMapping(ctx.FormatCurrency, nil, [][2]string{ {`{{ 512.5032 | lang.FormatCurrency 2 "USD" }}`, `$512.50`}, }, ) ns.AddMethodMapping(ctx.FormatNumber, nil, [][2]string{ {`{{ 512.5032 | lang.FormatNumber 2 }}`, `512.50`}, }, ) ns.AddMethodMapping(ctx.FormatNumberCustom, nil, [][2]string{ {`{{ lang.FormatNumberCustom 2 12345.6789 }}`, `12,345.68`}, {`{{ lang.FormatNumberCustom 2 12345.6789 "- , ." }}`, `12.345,68`}, {`{{ lang.FormatNumberCustom 6 -12345.6789 "- ." }}`, `-12345.678900`}, {`{{ lang.FormatNumberCustom 0 -12345.6789 "- . ," }}`, `-12,346`}, {`{{ lang.FormatNumberCustom 0 -12345.6789 "-|.| " "|" }}`, `-12 346`}, {`{{ -98765.4321 | lang.FormatNumberCustom 2 }}`, `-98,765.43`}, }, ) ns.AddMethodMapping(ctx.FormatPercent, nil, [][2]string{ {`{{ 512.5032 | lang.FormatPercent 2 }}`, `512.50%`}, }, ) ns.AddMethodMapping(ctx.Merge, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Translate, []string{"i18n", "T"}, [][2]string{}, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/lang/lang_test.go
tpl/lang/lang_test.go
package lang import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/deps" translators "github.com/gohugoio/localescompressed" ) func TestNumFmt(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(&deps.Deps{}, nil) cases := []struct { prec int n float64 runes string delim string want string }{ {2, -12345.6789, "", "", "-12,345.68"}, {2, -12345.6789, "- . ,", "", "-12,345.68"}, {2, -12345.1234, "- . ,", "", "-12,345.12"}, {2, 12345.6789, "- . ,", "", "12,345.68"}, {0, 12345.6789, "- . ,", "", "12,346"}, {11, -12345.6789, "- . ,", "", "-12,345.67890000000"}, {2, 927.675, "- .", "", "927.68"}, {2, 1927.675, "- .", "", "1927.68"}, {2, 2927.675, "- .", "", "2927.68"}, {3, -12345.6789, "- ,", "", "-12345,679"}, {6, -12345.6789, "- , .", "", "-12.345,678900"}, {3, -12345.6789, "-|,| ", "|", "-12 345,679"}, {6, -12345.6789, "-|,| ", "|", "-12 345,678900"}, // Arabic, ar_AE {6, -12345.6789, "\u200f- ٫ ٬", "", "\u200f-12٬345٫678900"}, {6, -12345.6789, "\u200f-|٫| ", "|", "\u200f-12 345٫678900"}, } for _, cas := range cases { var s string var err error if len(cas.runes) == 0 { s, err = ns.FormatNumberCustom(cas.prec, cas.n) } else { if cas.delim == "" { s, err = ns.FormatNumberCustom(cas.prec, cas.n, cas.runes) } else { s, err = ns.FormatNumberCustom(cas.prec, cas.n, cas.runes, cas.delim) } } c.Assert(err, qt.IsNil) c.Assert(s, qt.Equals, cas.want) } } func TestFormatNumbers(t *testing.T) { c := qt.New(t) nsNn := New(&deps.Deps{}, translators.GetTranslator("nn")) nsEn := New(&deps.Deps{}, translators.GetTranslator("en")) pi := 3.14159265359 c.Run("FormatNumber", func(c *qt.C) { c.Parallel() got, err := nsNn.FormatNumber(3, pi) c.Assert(err, qt.IsNil) c.Assert(got, qt.Equals, "3,142") got, err = nsEn.FormatNumber(3, pi) c.Assert(err, qt.IsNil) c.Assert(got, qt.Equals, "3.142") }) c.Run("FormatPercent", func(c *qt.C) { c.Parallel() got, err := nsEn.FormatPercent(3, 67.33333) c.Assert(err, qt.IsNil) c.Assert(got, qt.Equals, "67.333%") }) c.Run("FormatCurrency", func(c *qt.C) { c.Parallel() got, err := nsEn.FormatCurrency(2, "USD", 20000) c.Assert(err, qt.IsNil) c.Assert(got, qt.Equals, "$20,000.00") }) c.Run("FormatAccounting", func(c *qt.C) { c.Parallel() got, err := nsEn.FormatAccounting(2, "USD", 20000) c.Assert(err, qt.IsNil) c.Assert(got, qt.Equals, "$20,000.00") }) } // Issue 9446 func TestLanguageKeyFormat(t *testing.T) { c := qt.New(t) nsUnderscoreUpper := New(&deps.Deps{}, translators.GetTranslator("es_ES")) nsUnderscoreLower := New(&deps.Deps{}, translators.GetTranslator("es_es")) nsHyphenUpper := New(&deps.Deps{}, translators.GetTranslator("es-ES")) nsHyphenLower := New(&deps.Deps{}, translators.GetTranslator("es-es")) pi := 3.14159265359 c.Run("FormatNumber", func(c *qt.C) { c.Parallel() got, err := nsUnderscoreUpper.FormatNumber(3, pi) c.Assert(err, qt.IsNil) c.Assert(got, qt.Equals, "3,142") got, err = nsUnderscoreLower.FormatNumber(3, pi) c.Assert(err, qt.IsNil) c.Assert(got, qt.Equals, "3,142") got, err = nsHyphenUpper.FormatNumber(3, pi) c.Assert(err, qt.IsNil) c.Assert(got, qt.Equals, "3,142") got, err = nsHyphenLower.FormatNumber(3, pi) c.Assert(err, qt.IsNil) c.Assert(got, qt.Equals, "3,142") }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/lang/lang.go
tpl/lang/lang.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 lang provides template functions for content internationalization. package lang import ( "context" "errors" "fmt" "math" "strconv" "strings" "github.com/gohugoio/locales" translators "github.com/gohugoio/localescompressed" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/deps" "github.com/spf13/cast" ) // New returns a new instance of the lang-namespaced template functions. func New(deps *deps.Deps, translator locales.Translator) *Namespace { return &Namespace{ translator: translator, deps: deps, } } // Namespace provides template functions for the "lang" namespace. type Namespace struct { translator locales.Translator deps *deps.Deps } // Translate returns a translated string for id. func (ns *Namespace) Translate(ctx context.Context, id any, args ...any) (string, error) { var templateData any if len(args) > 0 { if len(args) > 1 { return "", fmt.Errorf("wrong number of arguments, expecting at most 2, got %d", len(args)+1) } templateData = args[0] } sid, err := cast.ToStringE(id) if err != nil { return "", err } return ns.deps.Translate(ctx, sid, templateData), nil } // FormatNumber formats number with the given precision for the current language. func (ns *Namespace) FormatNumber(precision, number any) (string, error) { p, n, err := ns.castPrecisionNumber(precision, number) if err != nil { return "", err } return ns.translator.FmtNumber(n, p), nil } // FormatPercent formats number with the given precision for the current language. // Note that the number is assumed to be a percentage. func (ns *Namespace) FormatPercent(precision, number any) (string, error) { p, n, err := ns.castPrecisionNumber(precision, number) if err != nil { return "", err } return ns.translator.FmtPercent(n, p), nil } // FormatCurrency returns the currency representation of number for the given currency and precision // for the current language. // // The return value is formatted with at least two decimal places. func (ns *Namespace) FormatCurrency(precision, currency, number any) (string, error) { p, n, err := ns.castPrecisionNumber(precision, number) if err != nil { return "", err } c := translators.GetCurrency(cast.ToString(currency)) if c < 0 { return "", fmt.Errorf("unknown currency code: %q", currency) } return ns.translator.FmtCurrency(n, p, c), nil } // FormatAccounting returns the currency representation of number for the given currency and precision // for the current language in accounting notation. // // The return value is formatted with at least two decimal places. func (ns *Namespace) FormatAccounting(precision, currency, number any) (string, error) { p, n, err := ns.castPrecisionNumber(precision, number) if err != nil { return "", err } c := translators.GetCurrency(cast.ToString(currency)) if c < 0 { return "", fmt.Errorf("unknown currency code: %q", currency) } return ns.translator.FmtAccounting(n, p, c), nil } func (ns *Namespace) castPrecisionNumber(precision, number any) (uint64, float64, error) { p, err := cast.ToUint64E(precision) if err != nil { return 0, 0, err } // Sanity check. if p > 20 { return 0, 0, fmt.Errorf("invalid precision: %d", precision) } n, err := cast.ToFloat64E(number) if err != nil { return 0, 0, err } return p, n, nil } // FormatNumberCustom formats a number with the given precision. The first // options parameter is a space-delimited string of characters to represent // negativity, the decimal point, and grouping. The default value is `- . ,`. // The second options parameter defines an alternate delimiting character. // // Note that numbers are rounded up at 5 or greater. // So, with precision set to 0, 1.5 becomes `2`, and 1.4 becomes `1`. // // For a simpler function that adapts to the current language, see FormatNumber. func (ns *Namespace) FormatNumberCustom(precision, number any, options ...any) (string, error) { prec, err := cast.ToIntE(precision) if err != nil { return "", err } n, err := cast.ToFloat64E(number) if err != nil { return "", err } var neg, dec, grp string if len(options) == 0 { // defaults neg, dec, grp = "-", ".", "," } else { delim := " " if len(options) == 2 { // custom delimiter s, err := cast.ToStringE(options[1]) if err != nil { return "", err } delim = s } s, err := cast.ToStringE(options[0]) if err != nil { return "", err } rs := strings.Split(s, delim) switch len(rs) { case 0: case 1: neg = rs[0] case 2: neg, dec = rs[0], rs[1] case 3: neg, dec, grp = rs[0], rs[1], rs[2] default: return "", errors.New("too many fields in options parameter to NumFmt") } } exp := math.Pow(10.0, float64(prec)) r := math.Round(n*exp) / exp // Logic from MIT Licensed github.com/gohugoio/locales/ // Original Copyright (c) 2016 Go Playground s := strconv.FormatFloat(math.Abs(r), 'f', prec, 64) L := len(s) + 2 + len(s[:len(s)-1-prec])/3 var count int inWhole := prec == 0 b := make([]byte, 0, L) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { for j := len(dec) - 1; j >= 0; j-- { b = append(b, dec[j]) } inWhole = true continue } if inWhole { if count == 3 { for j := len(grp) - 1; j >= 0; j-- { b = append(b, grp[j]) } count = 1 } else { count++ } } b = append(b, s[i]) } if n < 0 { for j := len(neg) - 1; j >= 0; j-- { b = append(b, neg[j]) } } // reverse for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } return string(b), nil } type pagesLanguageMerger interface { MergeByLanguageInterface(other any) (any, error) } // Merge creates a union of pages from two languages. func (ns *Namespace) Merge(p2, p1 any) (any, error) { if !hreflect.IsTruthful(p1) { return p2, nil } if !hreflect.IsTruthful(p2) { return p1, nil } merger, ok := p1.(pagesLanguageMerger) if !ok { return nil, fmt.Errorf("language merge not supported for %T", p1) } return merger.MergeByLanguageInterface(p2) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/encoding/init.go
tpl/encoding/init.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 encoding import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const name = "encoding" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New() ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.Base64Decode, []string{"base64Decode"}, [][2]string{ {`{{ "SGVsbG8gd29ybGQ=" | base64Decode }}`, `Hello world`}, {`{{ 42 | base64Encode | base64Decode }}`, `42`}, }, ) ns.AddMethodMapping(ctx.Base64Encode, []string{"base64Encode"}, [][2]string{ {`{{ "Hello world" | base64Encode }}`, `SGVsbG8gd29ybGQ=`}, }, ) ns.AddMethodMapping(ctx.Jsonify, []string{"jsonify"}, [][2]string{ {`{{ (slice "A" "B" "C") | jsonify }}`, `["A","B","C"]`}, {`{{ (slice "A" "B" "C") | jsonify (dict "indent" " ") }}`, "[\n \"A\",\n \"B\",\n \"C\"\n]"}, }, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/encoding/encoding_test.go
tpl/encoding/encoding_test.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 encoding import ( "html/template" "math" "testing" qt "github.com/frankban/quicktest" ) type tstNoStringer struct{} func TestBase64Decode(t *testing.T) { t.Parallel() c := qt.New(t) ns := New() for _, test := range []struct { v any expect any }{ {"YWJjMTIzIT8kKiYoKSctPUB+", "abc123!?$*&()'-=@~"}, // errors {t, false}, } { result, err := ns.Base64Decode(test.v) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestBase64Encode(t *testing.T) { t.Parallel() c := qt.New(t) ns := New() for _, test := range []struct { v any expect any }{ {"YWJjMTIzIT8kKiYoKSctPUB+", "WVdKak1USXpJVDhrS2lZb0tTY3RQVUIr"}, // errors {t, false}, } { result, err := ns.Base64Encode(test.v) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestJsonify(t *testing.T) { t.Parallel() c := qt.New(t) ns := New() for i, test := range []struct { opts any v any expect any }{ {nil, []string{"a", "b"}, template.HTML(`["a","b"]`)}, {map[string]string{"indent": "<i>"}, []string{"a", "b"}, template.HTML("[\n<i>\"a\",\n<i>\"b\"\n]")}, {map[string]string{"prefix": "<p>"}, []string{"a", "b"}, template.HTML("[\n<p>\"a\",\n<p>\"b\"\n<p>]")}, {map[string]string{"prefix": "<p>", "indent": "<i>"}, []string{"a", "b"}, template.HTML("[\n<p><i>\"a\",\n<p><i>\"b\"\n<p>]")}, {map[string]string{"indent": "<i>"}, []string{"a", "b"}, template.HTML("[\n<i>\"a\",\n<i>\"b\"\n]")}, {map[string]any{"noHTMLEscape": false}, []string{"<a>", "<b>"}, template.HTML("[\"\\u003ca\\u003e\",\"\\u003cb\\u003e\"]")}, {map[string]any{"noHTMLEscape": true}, []string{"<a>", "<b>"}, template.HTML("[\"<a>\",\"<b>\"]")}, {nil, tstNoStringer{}, template.HTML("{}")}, {nil, nil, template.HTML("null")}, // errors {nil, math.NaN(), false}, {tstNoStringer{}, []string{"a", "b"}, false}, } { args := []any{} if test.opts != nil { args = append(args, test.opts) } args = append(args, test.v) result, err := ns.Jsonify(args...) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil), qt.Commentf("#%d", i)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect, qt.Commentf("#%d", i)) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/encoding/encoding.go
tpl/encoding/encoding.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 encoding provides template functions for encoding content. package encoding import ( "encoding/base64" "encoding/json" "errors" "html/template" bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/common/maps" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" ) // New returns a new instance of the encoding-namespaced template functions. func New() *Namespace { return &Namespace{} } // Namespace provides template functions for the "encoding" namespace. type Namespace struct{} // Base64Decode returns the base64 decoding of the given content. func (ns *Namespace) Base64Decode(content any) (string, error) { conv, err := cast.ToStringE(content) if err != nil { return "", err } dec, err := base64.StdEncoding.DecodeString(conv) return string(dec), err } // Base64Encode returns the base64 encoding of the given content. func (ns *Namespace) Base64Encode(content any) (string, error) { conv, err := cast.ToStringE(content) if err != nil { return "", err } return base64.StdEncoding.EncodeToString([]byte(conv)), nil } // Jsonify encodes a given object to JSON. To pretty print the JSON, pass a map // or dictionary of options as the first value in args. Supported options are // "prefix" and "indent". Each JSON element in the output will begin on a new // line beginning with prefix followed by one or more copies of indent according // to the indentation nesting. func (ns *Namespace) Jsonify(args ...any) (template.HTML, error) { var ( b []byte err error obj any opts jsonifyOpts ) switch len(args) { case 0: return "", nil case 1: obj = args[0] case 2: var m map[string]any m, err = maps.ToStringMapE(args[0]) if err != nil { break } if err = mapstructure.WeakDecode(m, &opts); err != nil { break } obj = args[1] default: err = errors.New("too many arguments to jsonify") } if err != nil { return "", err } buff := bp.GetBuffer() defer bp.PutBuffer(buff) e := json.NewEncoder(buff) e.SetEscapeHTML(!opts.NoHTMLEscape) e.SetIndent(opts.Prefix, opts.Indent) if err = e.Encode(obj); err != nil { return "", err } b = buff.Bytes() // See https://github.com/golang/go/issues/37083 // Hugo changed from MarshalIndent/Marshal. To make the output // the same, we need to trim the trailing newline. b = b[:len(b)-1] return template.HTML(b), nil } type jsonifyOpts struct { Prefix string Indent string NoHTMLEscape bool }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/hash/hash.go
tpl/hash/hash.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package hash provides non-cryptographic hash functions for template use. package hash import ( "context" "hash/fnv" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" "github.com/spf13/cast" ) // New returns a new instance of the hash-namespaced template functions. func New() *Namespace { return &Namespace{} } // Namespace provides template functions for the "hash" namespace. type Namespace struct{} // FNV32a hashes v using fnv32a algorithm. func (ns *Namespace) FNV32a(v any) (int, error) { conv, err := cast.ToStringE(v) if err != nil { return 0, err } algorithm := fnv.New32a() algorithm.Write([]byte(conv)) return int(algorithm.Sum32()), nil } // XxHash returns the xxHash of the input string. func (ns *Namespace) XxHash(v any) (string, error) { conv, err := cast.ToStringE(v) if err != nil { return "", err } return hashing.XxHashFromStringHexEncoded(conv), nil } const name = "hash" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New() ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.FNV32a, nil, [][2]string{ {`{{ hash.FNV32a "Hugo Rocks!!" }}`, `1515779328`}, }, ) ns.AddMethodMapping(ctx.XxHash, []string{"xxhash"}, [][2]string{ {`{{ hash.XxHash "The quick brown fox jumps over the lazy dog" }}`, `0b242d361fda71bc`}, }, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/hash/hash_test.go
tpl/hash/hash_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package hash provides non-cryptographic hash functions for template use. package hash import ( "crypto/md5" "encoding/hex" "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/spf13/cast" ) func TestXxHash(t *testing.T) { t.Parallel() c := qt.New(t) ns := New() h, err := ns.XxHash("The quick brown fox jumps over the lazy dog") c.Assert(err, qt.IsNil) // Facit: https://asecuritysite.com/encryption/xxhash?val=The%20quick%20brown%20fox%20jumps%20over%20the%20lazy%20dog c.Assert(h, qt.Equals, "0b242d361fda71bc") } func BenchmarkXxHash(b *testing.B) { const inputSmall = "The quick brown fox jumps over the lazy dog" inputLarge := strings.Repeat(inputSmall, 100) runBench := func(name, input string, b *testing.B, fn func(v any)) { b.Run(fmt.Sprintf("%s_%d", name, len(input)), func(b *testing.B) { for b.Loop() { fn(input) } }) } ns := New() fnXxHash := func(v any) { _, err := ns.XxHash(v) if err != nil { panic(err) } } fnFNv32a := func(v any) { _, err := ns.FNV32a(v) if err != nil { panic(err) } } // Copied from the crypto tpl/crypto package, // just to have something to compare the above with. fnMD5 := func(v any) { conv, err := cast.ToStringE(v) if err != nil { panic(err) } hash := md5.Sum([]byte(conv)) _ = hex.EncodeToString(hash[:]) } for _, input := range []string{inputSmall, inputLarge} { runBench("xxHash", input, b, fnXxHash) runBench("mdb5", input, b, fnMD5) runBench("fnv32a", input, b, fnFNv32a) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/css/css.go
tpl/css/css.go
package css import ( "context" "errors" "fmt" "sync" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/types/css" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_transformers/babel" "github.com/gohugoio/hugo/resources/resource_transformers/cssjs" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" "github.com/gohugoio/hugo/tpl/internal" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" "github.com/spf13/cast" ) const name = "css" // Namespace provides template functions for the "css" namespace. type Namespace struct { d *deps.Deps scssClientLibSass *scss.Client postcssClient *cssjs.PostCSSClient tailwindcssClient *cssjs.TailwindCSSClient babelClient *babel.Client // The Dart Client requires a os/exec process, so only // create it if we really need it. // This is mostly to avoid creating one per site build test. scssClientDartSassInit sync.Once scssClientDartSass *dartsass.Client } // Quoted returns a string that needs to be quoted in CSS. func (ns *Namespace) Quoted(v any) css.QuotedString { s := cast.ToString(v) return css.QuotedString(s) } // Unquoted returns a string that does not need to be quoted in CSS. func (ns *Namespace) Unquoted(v any) css.UnquotedString { s := cast.ToString(v) return css.UnquotedString(s) } // PostCSS processes the given Resource with PostCSS. func (ns *Namespace) PostCSS(args ...any) (resource.Resource, error) { if len(args) > 2 { return nil, errors.New("must not provide more arguments than resource object and options") } r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } return ns.postcssClient.Process(r, m) } // TailwindCSS processes the given Resource with tailwindcss. func (ns *Namespace) TailwindCSS(args ...any) (resource.Resource, error) { if len(args) > 2 { return nil, errors.New("must not provide more arguments than resource object and options") } r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } return ns.tailwindcssClient.Process(r, m) } // Sass processes the given Resource with SASS. func (ns *Namespace) Sass(args ...any) (resource.Resource, error) { if len(args) > 2 { return nil, errors.New("must not provide more arguments than resource object and options") } var ( r resources.ResourceTransformer m map[string]any targetPath string err error ok bool transpiler = sass.TranspilerLibSass // Deprecated default. Will be dartsass in future versions. See below. ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if m != nil { if t, _, found := maps.LookupEqualFold(m, "transpiler"); found { switch t { case sass.TranspilerDart: transpiler = cast.ToString(t) case sass.TranspilerLibSass: hugo.Deprecate("css.Sass: libsass", "Use dartsass instead. See https://gohugo.io/functions/css/sass/#dart-sass", "v0.153.0") transpiler = cast.ToString(t) default: return nil, fmt.Errorf("unsupported transpiler %q; valid values are %q or %q", t, sass.TranspilerLibSass, sass.TranspilerDart) } } } if transpiler == sass.TranspilerLibSass { var options scss.Options if targetPath != "" { options.TargetPath = paths.ToSlashTrimLeading(targetPath) } else if m != nil { options, err = scss.DecodeOptions(m) if err != nil { return nil, err } } return ns.scssClientLibSass.ToCSS(r, options) } if m == nil { m = make(map[string]any) } if targetPath != "" { m["targetPath"] = targetPath } client, err := ns.getscssClientDartSass() if err != nil { return nil, err } return client.ToCSS(r, m) } func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { scssClient, err := scss.New(d.BaseFs.Assets, d.ResourceSpec) if err != nil { panic(err) } ctx := &Namespace{ d: d, scssClientLibSass: scssClient, postcssClient: cssjs.NewPostCSSClient(d.ResourceSpec), tailwindcssClient: cssjs.NewTailwindCSSClient(d.ResourceSpec), babelClient: babel.New(d.ResourceSpec), } ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.PostCSS, []string{"postCSS"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Quoted, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Sass, []string{"toCSS"}, [][2]string{}, ) ns.AddMethodMapping(ctx.TailwindCSS, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Unquoted, nil, [][2]string{}, ) return ns } internal.AddTemplateFuncsNamespace(f) } func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) { var err error ns.scssClientDartSassInit.Do(func() { ns.scssClientDartSass, err = dartsass.New(ns.d.BaseFs.Assets, ns.d.ResourceSpec) if err != nil { return } ns.d.BuildClosers.Add(ns.scssClientDartSass) }) return ns.scssClientDartSass, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/inflect/init.go
tpl/inflect/init.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 inflect import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const name = "inflect" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New() ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.Humanize, []string{"humanize"}, [][2]string{ {`{{ humanize "my-first-post" }}`, `My first post`}, {`{{ humanize "myCamelPost" }}`, `My camel post`}, {`{{ humanize "52" }}`, `52nd`}, {`{{ humanize 103 }}`, `103rd`}, }, ) ns.AddMethodMapping(ctx.Pluralize, []string{"pluralize"}, [][2]string{ {`{{ "cat" | pluralize }}`, `cats`}, }, ) ns.AddMethodMapping(ctx.Singularize, []string{"singularize"}, [][2]string{ {`{{ "cats" | singularize }}`, `cat`}, }, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/inflect/inflect.go
tpl/inflect/inflect.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 inflect provides template functions for the inflection of words. package inflect import ( "strconv" "strings" _inflect "github.com/gobuffalo/flect" "github.com/spf13/cast" ) // New returns a new instance of the inflect-namespaced template functions. func New() *Namespace { return &Namespace{} } // Namespace provides template functions for the "inflect" namespace. type Namespace struct{} // Humanize returns the humanized form of v. // // If v is either an integer or a string containing an integer // value, the behavior is to add the appropriate ordinal. func (ns *Namespace) Humanize(v any) (string, error) { word, err := cast.ToStringE(v) if err != nil { return "", err } if word == "" { return "", nil } _, ok := v.(int) // original param was literal int value _, err = strconv.Atoi(word) // original param was string containing an int value if ok || err == nil { return _inflect.Ordinalize(word), nil } str := _inflect.Humanize(word) return _inflect.Humanize(strings.ToLower(str)), nil } // Pluralize returns the plural form of the single word in v. func (ns *Namespace) Pluralize(v any) (string, error) { word, err := cast.ToStringE(v) if err != nil { return "", err } return _inflect.Pluralize(word), nil } // Singularize returns the singular form of a single word in v. func (ns *Namespace) Singularize(v any) (string, error) { word, err := cast.ToStringE(v) if err != nil { return "", err } return _inflect.Singularize(word), nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/inflect/inflect_test.go
tpl/inflect/inflect_test.go
package inflect import ( "testing" qt "github.com/frankban/quicktest" ) func TestInflect(t *testing.T) { t.Parallel() c := qt.New(t) ns := New() for _, test := range []struct { fn func(i any) (string, error) in any expect any }{ {ns.Humanize, "MyCamel", "My camel"}, {ns.Humanize, "óbito", "Óbito"}, {ns.Humanize, "", ""}, {ns.Humanize, "103", "103rd"}, {ns.Humanize, "41", "41st"}, {ns.Humanize, 103, "103rd"}, {ns.Humanize, int64(92), "92nd"}, {ns.Humanize, "5.5", "5.5"}, {ns.Humanize, t, false}, {ns.Humanize, "this is a TEST", "This is a test"}, {ns.Humanize, "my-first-Post", "My first post"}, {ns.Pluralize, "cat", "cats"}, {ns.Pluralize, "", ""}, {ns.Pluralize, t, false}, {ns.Singularize, "cats", "cat"}, {ns.Singularize, "", ""}, {ns.Singularize, t, false}, } { result, err := test.fn(test.in) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/math/init.go
tpl/math/init.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 import ( "context" "runtime" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const name = "math" func init() { mathAtan1 := "0.7853981633974483" mathTan1 := "1.557407724654902" if runtime.GOARCH == "s390x" { mathAtan1 = "0.7853981633974484" mathTan1 = "1.5574077246549018" } f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New(d) ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.Abs, nil, [][2]string{ {"{{ math.Abs -2.1 }}", "2.1"}, }, ) ns.AddMethodMapping(ctx.Acos, nil, [][2]string{ {"{{ math.Acos 1 }}", "0"}, }, ) ns.AddMethodMapping(ctx.Add, []string{"add"}, [][2]string{ {"{{ add 1 2 }}", "3"}, }, ) ns.AddMethodMapping(ctx.Asin, nil, [][2]string{ {"{{ math.Asin 1 }}", "1.5707963267948966"}, }, ) ns.AddMethodMapping(ctx.Atan, nil, [][2]string{ {"{{ math.Atan 1 }}", mathAtan1}, }, ) ns.AddMethodMapping(ctx.Atan2, nil, [][2]string{ {"{{ math.Atan2 1 2 }}", "0.4636476090008061"}, }, ) ns.AddMethodMapping(ctx.Ceil, nil, [][2]string{ {"{{ math.Ceil 2.1 }}", "3"}, }, ) ns.AddMethodMapping(ctx.Cos, nil, [][2]string{ {"{{ math.Cos 1 }}", "0.5403023058681398"}, }, ) ns.AddMethodMapping(ctx.Counter, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Div, []string{"div"}, [][2]string{ {"{{ div 6 3 }}", "2"}, }, ) ns.AddMethodMapping(ctx.Floor, nil, [][2]string{ {"{{ math.Floor 1.9 }}", "1"}, }, ) ns.AddMethodMapping(ctx.Log, nil, [][2]string{ {"{{ math.Log 1 }}", "0"}, }, ) ns.AddMethodMapping(ctx.Max, nil, [][2]string{ {"{{ math.Max 1 2 }}", "2"}, }, ) ns.AddMethodMapping(ctx.MaxInt64, nil, [][2]string{ {"{{ math.MaxInt64 }}", "9223372036854775807"}, }, ) ns.AddMethodMapping(ctx.Min, nil, [][2]string{ {"{{ math.Min 1 2 }}", "1"}, }, ) ns.AddMethodMapping(ctx.Mod, []string{"mod"}, [][2]string{ {"{{ mod 15 3 }}", "0"}, }, ) ns.AddMethodMapping(ctx.ModBool, []string{"modBool"}, [][2]string{ {"{{ modBool 15 3 }}", "true"}, }, ) ns.AddMethodMapping(ctx.Mul, []string{"mul"}, [][2]string{ {"{{ mul 2 3 }}", "6"}, }, ) ns.AddMethodMapping(ctx.Pi, nil, [][2]string{ {"{{ math.Pi }}", "3.141592653589793"}, }, ) ns.AddMethodMapping(ctx.Pow, []string{"pow"}, [][2]string{ {"{{ math.Pow 2 3 }}", "8"}, }, ) ns.AddMethodMapping(ctx.Product, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Rand, nil, [][2]string{ {"{{ math.Rand }}", "0.6312770459590062"}, }, ) ns.AddMethodMapping(ctx.Round, nil, [][2]string{ {"{{ math.Round 1.5 }}", "2"}, }, ) ns.AddMethodMapping(ctx.Sin, nil, [][2]string{ {"{{ math.Sin 1 }}", "0.8414709848078965"}, }, ) ns.AddMethodMapping(ctx.Sqrt, nil, [][2]string{ {"{{ math.Sqrt 81 }}", "9"}, }, ) ns.AddMethodMapping(ctx.Sub, []string{"sub"}, [][2]string{ {"{{ sub 3 2 }}", "1"}, }, ) ns.AddMethodMapping(ctx.Sum, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Tan, nil, [][2]string{ {"{{ math.Tan 1 }}", mathTan1}, }, ) ns.AddMethodMapping(ctx.ToDegrees, nil, [][2]string{ {"{{ math.ToDegrees 1.5707963267948966 }}", "90"}, }, ) ns.AddMethodMapping(ctx.ToRadians, nil, [][2]string{ {"{{ math.ToRadians 90 }}", "1.5707963267948966"}, }, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/math/math_test.go
tpl/math/math_test.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 import ( "math" "testing" qt "github.com/frankban/quicktest" ) func TestBasicNSArithmetic(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) type TestCase struct { fn func(inputs ...any) (any, error) values []any expect any } for _, test := range []TestCase{ {ns.Add, []any{4, 2}, int64(6)}, {ns.Add, []any{4, 2, 5}, int64(11)}, {ns.Add, []any{1.0, "foo"}, false}, {ns.Add, []any{0}, false}, {ns.Sub, []any{4, 2}, int64(2)}, {ns.Sub, []any{4, 2, 5}, int64(-3)}, {ns.Sub, []any{1.0, "foo"}, false}, {ns.Sub, []any{0}, false}, {ns.Mul, []any{4, 2}, int64(8)}, {ns.Mul, []any{4, 2, 5}, int64(40)}, {ns.Mul, []any{1.0, "foo"}, false}, {ns.Mul, []any{0}, false}, {ns.Div, []any{4, 2}, int64(2)}, {ns.Div, []any{4, 2, 5}, int64(0)}, {ns.Div, []any{1.0, "foo"}, false}, {ns.Div, []any{0}, false}, } { result, err := test.fn(test.values...) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestAbs(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any expect any }{ {0.0, 0.0}, {1.5, 1.5}, {-1.5, 1.5}, {-2, 2.0}, {"abc", false}, } { result, err := ns.Abs(test.x) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestCeil(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any expect any }{ {0.1, 1.0}, {0.5, 1.0}, {1.1, 2.0}, {1.5, 2.0}, {-0.1, 0.0}, {-0.5, 0.0}, {-1.1, -1.0}, {-1.5, -1.0}, {"abc", false}, } { result, err := ns.Ceil(test.x) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestFloor(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any expect any }{ {0.1, 0.0}, {0.5, 0.0}, {1.1, 1.0}, {1.5, 1.0}, {-0.1, -1.0}, {-0.5, -1.0}, {-1.1, -2.0}, {-1.5, -2.0}, {"abc", false}, } { result, err := ns.Floor(test.x) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestLog(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { a any expect any }{ {1, 0.0}, {3, 1.0986}, {0, math.Inf(-1)}, {1.0, 0.0}, {3.1, 1.1314}, {"abc", false}, } { result, err := ns.Log(test.a) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions if result != math.Inf(-1) { result = float64(int(result*10000)) / 10000 } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } // Separate test for Log(-1) -- returns NaN result, err := ns.Log(-1) c.Assert(err, qt.IsNil) c.Assert(result, qt.Satisfies, math.IsNaN) } func TestSqrt(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { a any expect any }{ {81, 9.0}, {0.25, 0.5}, {0, 0.0}, {"abc", false}, } { result, err := ns.Sqrt(test.a) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions if result != math.Inf(-1) { result = float64(int(result*10000)) / 10000 } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } // Separate test for Sqrt(-1) -- returns NaN result, err := ns.Sqrt(-1) c.Assert(err, qt.IsNil) c.Assert(result, qt.Satisfies, math.IsNaN) } func TestMod(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { a any b any expect any }{ {3, 2, int64(1)}, {3, 1, int64(0)}, {3, 0, false}, {0, 3, int64(0)}, {3.1, 2, int64(1)}, {3, 2.1, int64(1)}, {3.1, 2.1, int64(1)}, {int8(3), int8(2), int64(1)}, {int16(3), int16(2), int64(1)}, {int32(3), int32(2), int64(1)}, {int64(3), int64(2), int64(1)}, {"3", "2", int64(1)}, {"3.1", "2", int64(1)}, {"aaa", "0", false}, {"3", "aaa", false}, } { result, err := ns.Mod(test.a, test.b) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestModBool(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { a any b any expect any }{ {3, 3, true}, {3, 2, false}, {3, 1, true}, {3, 0, nil}, {0, 3, true}, {3.1, 2, false}, {3, 2.1, false}, {3.1, 2.1, false}, {int8(3), int8(3), true}, {int8(3), int8(2), false}, {int16(3), int16(3), true}, {int16(3), int16(2), false}, {int32(3), int32(3), true}, {int32(3), int32(2), false}, {int64(3), int64(3), true}, {int64(3), int64(2), false}, {"3", "3", true}, {"3", "2", false}, {"3.1", "2", false}, {"aaa", "0", nil}, {"3", "aaa", nil}, } { result, err := ns.ModBool(test.a, test.b) if test.expect == nil { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestRound(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any expect any }{ {0.1, 0.0}, {0.5, 1.0}, {1.1, 1.0}, {1.5, 2.0}, {-0.1, 0.0}, {-0.5, -1.0}, {-1.1, -1.0}, {-1.5, -2.0}, {"abc", false}, } { result, err := ns.Round(test.x) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestPow(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { a any b any expect any }{ {0, 0, 1.0}, {2, 0, 1.0}, {2, 3, 8.0}, {-2, 3, -8.0}, {2, -3, 0.125}, {-2, -3, -0.125}, {0.2, 3, 0.008}, {2, 0.3, 1.2311}, {0.2, 0.3, 0.617}, {"aaa", "3", false}, {"2", "aaa", false}, } { result, err := ns.Pow(test.a, test.b) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestMax(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) type TestCase struct { values []any expect any } for _, test := range []TestCase{ // two values {[]any{-1, -1}, -1.0}, {[]any{-1, 0}, 0.0}, {[]any{-1, 1}, 1.0}, {[]any{0, -1}, 0.0}, {[]any{0, 0}, 0.0}, {[]any{0, 1}, 1.0}, {[]any{1, -1}, 1.0}, {[]any{1, 0}, 1.0}, {[]any{32}, 32.0}, {[]any{1, 1}, 1.0}, {[]any{1.2, 1.23}, 1.23}, {[]any{-1.2, -1.23}, -1.2}, {[]any{0, "a"}, false}, {[]any{"a", 0}, false}, {[]any{"a", "b"}, false}, // Issue #11030 {[]any{7, []any{3, 4}}, 7.0}, {[]any{8, []any{3, 12}, 3}, 12.0}, {[]any{[]any{3, 5, 2}}, 5.0}, {[]any{3, []int{3, 6}, 3}, 6.0}, // No values. {[]any{}, false}, // multi values {[]any{-1, -2, -3}, -1.0}, {[]any{1, 2, 3}, 3.0}, {[]any{"a", 2, 3}, false}, } { result, err := ns.Max(test.values...) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } msg := qt.Commentf("values: %v", test.values) c.Assert(err, qt.IsNil, msg) c.Assert(result, qt.Equals, test.expect, msg) } } func TestMin(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) type TestCase struct { values []any expect any } for _, test := range []TestCase{ // two values {[]any{-1, -1}, -1.0}, {[]any{-1, 0}, -1.0}, {[]any{-1, 1}, -1.0}, {[]any{0, -1}, -1.0}, {[]any{0, 0}, 0.0}, {[]any{0, 1}, 0.0}, {[]any{1, -1}, -1.0}, {[]any{1, 0}, 0.0}, {[]any{1, 1}, 1.0}, {[]any{2}, 2.0}, {[]any{1.2, 1.23}, 1.2}, {[]any{-1.2, -1.23}, -1.23}, {[]any{0, "a"}, false}, {[]any{"a", 0}, false}, {[]any{"a", "b"}, false}, // Issue #11030 {[]any{1, []any{3, 4}}, 1.0}, {[]any{8, []any{3, 2}, 3}, 2.0}, {[]any{[]any{3, 2, 2}}, 2.0}, {[]any{8, []int{3, 2}, 3}, 2.0}, // No values. {[]any{}, false}, // multi values {[]any{-1, -2, -3}, -3.0}, {[]any{1, 2, 3}, 1.0}, {[]any{"a", 2, 3}, false}, } { result, err := ns.Min(test.values...) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil, qt.Commentf("values: %v", test.values)) c.Assert(result, qt.Equals, test.expect) } } func TestSum(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) mustSum := func(values ...any) any { result, err := ns.Sum(values...) c.Assert(err, qt.IsNil) return result } c.Assert(mustSum(1, 2, 3), qt.Equals, 6.0) c.Assert(mustSum(1, 2, 3.0), qt.Equals, 6.0) c.Assert(mustSum(1, 2, []any{3, 4}), qt.Equals, 10.0) c.Assert(mustSum(23), qt.Equals, 23.0) c.Assert(mustSum([]any{23}), qt.Equals, 23.0) c.Assert(mustSum([]any{}), qt.Equals, 0.0) _, err := ns.Sum() c.Assert(err, qt.Not(qt.IsNil)) } func TestProduct(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) mustProduct := func(values ...any) any { result, err := ns.Product(values...) c.Assert(err, qt.IsNil) return result } c.Assert(mustProduct(2, 2, 3), qt.Equals, 12.0) c.Assert(mustProduct(1, 2, 3.0), qt.Equals, 6.0) c.Assert(mustProduct(1, 2, []any{3, 4}), qt.Equals, 24.0) c.Assert(mustProduct(3.0), qt.Equals, 3.0) c.Assert(mustProduct([]string{}), qt.Equals, 0.0) _, err := ns.Product() c.Assert(err, qt.Not(qt.IsNil)) } // Test trigonometric functions func TestPi(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) expect := 3.1415 result := ns.Pi() // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(result, qt.Equals, expect) } func TestSin(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { a any expect any }{ {0, 0.0}, {1, 0.8414}, {math.Pi / 2, 1.0}, {math.Pi, 0.0}, {-1.0, -0.8414}, {"abc", false}, } { result, err := ns.Sin(test.a) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestCos(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { a any expect any }{ {0, 1.0}, {1, 0.5403}, {math.Pi / 2, 0.0}, {math.Pi, -1.0}, {-1.0, 0.5403}, {"abc", false}, } { result, err := ns.Cos(test.a) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestTan(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { a any expect any }{ {0, 0.0}, {1, 1.5574}, // {math.Pi / 2, math.Inf(1)}, {math.Pi, 0.0}, {-1.0, -1.5574}, {"abc", false}, } { result, err := ns.Tan(test.a) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions if result != math.Inf(1) { result = float64(int(result*10000)) / 10000 } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } // Separate test for Tan(oo) -- returns NaN result, err := ns.Tan(math.Inf(1)) c.Assert(err, qt.IsNil) c.Assert(result, qt.Satisfies, math.IsNaN) } // Test inverse trigonometric functions func TestAsin(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any expect any }{ {0.0, 0.0}, {1.0, 1.5707}, {-1.0, -1.5707}, {0.5, 0.5235}, {"abc", false}, } { result, err := ns.Asin(test.x) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } // Separate test for Asin(2) -- returns NaN result, err := ns.Asin(2) c.Assert(err, qt.IsNil) c.Assert(result, qt.Satisfies, math.IsNaN) } func TestAcos(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any expect any }{ {1.0, 0.0}, {0.0, 1.5707}, {-1.0, 3.1415}, {0.5, 1.0471}, {"abc", false}, } { result, err := ns.Acos(test.x) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } // Separate test for Acos(2) -- returns NaN result, err := ns.Acos(2) c.Assert(err, qt.IsNil) c.Assert(result, qt.Satisfies, math.IsNaN) } func TestAtan(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any expect any }{ {0.0, 0.0}, {1, 0.7853}, {-1.0, -0.7853}, {math.Inf(1), 1.5707}, {"abc", false}, } { result, err := ns.Atan(test.x) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestAtan2(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any y any expect any }{ {1.0, 1.0, 0.7853}, {-1.0, 1.0, -0.7853}, {1.0, -1.0, 2.3561}, {-1.0, -1.0, -2.3561}, {1, 0, 1.5707}, {-1, 0, -1.5707}, {0, 1, 0.0}, {0, -1, 3.1415}, {0.0, 0.0, 0.0}, {"abc", "def", false}, } { result, err := ns.Atan2(test.x, test.y) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } // Test angle helper functions func TestToDegrees(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any expect any }{ {0.0, 0.0}, {1, 57.2957}, {math.Pi / 2, 90.0}, {math.Pi, 180.0}, {"abc", false}, } { result, err := ns.ToDegrees(test.x) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestToRadians(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(nil) for _, test := range []struct { x any expect any }{ {0, 0.0}, {57.29577951308232, 1.0}, {90, 1.5707}, {180.0, 3.1415}, {"abc", false}, } { result, err := ns.ToRadians(test.x) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } // we compare only 4 digits behind point if its a real float // otherwise we usually get different float values on the last positions result = float64(int(result*10000)) / 10000 c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestMaxInt64(t *testing.T) { t.Parallel() ns := New(nil) var want int64 = 9223372036854775807 got := ns.MaxInt64() if want != got { t.Errorf("want %d, got %d", want, got) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/math/math.go
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" "fmt" "math" "math/rand" "reflect" _math "github.com/gohugoio/hugo/common/math" "github.com/gohugoio/hugo/deps" "github.com/spf13/cast" ) var ( errMustTwoNumbersError = errors.New("must provide at least two numbers") errMustOneNumberError = errors.New("must provide at least one number") ) // New returns a new instance of the math-namespaced template functions. func New(d *deps.Deps) *Namespace { return &Namespace{ d: d, } } // Namespace provides template functions for the "math" namespace. type Namespace struct { d *deps.Deps } // 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 } // Acos returns the arccosine, in radians, of n. func (ns *Namespace) Acos(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("requires a numeric argument") } return math.Acos(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, '+') } // Asin returns the arcsine, in radians, of n. func (ns *Namespace) Asin(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("requires a numeric argument") } return math.Asin(af), nil } // Atan returns the arctangent, in radians, of n. func (ns *Namespace) Atan(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("requires a numeric argument") } return math.Atan(af), nil } // Atan2 returns the arc tangent of n/m, using the signs of the two to determine the quadrant of the return value. func (ns *Namespace) Atan2(n, m any) (float64, error) { afx, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("requires numeric arguments") } afy, err := cast.ToFloat64E(m) if err != nil { return 0, errors.New("requires numeric arguments") } return math.Atan2(afx, afy), nil } // 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 } // Cos returns the cosine of the radian argument n. func (ns *Namespace) Cos(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("requires a numeric argument") } return math.Cos(af), 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 all numbers in inputs. Any slices in inputs are flattened. func (ns *Namespace) Max(inputs ...any) (maximum float64, err error) { return ns.applyOpToScalarsOrSlices("Max", math.Max, inputs...) } // MaxInt64 returns the maximum value for a signed 64-bit integer. func (ns *Namespace) MaxInt64() int64 { return math.MaxInt64 } // Min returns the smaller of all numbers in inputs. Any slices in inputs are flattened. func (ns *Namespace) Min(inputs ...any) (minimum float64, err error) { return ns.applyOpToScalarsOrSlices("Min", math.Min, inputs...) } // 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, '*') } // Pi returns the mathematical constant pi. func (ns *Namespace) Pi() float64 { return math.Pi } // 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 } // Product returns the product of all numbers in inputs. Any slices in inputs are flattened. func (ns *Namespace) Product(inputs ...any) (product float64, err error) { fn := func(x, y float64) float64 { return x * y } return ns.applyOpToScalarsOrSlices("Product", fn, inputs...) } // Rand returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0). func (ns *Namespace) Rand() float64 { return rand.Float64() } // 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 } // Sin returns the sine of the radian argument n. func (ns *Namespace) Sin(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("requires a numeric argument") } return math.Sin(af), 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, '-') } // Sum returns the sum of all numbers in inputs. Any slices in inputs are flattened. func (ns *Namespace) Sum(inputs ...any) (sum float64, err error) { fn := func(x, y float64) float64 { return x + y } return ns.applyOpToScalarsOrSlices("Sum", fn, inputs...) } // Tan returns the tangent of the radian argument n. func (ns *Namespace) Tan(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("requires a numeric argument") } return math.Tan(af), nil } // ToDegrees converts radians into degrees. func (ns *Namespace) ToDegrees(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("requires a numeric argument") } return af * 180 / math.Pi, nil } // ToRadians converts degrees into radians. func (ns *Namespace) ToRadians(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("requires a numeric argument") } return af * math.Pi / 180, nil } func (ns *Namespace) applyOpToScalarsOrSlices(opName string, op func(x, y float64) float64, inputs ...any) (result float64, err error) { var i int var hasValue bool for _, input := range inputs { var values []float64 var isSlice bool values, isSlice, err = ns.toFloatsE(input) if err != nil { err = fmt.Errorf("%s operator can't be used with non-float values", opName) return } hasValue = hasValue || len(values) > 0 || isSlice for _, value := range values { i++ if i == 1 { result = value continue } result = op(result, value) } } if !hasValue { err = errMustOneNumberError return } return } func (ns *Namespace) toFloatsE(v any) ([]float64, bool, error) { vv := reflect.ValueOf(v) switch vv.Kind() { case reflect.Slice, reflect.Array: var floats []float64 for i := range vv.Len() { f, err := cast.ToFloat64E(vv.Index(i).Interface()) if err != nil { return nil, true, err } floats = append(floats, f) } return floats, true, nil default: f, err := cast.ToFloat64E(v) if err != nil { return nil, false, err } return []float64{f}, false, nil } } 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 } // 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 ns.d.Counters.MathCounter.Add(1) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/math/round.go
tpl/math/round.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // According to https://github.com/golang/go/issues/20100, the Go stdlib will // include math.Round beginning with Go 1.10. // // The following implementation was taken from https://golang.org/cl/43652. package math import "math" const ( mask = 0x7FF shift = 64 - 11 - 1 bias = 1023 ) // Round returns the nearest integer, rounding half away from zero. // // Special cases are: // // Round(±0) = ±0 // Round(±Inf) = ±Inf // Round(NaN) = NaN func _round(x float64) float64 { // Round is a faster implementation of: // // func Round(x float64) float64 { // t := Trunc(x) // if Abs(x-t) >= 0.5 { // return t + Copysign(1, x) // } // return t // } const ( signMask = 1 << 63 fracMask = 1<<shift - 1 half = 1 << (shift - 1) one = bias << shift ) bits := math.Float64bits(x) e := uint(bits>>shift) & mask if e < bias { // Round abs(x) < 1 including denormals. bits &= signMask // +-0 if e == bias-1 { bits |= one // +-1 } } else if e < bias+shift { // Round any abs(x) >= 1 containing a fractional component [0,1). // // Numbers with larger exponents are returned unchanged since they // must be either an integer, infinity, or NaN. e -= bias bits += half >> e bits &^= fracMask >> e } return math.Float64frombits(bits) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/compare/init.go
tpl/compare/init.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 compare import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/tpl/internal" ) const name = "compare" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { language := d.Conf.Language().(*langs.Language) if language == nil { panic("language must be set") } ctx := New(langs.GetLocation(language), false) ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.Conditional, []string{"cond"}, [][2]string{ {`{{ cond (eq (add 2 2) 4) "2+2 is 4" "what?" | safeHTML }}`, `2+2 is 4`}, }, ) ns.AddMethodMapping(ctx.Default, []string{"default"}, [][2]string{ {`{{ "Hugo Rocks!" | default "Hugo Rules!" }}`, `Hugo Rocks!`}, {`{{ "" | default "Hugo Rules!" }}`, `Hugo Rules!`}, }, ) ns.AddMethodMapping(ctx.Eq, []string{"eq"}, [][2]string{ {`{{ if eq .Section "blog" }}current-section{{ end }}`, `current-section`}, }, ) ns.AddMethodMapping(ctx.Ge, []string{"ge"}, [][2]string{ {`{{ if ge hugo.Version "0.80" }}Reasonable new Hugo version!{{ end }}`, `Reasonable new Hugo version!`}, }, ) ns.AddMethodMapping(ctx.Gt, []string{"gt"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Le, []string{"le"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Lt, []string{"lt"}, [][2]string{}, ) // For internal use only. ns.AddMethodMapping(ctx.LtCollate, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Ne, []string{"ne"}, [][2]string{}, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/compare/compare_test.go
tpl/compare/compare_test.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 compare import ( "math" "path" "reflect" "runtime" "testing" "time" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/version" "github.com/gohugoio/hugo/htesting/hqt" "github.com/spf13/cast" ) type T struct { NonEmptyInterfaceNil I NonEmptyInterfaceTypedNil I } type I interface { Foo() string } func (t *T) Foo() string { return "foo" } var testT = &T{ NonEmptyInterfaceTypedNil: (*T)(nil), } type ( tstEqerType1 string tstEqerType2 string ) func (t tstEqerType2) Eq(other any) bool { return cast.ToString(t) == cast.ToString(other) } func (t tstEqerType2) String() string { return string(t) } func (t tstEqerType1) Eq(other any) bool { return cast.ToString(t) == cast.ToString(other) } func (t tstEqerType1) String() string { return string(t) } type stringType string type tstCompareType int const ( tstEq tstCompareType = iota tstNe tstGt tstGe tstLt tstLe ) func tstIsEq(tp tstCompareType) bool { return tp == tstEq || tp == tstGe || tp == tstLe } func tstIsGt(tp tstCompareType) bool { return tp == tstGt || tp == tstGe } func tstIsLt(tp tstCompareType) bool { return tp == tstLt || tp == tstLe } func TestDefaultFunc(t *testing.T) { t.Parallel() c := qt.New(t) then := time.Now() now := time.Now() ns := New(time.UTC, false) for i, test := range []struct { dflt any given any expect any }{ {true, false, false}, {"5", 0, "5"}, {"test1", "set", "set"}, {"test2", "", "test2"}, {"test3", nil, "test3"}, {[2]int{10, 20}, [2]int{1, 2}, [2]int{1, 2}}, {[2]int{10, 20}, [0]int{}, [2]int{10, 20}}, {[2]int{100, 200}, nil, [2]int{100, 200}}, {[]string{"one"}, []string{"uno"}, []string{"uno"}}, {[]string{"two"}, []string{}, []string{"two"}}, {[]string{"three"}, nil, []string{"three"}}, {map[string]int{"one": 1}, map[string]int{"uno": 1}, map[string]int{"uno": 1}}, {map[string]int{"one": 1}, map[string]int{}, map[string]int{"one": 1}}, {map[string]int{"two": 2}, nil, map[string]int{"two": 2}}, {10, 1, 1}, {10, 0, 10}, {20, nil, 20}, {float32(10), float32(1), float32(1)}, {float32(10), 0, float32(10)}, {float32(20), nil, float32(20)}, {complex(2, -2), complex(1, -1), complex(1, -1)}, {complex(2, -2), complex(0, 0), complex(2, -2)}, {complex(3, -3), nil, complex(3, -3)}, {struct{ f string }{f: "one"}, struct{}{}, struct{}{}}, {struct{ f string }{f: "two"}, nil, struct{ f string }{f: "two"}}, {then, now, now}, {then, time.Time{}, then}, } { eq := qt.CmpEquals(hqt.DeepAllowUnexported(test.dflt)) errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.Default(test.dflt, test.given) c.Assert(err, qt.IsNil, errMsg) c.Assert(result, eq, test.expect, errMsg) } } func TestCompare(t *testing.T) { t.Parallel() n := New(time.UTC, false) twoEq := func(a, b any) bool { return n.Eq(a, b) } twoGt := func(a, b any) bool { return n.Gt(a, b) } twoLt := func(a, b any) bool { return n.Lt(a, b) } twoGe := func(a, b any) bool { return n.Ge(a, b) } twoLe := func(a, b any) bool { return n.Le(a, b) } twoNe := func(a, b any) bool { return n.Ne(a, b) } for _, test := range []struct { tstCompareType funcUnderTest func(a, b any) bool }{ {tstGt, twoGt}, {tstLt, twoLt}, {tstGe, twoGe}, {tstLe, twoLe}, {tstEq, twoEq}, {tstNe, twoNe}, } { doTestCompare(t, test.tstCompareType, test.funcUnderTest) } } func doTestCompare(t *testing.T, tp tstCompareType, funcUnderTest func(a, b any) bool) { for i, test := range []struct { left any right any expectIndicator int }{ {5, 8, -1}, {8, 5, 1}, {5, 5, 0}, {int(5), int64(5), 0}, {int32(5), int(5), 0}, {int16(4), 4, 0}, {uint8(4), 4, 0}, {uint16(4), 4, 0}, {uint16(4), 4, 0}, {uint32(4), uint16(4), 0}, {uint32(4), uint16(3), 1}, {uint64(4), 4, 0}, {4, uint64(4), 0}, {uint64(4), 5, -1}, {5, uint64(4), 1}, {uint64(5), uint64(4), 1}, {uint64(4), uint64(5), -1}, {uint64(5), uint64(5), 0}, {uint64(math.MaxUint32), uint32(math.MaxUint32), 0}, {uint64(math.MaxUint16), int(math.MaxUint16), 0}, {int16(4), int(5), -1}, {uint(15), uint64(15), 0}, {-2, 1, -1}, {2, -5, 1}, {0.0, 1.23, -1}, {1.1, 1.1, 0}, {float32(1.0), float64(1.0), 0}, {1.23, 0.0, 1}, {"5", "5", 0}, {"8", "5", 1}, {"5", "0001", 1}, {[]int{100, 99}, []int{1, 2, 3, 4}, -1}, {cast.ToTime("2015-11-20"), cast.ToTime("2015-11-20"), 0}, {cast.ToTime("2015-11-19"), cast.ToTime("2015-11-20"), -1}, {cast.ToTime("2015-11-20"), cast.ToTime("2015-11-19"), 1}, {"a", "a", 0}, {"a", "b", -1}, {"b", "a", 1}, {"infinity", "infinity", 0}, {"nan", "nan", 0}, {tstEqerType1("a"), tstEqerType1("a"), 0}, {tstEqerType1("a"), tstEqerType2("a"), 0}, {tstEqerType2("a"), tstEqerType1("a"), 0}, {tstEqerType2("a"), tstEqerType1("b"), -1}, {version.MustParseVersion("0.32.1").Version(), version.MustParseVersion("0.32").Version(), 1}, {version.MustParseVersion("0.35").Version(), version.MustParseVersion("0.32").Version(), 1}, {version.MustParseVersion("0.36").Version(), version.MustParseVersion("0.36").Version(), 0}, {version.MustParseVersion("0.32").Version(), version.MustParseVersion("0.36").Version(), -1}, {version.MustParseVersion("0.32").Version(), "0.36", -1}, {"0.36", version.MustParseVersion("0.32").Version(), 1}, {"0.36", version.MustParseVersion("0.36").Version(), 0}, {"0.37", version.MustParseVersion("0.37-DEV").Version(), 1}, {"0.37-DEV", version.MustParseVersion("0.37").Version(), -1}, {"0.36", version.MustParseVersion("0.37-DEV").Version(), -1}, {"0.37-DEV", version.MustParseVersion("0.37-DEV").Version(), 0}, // https://github.com/gohugoio/hugo/issues/5905 {nil, nil, 0}, {testT.NonEmptyInterfaceNil, nil, 0}, {testT.NonEmptyInterfaceTypedNil, nil, 0}, } { result := funcUnderTest(test.left, test.right) success := false if test.expectIndicator == 0 { if tstIsEq(tp) { success = result } else { success = !result } } if test.expectIndicator < 0 { success = result && (tstIsLt(tp) || tp == tstNe) success = success || (!result && !tstIsLt(tp)) } if test.expectIndicator > 0 { success = result && (tstIsGt(tp) || tp == tstNe) success = success || (!result && (!tstIsGt(tp) || tp != tstNe)) } if !success { t.Fatalf("[%d][%s] %v compared to %v: %t", i, path.Base(runtime.FuncForPC(reflect.ValueOf(funcUnderTest).Pointer()).Name()), test.left, test.right, result) } } } func TestEqualExtend(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(time.UTC, false) for _, test := range []struct { first any others []any expect bool }{ {1, []any{1, 2}, true}, {1, []any{2, 1}, true}, {1, []any{2, 3}, false}, {tstEqerType1("a"), []any{tstEqerType1("a"), tstEqerType1("b")}, true}, {tstEqerType1("a"), []any{tstEqerType1("b"), tstEqerType1("a")}, true}, {tstEqerType1("a"), []any{tstEqerType1("b"), tstEqerType1("c")}, false}, } { result := ns.Eq(test.first, test.others...) c.Assert(result, qt.Equals, test.expect) } } func TestNotEqualExtend(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(time.UTC, false) for _, test := range []struct { first any others []any expect bool }{ {1, []any{2, 3}, true}, {1, []any{2, 1}, false}, {1, []any{1, 2}, false}, } { result := ns.Ne(test.first, test.others...) c.Assert(result, qt.Equals, test.expect) } } func TestGreaterEqualExtend(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(time.UTC, false) for _, test := range []struct { first any others []any expect bool }{ {5, []any{2, 3}, true}, {5, []any{5, 5}, true}, {3, []any{4, 2}, false}, {3, []any{2, 4}, false}, } { result := ns.Ge(test.first, test.others...) c.Assert(result, qt.Equals, test.expect) } } func TestGreaterThanExtend(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(time.UTC, false) for _, test := range []struct { first any others []any expect bool }{ {5, []any{2, 3}, true}, {5, []any{5, 4}, false}, {3, []any{4, 2}, false}, } { result := ns.Gt(test.first, test.others...) c.Assert(result, qt.Equals, test.expect) } } func TestLessEqualExtend(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(time.UTC, false) for _, test := range []struct { first any others []any expect bool }{ {1, []any{2, 3}, true}, {1, []any{1, 2}, true}, {2, []any{1, 2}, false}, {3, []any{2, 4}, false}, } { result := ns.Le(test.first, test.others...) c.Assert(result, qt.Equals, test.expect) } } func TestLessThanExtend(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(time.UTC, false) for _, test := range []struct { first any others []any expect bool }{ {1, []any{2, 3}, true}, {1, []any{1, 2}, false}, {2, []any{1, 2}, false}, {3, []any{2, 4}, false}, } { result := ns.Lt(test.first, test.others...) c.Assert(result, qt.Equals, test.expect) } } func TestCase(t *testing.T) { c := qt.New(t) n := New(time.UTC, false) c.Assert(n.Eq("az", "az"), qt.Equals, true) c.Assert(n.Eq("az", stringType("az")), qt.Equals, true) } func TestStringType(t *testing.T) { c := qt.New(t) n := New(time.UTC, true) c.Assert(n.Lt("az", "Za"), qt.Equals, true) c.Assert(n.Gt("ab", "Ab"), qt.Equals, true) } func TestTimeUnix(t *testing.T) { t.Parallel() n := New(time.UTC, false) var sec int64 = 1234567890 tv := reflect.ValueOf(time.Unix(sec, 0)) i := 1 res := n.toTimeUnix(tv) if sec != res { t.Errorf("[%d] timeUnix got %v but expected %v", i, res, sec) } i++ func(t *testing.T) { defer func() { if err := recover(); err == nil { t.Errorf("[%d] timeUnix didn't return an expected error", i) } }() iv := reflect.ValueOf(sec) n.toTimeUnix(iv) }(t) } func TestConditional(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(time.UTC, false) type args struct { cond any v1 any v2 any } tests := []struct { name string args args want any }{ {"a", args{cond: true, v1: "true", v2: "false"}, "true"}, {"b", args{cond: false, v1: "true", v2: "false"}, "false"}, {"c", args{cond: 1, v1: "true", v2: "false"}, "true"}, {"d", args{cond: 0, v1: "true", v2: "false"}, "false"}, {"e", args{cond: "foo", v1: "true", v2: "false"}, "true"}, {"f", args{cond: "", v1: "true", v2: "false"}, "false"}, {"g", args{cond: []int{6, 7}, v1: "true", v2: "false"}, "true"}, {"h", args{cond: []int{}, v1: "true", v2: "false"}, "false"}, {"i", args{cond: nil, v1: "true", v2: "false"}, "false"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { c.Assert(ns.Conditional(tt.args.cond, tt.args.v1, tt.args.v2), qt.Equals, tt.want) }) } } // Issue 9462 func TestComparisonArgCount(t *testing.T) { t.Parallel() c := qt.New(t) ns := New(time.UTC, false) panicMsg := "missing arguments for comparison" c.Assert(func() { ns.Eq(1) }, qt.PanicMatches, panicMsg) c.Assert(func() { ns.Ge(1) }, qt.PanicMatches, panicMsg) c.Assert(func() { ns.Gt(1) }, qt.PanicMatches, panicMsg) c.Assert(func() { ns.Le(1) }, qt.PanicMatches, panicMsg) c.Assert(func() { ns.Lt(1) }, qt.PanicMatches, panicMsg) c.Assert(func() { ns.Ne(1) }, qt.PanicMatches, panicMsg) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/compare/compare.go
tpl/compare/compare.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 compare provides template functions for comparing values. package compare import ( "fmt" "math" "reflect" "strconv" "time" "github.com/gohugoio/hugo/compare" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/types" ) // New returns a new instance of the compare-namespaced template functions. func New(loc *time.Location, caseInsensitive bool) *Namespace { return &Namespace{loc: loc, caseInsensitive: caseInsensitive} } // Namespace provides template functions for the "compare" namespace. type Namespace struct { loc *time.Location // Enable to do case insensitive string compares. caseInsensitive bool } // Default checks whether a givenv is set and returns the default value defaultv if it // is not. "Set" in this context means non-zero for numeric types and times; // non-zero length for strings, arrays, slices, and maps; // any boolean or struct value; or non-nil for any other types. func (*Namespace) Default(defaultv any, givenv ...any) (any, error) { // given is variadic because the following construct will not pass a piped // argument when the key is missing: {{ index . "key" | default "foo" }} // The Go template will complain that we got 1 argument when we expected 2. if len(givenv) == 0 { return defaultv, nil } if len(givenv) != 1 { return nil, fmt.Errorf("wrong number of args for default: want 2 got %d", len(givenv)+1) } g := reflect.ValueOf(givenv[0]) if !g.IsValid() { return defaultv, nil } set := false switch g.Kind() { case reflect.Bool: set = true case reflect.String, reflect.Array, reflect.Slice, reflect.Map: set = g.Len() != 0 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: set = g.Int() != 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: set = g.Uint() != 0 case reflect.Float32, reflect.Float64: set = g.Float() != 0 case reflect.Complex64, reflect.Complex128: set = g.Complex() != 0 case reflect.Struct: switch actual := givenv[0].(type) { case time.Time: set = !actual.IsZero() default: set = true } default: set = !g.IsNil() } if set { return givenv[0], nil } return defaultv, nil } // Eq returns the boolean truth of arg1 == arg2 || arg1 == arg3 || arg1 == arg4. func (n *Namespace) Eq(first any, others ...any) bool { if n.caseInsensitive { panic("caseInsensitive not implemented for Eq") } n.checkComparisonArgCount(1, others...) normalize := func(v any) any { if types.IsNil(v) { return nil } if at, ok := v.(htime.AsTimeProvider); ok { return at.AsTime(n.loc) } vv := reflect.ValueOf(v) switch vv.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return vv.Int() case reflect.Float32, reflect.Float64: return vv.Float() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: i := vv.Uint() // If it can fit in an int, convert it. if i <= math.MaxInt64 { return int64(i) } return i case reflect.String: return vv.String() default: return v } } normFirst := normalize(first) for _, other := range others { if e, ok := first.(compare.Eqer); ok { if e.Eq(other) { return true } continue } if e, ok := other.(compare.Eqer); ok { if e.Eq(first) { return true } continue } other = normalize(other) if reflect.DeepEqual(normFirst, other) { return true } } return false } // Ne returns the boolean truth of arg1 != arg2 && arg1 != arg3 && arg1 != arg4. func (n *Namespace) Ne(first any, others ...any) bool { n.checkComparisonArgCount(1, others...) for _, other := range others { if n.Eq(first, other) { return false } } return true } // Ge returns the boolean truth of arg1 >= arg2 && arg1 >= arg3 && arg1 >= arg4. func (n *Namespace) Ge(first any, others ...any) bool { n.checkComparisonArgCount(1, others...) for _, other := range others { left, right := n.compareGet(first, other) if !(left >= right) { return false } } return true } // Gt returns the boolean truth of arg1 > arg2 && arg1 > arg3 && arg1 > arg4. func (n *Namespace) Gt(first any, others ...any) bool { n.checkComparisonArgCount(1, others...) for _, other := range others { left, right := n.compareGet(first, other) if !(left > right) { return false } } return true } // Le returns the boolean truth of arg1 <= arg2 && arg1 <= arg3 && arg1 <= arg4. func (n *Namespace) Le(first any, others ...any) bool { n.checkComparisonArgCount(1, others...) for _, other := range others { left, right := n.compareGet(first, other) if !(left <= right) { return false } } return true } // LtCollate returns the boolean truth of arg1 < arg2 && arg1 < arg3 && arg1 < arg4. // The provided collator will be used for string comparisons. // This is for internal use. func (n *Namespace) LtCollate(collator *langs.Collator, first any, others ...any) bool { n.checkComparisonArgCount(1, others...) for _, other := range others { left, right := n.compareGetWithCollator(collator, first, other) if !(left < right) { return false } } return true } // Lt returns the boolean truth of arg1 < arg2 && arg1 < arg3 && arg1 < arg4. func (n *Namespace) Lt(first any, others ...any) bool { return n.LtCollate(nil, first, others...) } func (n *Namespace) checkComparisonArgCount(min int, others ...any) bool { if len(others) < min { panic("missing arguments for comparison") } return true } // Conditional can be used as a ternary operator. // // It returns v1 if cond is true, else v2. func (n *Namespace) Conditional(cond any, v1, v2 any) any { if hreflect.IsTruthful(cond) { return v1 } return v2 } func (ns *Namespace) compareGet(a any, b any) (float64, float64) { return ns.compareGetWithCollator(nil, a, b) } func (ns *Namespace) compareTwoUints(a uint64, b uint64) (float64, float64) { if a < b { return 0, 1 } else if a == b { return 0, 0 } else { return 1, 0 } } func (ns *Namespace) compareGetWithCollator(collator *langs.Collator, a any, b any) (float64, float64) { if ac, ok := a.(compare.Comparer); ok { c := ac.Compare(b) if c < 0 { return 1, 0 } else if c == 0 { return 0, 0 } else { return 0, 1 } } if bc, ok := b.(compare.Comparer); ok { c := bc.Compare(a) if c < 0 { return 0, 1 } else if c == 0 { return 0, 0 } else { return 1, 0 } } var left, right float64 var leftStr, rightStr *string av := reflect.ValueOf(a) bv := reflect.ValueOf(b) switch av.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: left = float64(av.Len()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if hreflect.IsUint(bv.Kind()) { return ns.compareTwoUints(uint64(av.Int()), bv.Uint()) } left = float64(av.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: left = float64(av.Uint()) case reflect.Uint64: if hreflect.IsUint(bv.Kind()) { return ns.compareTwoUints(av.Uint(), bv.Uint()) } case reflect.Float32, reflect.Float64: left = av.Float() case reflect.String: var err error left, err = strconv.ParseFloat(av.String(), 64) // Check if float is a special floating value and cast value as string. if math.IsInf(left, 0) || math.IsNaN(left) || err != nil { str := av.String() leftStr = &str } case reflect.Struct: if hreflect.IsTime(av.Type()) { left = float64(ns.toTimeUnix(av)) } case reflect.Bool: left = 0 if av.Bool() { left = 1 } } switch bv.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: right = float64(bv.Len()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if hreflect.IsUint(av.Kind()) { return ns.compareTwoUints(av.Uint(), uint64(bv.Int())) } right = float64(bv.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: right = float64(bv.Uint()) case reflect.Uint64: if hreflect.IsUint(av.Kind()) { return ns.compareTwoUints(av.Uint(), bv.Uint()) } case reflect.Float32, reflect.Float64: right = bv.Float() case reflect.String: var err error right, err = strconv.ParseFloat(bv.String(), 64) // Check if float is a special floating value and cast value as string. if math.IsInf(right, 0) || math.IsNaN(right) || err != nil { str := bv.String() rightStr = &str } case reflect.Struct: if hreflect.IsTime(bv.Type()) { right = float64(ns.toTimeUnix(bv)) } case reflect.Bool: right = 0 if bv.Bool() { right = 1 } } if (ns.caseInsensitive || collator != nil) && leftStr != nil && rightStr != nil { var c int if collator != nil { c = collator.CompareStrings(*leftStr, *rightStr) } else { c = compare.Strings(*leftStr, *rightStr) } if c < 0 { return 0, 1 } else if c > 0 { return 1, 0 } else { return 0, 0 } } switch { case leftStr == nil || rightStr == nil: case *leftStr < *rightStr: return 0, 1 case *leftStr > *rightStr: return 1, 0 default: return 0, 0 } return left, right } 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() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/time/time.go
tpl/time/time.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 time provides template functions for measuring and displaying time. package time import ( "fmt" "time" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/deps" "github.com/spf13/cast" ) // New returns a new instance of the time-namespaced template functions. func New(timeFormatter htime.TimeFormatter, location *time.Location, deps *deps.Deps) *Namespace { if deps.MemCache == nil { panic("must provide MemCache") } return &Namespace{ timeFormatter: timeFormatter, location: location, deps: deps, cacheIn: dynacache.GetOrCreatePartition[string, *time.Location]( deps.MemCache, "/tmpl/time/in", dynacache.OptionsPartition{Weight: 30, ClearWhen: dynacache.ClearNever}, ), } } // Namespace provides template functions for the "time" namespace. type Namespace struct { timeFormatter htime.TimeFormatter location *time.Location deps *deps.Deps cacheIn *dynacache.Partition[string, *time.Location] } // AsTime converts the textual representation of the datetime string into // a time.Time interface. func (ns *Namespace) AsTime(v any, args ...any) (any, error) { loc := ns.location if len(args) > 0 { locStr, err := cast.ToStringE(args[0]) if err != nil { return nil, err } loc, err = time.LoadLocation(locStr) if err != nil { return nil, err } } return htime.ToTimeInDefaultLocationE(v, loc) } // Format converts the textual representation of the datetime string in v into // time.Time if needed and formats it with the given layout. func (ns *Namespace) Format(layout string, v any) (string, error) { t, err := htime.ToTimeInDefaultLocationE(v, ns.location) if err != nil { return "", err } return ns.timeFormatter.Format(t, layout), nil } // Now returns the current local time or `clock` time func (ns *Namespace) Now() time.Time { return htime.Now() } // In returns the time t in the IANA time zone specified by timeZoneName. // If timeZoneName is "" or "UTC", the time is returned in UTC. // If timeZoneName is "Local", the time is returned in the system's local time zone. // Otherwise, timeZoneName must be a valid IANA location name (e.g., "Europe/Oslo"). func (ns *Namespace) In(timeZoneName string, t time.Time) (time.Time, error) { location, err := ns.cacheIn.GetOrCreate(dynacache.CleanKey(timeZoneName), func(string) (*time.Location, error) { return time.LoadLocation(timeZoneName) }) if err != nil { return time.Time{}, err } return t.In(location), nil } // ParseDuration parses the duration string s. // A duration string is a possibly signed sequence of // decimal numbers, each with optional fraction and a unit suffix, // such as "300ms", "-1.5h" or "2h45m". // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". // See https://golang.org/pkg/time/#ParseDuration func (ns *Namespace) ParseDuration(s any) (time.Duration, error) { ss, err := cast.ToStringE(s) if err != nil { return 0, err } return time.ParseDuration(ss) } var durationUnits = map[string]time.Duration{ "nanosecond": time.Nanosecond, "ns": time.Nanosecond, "microsecond": time.Microsecond, "us": time.Microsecond, "µs": time.Microsecond, "millisecond": time.Millisecond, "ms": time.Millisecond, "second": time.Second, "s": time.Second, "minute": time.Minute, "m": time.Minute, "hour": time.Hour, "h": time.Hour, } // Duration converts the given number to a time.Duration. // Unit is one of nanosecond/ns, microsecond/us/µs, millisecond/ms, second/s, minute/m or hour/h. func (ns *Namespace) Duration(unit any, number any) (time.Duration, error) { unitStr, err := cast.ToStringE(unit) if err != nil { return 0, err } unitDuration, found := durationUnits[unitStr] if !found { return 0, fmt.Errorf("%q is not a valid duration unit", unit) } n, err := cast.ToInt64E(number) if err != nil { return 0, err } return time.Duration(n) * unitDuration, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/time/init.go
tpl/time/init.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 time import ( "context" "errors" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/tpl/internal" ) const name = "time" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { if d.Conf.Language() == nil { panic("Language must be set") } lang := d.Conf.Language().(*langs.Language) ctx := New(langs.GetTimeFormatter(lang), langs.GetLocation(lang), d) ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { // Handle overlapping "time" namespace and func. // // If no args are passed to `time`, assume namespace usage and // return namespace context. // // If args are passed, call AsTime(). switch len(args) { case 0: return ctx, nil case 1: return ctx.AsTime(args[0]) case 2: return ctx.AsTime(args[0], args[1]) // 3 or more arguments. Currently not supported. default: return nil, errors.New("invalid arguments supplied to `time`") } }, } ns.AddMethodMapping(ctx.AsTime, nil, [][2]string{ {`{{ (time "2015-01-21").Year }}`, `2015`}, }, ) ns.AddMethodMapping(ctx.Duration, []string{"duration"}, [][2]string{ {`{{ mul 60 60 | duration "second" }}`, `1h0m0s`}, }, ) ns.AddMethodMapping(ctx.Format, []string{"dateFormat"}, [][2]string{ {`dateFormat: {{ dateFormat "Monday, Jan 2, 2006" "2015-01-21" }}`, `dateFormat: Wednesday, Jan 21, 2015`}, }, ) ns.AddMethodMapping(ctx.In, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Now, []string{"now"}, [][2]string{}, ) ns.AddMethodMapping(ctx.ParseDuration, nil, [][2]string{ {`{{ "1h12m10s" | time.ParseDuration }}`, `1h12m10s`}, }, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/time/time_test.go
tpl/time/time_test.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 time_test import ( "strings" "testing" gtime "time" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/tpl/time" translators "github.com/gohugoio/localescompressed" ) func TestTimeLocation(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() loc, _ := gtime.LoadLocation("America/Antigua") ns := time.New(htime.NewTimeFormatter(translators.GetTranslator("en")), loc, b.H.Deps) for i, test := range []struct { name string value string location any expect any }{ {"Empty location", "2020-10-20", "", "2020-10-20 00:00:00 +0000 UTC"}, {"New location", "2020-10-20", nil, "2020-10-20 00:00:00 -0400 AST"}, {"New York EDT", "2020-10-20", "America/New_York", "2020-10-20 00:00:00 -0400 EDT"}, {"New York EST", "2020-01-20", "America/New_York", "2020-01-20 00:00:00 -0500 EST"}, {"Empty location, time", "2020-10-20 20:33:59", "", "2020-10-20 20:33:59 +0000 UTC"}, {"New York, time", "2020-10-20 20:33:59", "America/New_York", "2020-10-20 20:33:59 -0400 EDT"}, // The following have an explicit offset specified. In this case, it overrides timezone {"Offset minus 0700, empty location", "2020-09-23T20:33:44-0700", "", "2020-09-23 20:33:44 -0700 -0700"}, {"Offset plus 0200, empty location", "2020-09-23T20:33:44+0200", "", "2020-09-23 20:33:44 +0200 +0200"}, {"Offset, New York", "2020-09-23T20:33:44-0700", "America/New_York", "2020-09-23 20:33:44 -0700 -0700"}, {"Offset, Oslo", "2020-09-23T20:33:44+0200", "Europe/Oslo", "2020-09-23 20:33:44 +0200 +0200"}, // Failures. {"Invalid time zone", "2020-01-20", "invalid-timezone", false}, {"Invalid time value", "invalid-value", "", false}, } { t.Run(test.name, func(t *testing.T) { var args []any if test.location != nil { args = append(args, test.location) } result, err := ns.AsTime(test.value, args...) if b, ok := test.expect.(bool); ok && !b { if err == nil { t.Errorf("[%d] AsTime didn't return an expected error, got %v", i, result) } } else { if err != nil { t.Errorf("[%d] AsTime failed: %s", i, err) return } // See https://github.com/gohugoio/hugo/issues/8843#issuecomment-891551447 // Drop the location string (last element) when comparing, // as that may change depending on the local locale. timeStr := result.(gtime.Time).String() timeStr = timeStr[:strings.LastIndex(timeStr, " ")] if !strings.HasPrefix(test.expect.(string), timeStr) { t.Errorf("[%d] AsTime got %v but expected %v", i, timeStr, test.expect) } } }) } } func TestFormat(t *testing.T) { c := qt.New(t) b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() c.Run("UTC", func(c *qt.C) { c.Parallel() ns := time.New(htime.NewTimeFormatter(translators.GetTranslator("en")), gtime.UTC, b.H.Deps) for i, test := range []struct { layout string value any expect any }{ {"Monday, Jan 2, 2006", "2015-01-21", "Wednesday, Jan 21, 2015"}, {"Monday, Jan 2, 2006", gtime.Date(2015, gtime.January, 21, 0, 0, 0, 0, gtime.UTC), "Wednesday, Jan 21, 2015"}, {"This isn't a date layout string", "2015-01-21", "This isn't a date layout string"}, // The following test case gives either "Tuesday, Jan 20, 2015" or "Monday, Jan 19, 2015" depending on the local time zone {"Monday, Jan 2, 2006", 1421733600, gtime.Unix(1421733600, 0).Format("Monday, Jan 2, 2006")}, {"Monday, Jan 2, 2006", 1421733600.123, false}, {gtime.RFC3339, gtime.Date(2016, gtime.March, 3, 4, 5, 0, 0, gtime.UTC), "2016-03-03T04:05:00Z"}, {gtime.RFC1123, gtime.Date(2016, gtime.March, 3, 4, 5, 0, 0, gtime.UTC), "Thu, 03 Mar 2016 04:05:00 UTC"}, {gtime.RFC3339, "Thu, 03 Mar 2016 04:05:00 UTC", "2016-03-03T04:05:00Z"}, {gtime.RFC1123, "2016-03-03T04:05:00Z", "Thu, 03 Mar 2016 04:05:00 UTC"}, // Custom layouts, as introduced in Hugo 0.87. {":date_medium", "2015-01-21", "Jan 21, 2015"}, } { result, err := ns.Format(test.layout, test.value) if b, ok := test.expect.(bool); ok && !b { if err == nil { c.Errorf("[%d] DateFormat didn't return an expected error, got %v", i, result) } } else { if err != nil { c.Errorf("[%d] DateFormat failed: %s", i, err) continue } if result != test.expect { c.Errorf("[%d] DateFormat got %v but expected %v", i, result, test.expect) } } } }) // Issue #9084 c.Run("TZ America/Los_Angeles", func(c *qt.C) { c.Parallel() loc, err := gtime.LoadLocation("America/Los_Angeles") c.Assert(err, qt.IsNil) ns := time.New(htime.NewTimeFormatter(translators.GetTranslator("en")), loc, b.H.Deps) d, err := ns.Format(":time_full", "2020-03-09T11:00:00") c.Assert(err, qt.IsNil) c.Assert(d, qt.Equals, "11:00:00 am Pacific Daylight Time") }) } func TestDuration(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := time.New(htime.NewTimeFormatter(translators.GetTranslator("en")), gtime.UTC, b.H.Deps) for i, test := range []struct { unit any num any expect any }{ {"nanosecond", 10, 10 * gtime.Nanosecond}, {"ns", 10, 10 * gtime.Nanosecond}, {"microsecond", 20, 20 * gtime.Microsecond}, {"us", 20, 20 * gtime.Microsecond}, {"µs", 20, 20 * gtime.Microsecond}, {"millisecond", 20, 20 * gtime.Millisecond}, {"ms", 20, 20 * gtime.Millisecond}, {"second", 30, 30 * gtime.Second}, {"s", 30, 30 * gtime.Second}, {"minute", 20, 20 * gtime.Minute}, {"m", 20, 20 * gtime.Minute}, {"hour", 20, 20 * gtime.Hour}, {"h", 20, 20 * gtime.Hour}, {"hours", 20, false}, {"hour", "30", 30 * gtime.Hour}, } { result, err := ns.Duration(test.unit, test.num) if b, ok := test.expect.(bool); ok && !b { if err == nil { t.Errorf("[%d] Duration didn't return an expected error, got %v", i, result) } } else { if err != nil { t.Errorf("[%d] Duration failed: %s", i, err) continue } if result != test.expect { t.Errorf("[%d] Duration got %v but expected %v", i, result, test.expect) } } } } func TestIn(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := time.New(htime.NewTimeFormatter(translators.GetTranslator("en")), gtime.UTC, b.H.Deps) in := gtime.Date(2025, gtime.March, 31, 15, 0, 0, 0, gtime.UTC) tests := []struct { name string tzn string // time zone name want string wantErr bool }{ {name: "A", tzn: "America/Denver", want: "2025-03-31T09:00:00-06:00", wantErr: false}, {name: "B", tzn: "Australia/Adelaide", want: "2025-04-01T01:30:00+10:30", wantErr: false}, {name: "C", tzn: "Europe/Oslo", want: "2025-03-31T17:00:00+02:00", wantErr: false}, {name: "D", tzn: "UTC", want: "2025-03-31T15:00:00+00:00", wantErr: false}, {name: "E", tzn: "", want: "2025-03-31T15:00:00+00:00", wantErr: false}, {name: "F", tzn: "InvalidTimeZoneName", want: "0001-01-01T00:00:00+00:00", wantErr: true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result, err := ns.In(tt.tzn, in) if (err != nil) != tt.wantErr { t.Errorf("time.In() error = %v, wantErr %v", err, tt.wantErr) return } got := result.Format("2006-01-02T15:04:05-07:00") if got != tt.want { t.Errorf("time.In() = %v, want %v", got, tt.want) } }) } } // For benchmark tests below. var timeZoneNames []string = []string{"America/New_York", "Europe/Oslo", "Australia/Sydney", "UTC", "Local"} func BenchmarkInWithCaching(b *testing.B) { bb := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: b}, ).Build() ns := time.New(htime.NewTimeFormatter(translators.GetTranslator("en")), gtime.UTC, bb.H.Deps) for i := 0; b.Loop(); i++ { timeZoneName := timeZoneNames[i%len(timeZoneNames)] _, err := ns.In(timeZoneName, gtime.Now()) if err != nil { b.Fatalf("Error during benchmark: %v", err) } } } func BenchmarkInWithoutCaching(b *testing.B) { for i := 0; b.Loop(); i++ { timeZoneName := timeZoneNames[i%len(timeZoneNames)] location, err := gtime.LoadLocation(timeZoneName) if err != nil { b.Fatalf("Error during benchmark: %v", err) } _ = gtime.Now().In(location) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/strings/regexp_test.go
tpl/strings/regexp_test.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 strings import ( "testing" qt "github.com/frankban/quicktest" ) func TestFindRE(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { expr string content any limit any expect any }{ {"[G|g]o", "Hugo is a static site generator written in Go.", 2, []string{"go", "Go"}}, {"[G|g]o", "Hugo is a static site generator written in Go.", -1, []string{"go", "Go"}}, {"[G|g]o", "Hugo is a static site generator written in Go.", 1, []string{"go"}}, {"[G|g]o", "Hugo is a static site generator written in Go.", "1", []string{"go"}}, {"[G|g]o", "Hugo is a static site generator written in Go.", nil, []string(nil)}, // errors {"[G|go", "Hugo is a static site generator written in Go.", nil, false}, {"[G|g]o", t, nil, false}, } { result, err := ns.FindRE(test.expr, test.content, test.limit) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Check(result, qt.DeepEquals, test.expect) } } func TestFindRESubmatch(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { expr string content any limit any expect any }{ {`<a\s*href="(.+?)">(.+?)</a>`, `<li><a href="#foo">Foo</a></li><li><a href="#bar">Bar</a></li>`, -1, [][]string{ {"<a href=\"#foo\">Foo</a>", "#foo", "Foo"}, {"<a href=\"#bar\">Bar</a>", "#bar", "Bar"}, }}, // Some simple cases. {"([G|g]o)", "Hugo is a static site generator written in Go.", -1, [][]string{{"go", "go"}, {"Go", "Go"}}}, {"([G|g]o)", "Hugo is a static site generator written in Go.", 1, [][]string{{"go", "go"}}}, // errors {"([G|go", "Hugo is a static site generator written in Go.", nil, false}, {"([G|g]o)", t, nil, false}, } { result, err := ns.FindRESubmatch(test.expr, test.content, test.limit) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Check(result, qt.DeepEquals, test.expect) } } func TestReplaceRE(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { pattern any repl any s any n []any expect any }{ {"^https?://([^/]+).*", "$1", "http://gohugo.io/docs", nil, "gohugo.io"}, {"^https?://([^/]+).*", "$2", "http://gohugo.io/docs", nil, ""}, {"(ab)", "AB", "aabbaab", nil, "aABbaAB"}, {"(ab)", "AB", "aabbaab", []any{1}, "aABbaab"}, // errors {"(ab", "AB", "aabb", nil, false}, // invalid re {tstNoStringer{}, "$2", "http://gohugo.io/docs", nil, false}, {"^https?://([^/]+).*", tstNoStringer{}, "http://gohugo.io/docs", nil, false}, {"^https?://([^/]+).*", "$2", tstNoStringer{}, nil, false}, } { var ( result string err error ) if len(test.n) > 0 { result, err = ns.ReplaceRE(test.pattern, test.repl, test.s, test.n...) } else { result, err = ns.ReplaceRE(test.pattern, test.repl, test.s) } if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Check(result, qt.Equals, test.expect) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/strings/init.go
tpl/strings/init.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 strings import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const name = "strings" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New(d) ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.Chomp, []string{"chomp"}, [][2]string{ {`{{ chomp "<p>Blockhead</p>\n" | safeHTML }}`, `<p>Blockhead</p>`}, }, ) ns.AddMethodMapping(ctx.Contains, nil, [][2]string{ {`{{ strings.Contains "abc" "b" }}`, `true`}, {`{{ strings.Contains "abc" "d" }}`, `false`}, }, ) ns.AddMethodMapping(ctx.ContainsAny, nil, [][2]string{ {`{{ strings.ContainsAny "abc" "bcd" }}`, `true`}, {`{{ strings.ContainsAny "abc" "def" }}`, `false`}, }, ) ns.AddMethodMapping(ctx.ContainsNonSpace, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Count, nil, [][2]string{ {`{{ "aabab" | strings.Count "a" }}`, `3`}, }, ) ns.AddMethodMapping(ctx.CountRunes, []string{"countrunes"}, [][2]string{}, ) ns.AddMethodMapping(ctx.CountWords, []string{"countwords"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Diff, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.FindRE, []string{"findRE"}, [][2]string{ { `{{ findRE "[G|g]o" "Hugo is a static side generator written in Go." 1 }}`, `[go]`, }, }, ) ns.AddMethodMapping(ctx.FindRESubmatch, []string{"findRESubmatch"}, [][2]string{ { `{{ findRESubmatch §§<a\s*href="(.+?)">(.+?)</a>§§ §§<li><a href="#foo">Foo</a></li> <li><a href="#bar">Bar</a></li>§§ | print | safeHTML }}`, "[[<a href=\"#foo\">Foo</a> #foo Foo] [<a href=\"#bar\">Bar</a> #bar Bar]]", }, }, ) ns.AddMethodMapping(ctx.FirstUpper, nil, [][2]string{ {`{{ "hugo rocks!" | strings.FirstUpper }}`, `Hugo rocks!`}, }, ) ns.AddMethodMapping(ctx.HasPrefix, []string{"hasPrefix"}, [][2]string{ {`{{ hasPrefix "Hugo" "Hu" }}`, `true`}, {`{{ hasPrefix "Hugo" "Fu" }}`, `false`}, }, ) ns.AddMethodMapping(ctx.HasSuffix, []string{"hasSuffix"}, [][2]string{ {`{{ hasSuffix "Hugo" "go" }}`, `true`}, {`{{ hasSuffix "Hugo" "du" }}`, `false`}, }, ) ns.AddMethodMapping(ctx.Repeat, nil, [][2]string{ {`{{ "yo" | strings.Repeat 4 }}`, `yoyoyoyo`}, }, ) ns.AddMethodMapping(ctx.Replace, []string{"replace"}, [][2]string{ { `{{ replace "Batman and Robin" "Robin" "Catwoman" }}`, `Batman and Catwoman`, }, { `{{ replace "aabbaabb" "a" "z" 2 }}`, `zzbbaabb`, }, }, ) ns.AddMethodMapping(ctx.ReplaceRE, []string{"replaceRE"}, [][2]string{ { `{{ replaceRE "a+b" "X" "aabbaabbab" }}`, `XbXbX`, }, { `{{ replaceRE "a+b" "X" "aabbaabbab" 1 }}`, `Xbaabbab`, }, }, ) ns.AddMethodMapping(ctx.RuneCount, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.SliceString, []string{"slicestr"}, [][2]string{ {`{{ slicestr "BatMan" 0 3 }}`, `Bat`}, {`{{ slicestr "BatMan" 3 }}`, `Man`}, }, ) ns.AddMethodMapping(ctx.Split, []string{"split"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Substr, []string{"substr"}, [][2]string{ {`{{ substr "BatMan" 0 -3 }}`, `Bat`}, {`{{ substr "BatMan" 3 3 }}`, `Man`}, }, ) ns.AddMethodMapping(ctx.Title, []string{"title"}, [][2]string{ {`{{ title "Bat man" }}`, `Bat Man`}, {`{{ title "somewhere over the rainbow" }}`, `Somewhere Over the Rainbow`}, }, ) ns.AddMethodMapping(ctx.ToLower, []string{"lower"}, [][2]string{ {`{{ lower "BatMan" }}`, `batman`}, }, ) ns.AddMethodMapping(ctx.ToUpper, []string{"upper"}, [][2]string{ {`{{ upper "BatMan" }}`, `BATMAN`}, }, ) ns.AddMethodMapping(ctx.Trim, []string{"trim"}, [][2]string{ {`{{ trim "++Batman--" "+-" }}`, `Batman`}, }, ) ns.AddMethodMapping(ctx.TrimLeft, nil, [][2]string{ {`{{ "aabbaa" | strings.TrimLeft "a" }}`, `bbaa`}, }, ) ns.AddMethodMapping(ctx.TrimPrefix, nil, [][2]string{ {`{{ "aabbaa" | strings.TrimPrefix "a" }}`, `abbaa`}, {`{{ "aabbaa" | strings.TrimPrefix "aa" }}`, `bbaa`}, }, ) ns.AddMethodMapping(ctx.TrimRight, nil, [][2]string{ {`{{ "aabbaa" | strings.TrimRight "a" }}`, `aabb`}, }, ) ns.AddMethodMapping(ctx.TrimSpace, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.TrimSuffix, nil, [][2]string{ {`{{ "aabbaa" | strings.TrimSuffix "a" }}`, `aabba`}, {`{{ "aabbaa" | strings.TrimSuffix "aa" }}`, `aabb`}, }, ) ns.AddMethodMapping(ctx.Truncate, []string{"truncate"}, [][2]string{ {`{{ "this is a very long text" | truncate 10 " ..." }}`, `this is a ...`}, {`{{ "With [Markdown](/markdown) inside." | markdownify | truncate 14 }}`, `With <a href="/markdown">Markdown …</a>`}, }, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/strings/strings_test.go
tpl/strings/strings_test.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 strings import ( "html/template" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/deps" "github.com/spf13/cast" ) var ns = New(&deps.Deps{ Conf: testconfig.GetTestConfig(nil, nil), }) type tstNoStringer struct{} func TestChomp(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any expect any }{ {"\n a\n", "\n a"}, {"\n a\n\n", "\n a"}, {"\n a\r\n", "\n a"}, {"\n a\n\r\n", "\n a"}, {"\n a\r\r", "\n a"}, {"\n a\r", "\n a"}, // errors {tstNoStringer{}, false}, } { result, err := ns.Chomp(test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) // repeat the check with template.HTML input result, err = ns.Chomp(template.HTML(cast.ToString(test.s))) c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, template.HTML(cast.ToString(test.expect))) } } func TestContains(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any substr any expect bool isErr bool }{ {"", "", true, false}, {"123", "23", true, false}, {"123", "234", false, false}, {"123", "", true, false}, {"", "a", false, false}, {123, "23", true, false}, {123, "234", false, false}, {123, "", true, false}, {template.HTML("123"), []byte("23"), true, false}, {template.HTML("123"), []byte("234"), false, false}, {template.HTML("123"), []byte(""), true, false}, // errors {"", tstNoStringer{}, false, true}, {tstNoStringer{}, "", false, true}, } { result, err := ns.Contains(test.s, test.substr) if test.isErr { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestContainsAny(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any substr any expect bool isErr bool }{ {"", "", false, false}, {"", "1", false, false}, {"", "123", false, false}, {"1", "", false, false}, {"1", "1", true, false}, {"111", "1", true, false}, {"123", "789", false, false}, {"123", "729", true, false}, {"a☺b☻c☹d", "uvw☻xyz", true, false}, {1, "", false, false}, {1, "1", true, false}, {111, "1", true, false}, {123, "789", false, false}, {123, "729", true, false}, {[]byte("123"), template.HTML("789"), false, false}, {[]byte("123"), template.HTML("729"), true, false}, {[]byte("a☺b☻c☹d"), template.HTML("uvw☻xyz"), true, false}, // errors {"", tstNoStringer{}, false, true}, {tstNoStringer{}, "", false, true}, } { result, err := ns.ContainsAny(test.s, test.substr) if test.isErr { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestContainsNonSpace(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any expect bool isErr bool }{ {"", false, false}, {" ", false, false}, {" ", false, false}, {"\t", false, false}, {"\r", false, false}, {"a", true, false}, {" a", true, false}, {"a\n", true, false}, // error {tstNoStringer{}, false, true}, } { result, err := ns.ContainsNonSpace(test.s) if test.isErr { c.Assert(err, qt.IsNotNil) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestCountRunes(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any expect any }{ {"foo bar", 6}, {"旁边", 2}, {`<div class="test">旁边</div>`, 2}, // errors {tstNoStringer{}, false}, } { result, err := ns.CountRunes(test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestRuneCount(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any expect any }{ {"foo bar", 7}, {"旁边", 2}, {`<div class="test">旁边</div>`, 26}, // errors {tstNoStringer{}, false}, } { result, err := ns.RuneCount(test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestCountWords(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any expect any }{ {"Do Be Do Be Do", 5}, {"旁边", 2}, {`<div class="test">旁边</div>`, 2}, {"Here's to you...", 3}, {"Here’s to you...", 3}, {"Here’s to you…", 3}, // errors {tstNoStringer{}, false}, } { result, err := ns.CountWords(test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestHasPrefix(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any prefix any expect any isErr bool }{ {"abcd", "ab", true, false}, {"abcd", "cd", false, false}, {template.HTML("abcd"), "ab", true, false}, {template.HTML("abcd"), "cd", false, false}, {template.HTML("1234"), 12, true, false}, {template.HTML("1234"), 34, false, false}, {[]byte("abcd"), "ab", true, false}, // errors {"", tstNoStringer{}, false, true}, {tstNoStringer{}, "", false, true}, } { result, err := ns.HasPrefix(test.s, test.prefix) if test.isErr { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestHasSuffix(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any suffix any expect any isErr bool }{ {"abcd", "cd", true, false}, {"abcd", "ab", false, false}, {template.HTML("abcd"), "cd", true, false}, {template.HTML("abcd"), "ab", false, false}, {template.HTML("1234"), 34, true, false}, {template.HTML("1234"), 12, false, false}, {[]byte("abcd"), "cd", true, false}, // errors {"", tstNoStringer{}, false, true}, {tstNoStringer{}, "", false, true}, } { result, err := ns.HasSuffix(test.s, test.suffix) if test.isErr { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestReplace(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any old any new any limit any expect any }{ {"aab", "a", "b", nil, "bbb"}, {"11a11", 1, 2, nil, "22a22"}, {12345, 1, 2, nil, "22345"}, {"aab", "a", "b", 1, "bab"}, {"11a11", 1, 2, 2, "22a11"}, // errors {tstNoStringer{}, "a", "b", nil, false}, {"a", tstNoStringer{}, "b", nil, false}, {"a", "b", tstNoStringer{}, nil, false}, } { var ( result string err error ) if test.limit != nil { result, err = ns.Replace(test.s, test.old, test.new, test.limit) } else { result, err = ns.Replace(test.s, test.old, test.new) } if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestSliceString(t *testing.T) { t.Parallel() c := qt.New(t) var err error for _, test := range []struct { v1 any v2 any v3 any expect any }{ {"abc", 1, 2, "b"}, {"abc", 1, 3, "bc"}, {"abcdef", 1, int8(3), "bc"}, {"abcdef", 1, int16(3), "bc"}, {"abcdef", 1, int32(3), "bc"}, {"abcdef", 1, int64(3), "bc"}, {"abc", 0, 1, "a"}, {"abcdef", nil, nil, "abcdef"}, {"abcdef", 0, 6, "abcdef"}, {"abcdef", 0, 2, "ab"}, {"abcdef", 2, nil, "cdef"}, {"abcdef", int8(2), nil, "cdef"}, {"abcdef", int16(2), nil, "cdef"}, {"abcdef", int32(2), nil, "cdef"}, {"abcdef", int64(2), nil, "cdef"}, {123, 1, 3, "23"}, {"abcdef", 6, nil, false}, {"abcdef", 4, 7, false}, {"abcdef", -1, nil, false}, {"abcdef", -1, 7, false}, {"abcdef", 1, -1, false}, {tstNoStringer{}, 0, 1, false}, {"ĀĀĀ", 0, 1, "Ā"}, // issue #1333 {"a", t, nil, false}, {"a", 1, t, false}, } { var result string if test.v2 == nil { result, err = ns.SliceString(test.v1) } else if test.v3 == nil { result, err = ns.SliceString(test.v1, test.v2) } else { result, err = ns.SliceString(test.v1, test.v2, test.v3) } if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } // Too many arguments _, err = ns.SliceString("a", 1, 2, 3) if err == nil { t.Errorf("Should have errored") } } func TestSplit(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { v1 any v2 string expect any }{ {"a, b", ", ", []string{"a", "b"}}, {"a & b & c", " & ", []string{"a", "b", "c"}}, {"http://example.com", "http://", []string{"", "example.com"}}, {123, "2", []string{"1", "3"}}, {tstNoStringer{}, ",", false}, } { result, err := ns.Split(test.v1, test.v2) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.DeepEquals, test.expect) } } func TestSubstr(t *testing.T) { t.Parallel() c := qt.New(t) var err error for _, test := range []struct { v1 any v2 any v3 any expect any }{ {"abc", 1, 2, "bc"}, {"abc", 0, 1, "a"}, {"abcdef", 0, 0, ""}, {"abcdef", 1, 0, ""}, {"abcdef", -1, 0, ""}, {"abcdef", -1, 2, "f"}, {"abcdef", -3, 3, "def"}, {"abcdef", -1, nil, "f"}, {"abcdef", -2, nil, "ef"}, {"abcdef", -3, 1, "d"}, {"abcdef", 0, -1, "abcde"}, {"abcdef", 2, -1, "cde"}, {"abcdef", 4, -4, ""}, {"abcdef", 7, 1, ""}, {"abcdef", 6, nil, ""}, {"abcdef", 1, 100, "bcdef"}, {"abcdef", -100, 3, "abc"}, {"abcdef", -3, -1, "de"}, {"abcdef", 2, nil, "cdef"}, {"abcdef", int8(2), nil, "cdef"}, {"abcdef", int16(2), nil, "cdef"}, {"abcdef", int32(2), nil, "cdef"}, {"abcdef", int64(2), nil, "cdef"}, {"abcdef", 2, int8(3), "cde"}, {"abcdef", 2, int16(3), "cde"}, {"abcdef", 2, int32(3), "cde"}, {"abcdef", 2, int64(3), "cde"}, {123, 1, 3, "23"}, {1.2e3, 0, 4, "1200"}, {tstNoStringer{}, 0, 1, false}, {"abcdef", 2.0, nil, "cdef"}, {"abcdef", 2.0, 2, "cd"}, {"abcdef", 2, 2.0, "cd"}, {"ĀĀĀ", 1, 2, "ĀĀ"}, // # issue 1333 {"abcdef", "doo", nil, false}, {"abcdef", "doo", "doo", false}, {"abcdef", 1, "doo", false}, {"", 0, nil, ""}, } { var result string if test.v3 == nil { result, err = ns.Substr(test.v1, test.v2) } else { result, err = ns.Substr(test.v1, test.v2, test.v3) } if b, ok := test.expect.(bool); ok && !b { c.Check(err, qt.Not(qt.IsNil), qt.Commentf("%v", test)) continue } c.Assert(err, qt.IsNil, qt.Commentf("%v", test)) c.Check(result, qt.Equals, test.expect, qt.Commentf("%v", test)) } _, err = ns.Substr("abcdef") c.Assert(err, qt.Not(qt.IsNil)) _, err = ns.Substr("abcdef", 1, 2, 3) c.Assert(err, qt.Not(qt.IsNil)) } func TestTitle(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any expect any }{ {"test", "Test"}, {template.HTML("hypertext"), "Hypertext"}, {[]byte("bytes"), "Bytes"}, // errors {tstNoStringer{}, false}, } { result, err := ns.Title(test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestToLower(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any expect any }{ {"TEST", "test"}, {template.HTML("LoWeR"), "lower"}, {[]byte("BYTES"), "bytes"}, // errors {tstNoStringer{}, false}, } { result, err := ns.ToLower(test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestToUpper(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any expect any }{ {"test", "TEST"}, {template.HTML("UpPeR"), "UPPER"}, {[]byte("bytes"), "BYTES"}, // errors {tstNoStringer{}, false}, } { result, err := ns.ToUpper(test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestTrim(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any cutset any expect any }{ {"abba", "a", "bb"}, {"abba", "ab", ""}, {"<tag>", "<>", "tag"}, {`"quote"`, `"`, "quote"}, {1221, "1", "22"}, {1221, "12", ""}, {template.HTML("<tag>"), "<>", "tag"}, {[]byte("<tag>"), "<>", "tag"}, // errors {"", tstNoStringer{}, false}, {tstNoStringer{}, "", false}, } { result, err := ns.Trim(test.s, test.cutset) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestTrimLeft(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any cutset any expect any }{ {"abba", "a", "bba"}, {"abba", "ab", ""}, {"<tag>", "<>", "tag>"}, {`"quote"`, `"`, `quote"`}, {1221, "1", "221"}, {1221, "12", ""}, {"007", "0", "7"}, {template.HTML("<tag>"), "<>", "tag>"}, {[]byte("<tag>"), "<>", "tag>"}, // errors {"", tstNoStringer{}, false}, {tstNoStringer{}, "", false}, } { result, err := ns.TrimLeft(test.cutset, test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestTrimPrefix(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any prefix any expect any }{ {"aabbaa", "a", "abbaa"}, {"aabb", "b", "aabb"}, {1234, "12", "34"}, {1234, "34", "1234"}, // errors {"", tstNoStringer{}, false}, {tstNoStringer{}, "", false}, } { result, err := ns.TrimPrefix(test.prefix, test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestTrimRight(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any cutset any expect any }{ {"abba", "a", "abb"}, {"abba", "ab", ""}, {"<tag>", "<>", "<tag"}, {`"quote"`, `"`, `"quote`}, {1221, "1", "122"}, {1221, "12", ""}, {"007", "0", "007"}, {template.HTML("<tag>"), "<>", "<tag"}, {[]byte("<tag>"), "<>", "<tag"}, // errors {"", tstNoStringer{}, false}, {tstNoStringer{}, "", false}, } { result, err := ns.TrimRight(test.cutset, test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestTrimSuffix(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any suffix any expect any }{ {"aabbaa", "a", "aabba"}, {"aabb", "b", "aab"}, {1234, "12", "1234"}, {1234, "34", "12"}, // errors {"", tstNoStringer{}, false}, {tstNoStringer{}, "", false}, } { result, err := ns.TrimSuffix(test.suffix, test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestRepeat(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any n any expect any }{ {"yo", "2", "yoyo"}, {"~", "16", "~~~~~~~~~~~~~~~~"}, {"<tag>", "0", ""}, {"yay", "1", "yay"}, {1221, "1", "1221"}, {1221, 2, "12211221"}, {template.HTML("<tag>"), "2", "<tag><tag>"}, {[]byte("<tag>"), 2, "<tag><tag>"}, // errors {"", tstNoStringer{}, false}, {tstNoStringer{}, "", false}, {"ab", -1, false}, } { result, err := ns.Repeat(test.n, test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestDiff(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { oldname string old any newname string new any expect any }{ {"old", "foo\n", "new", "bar\n", "diff old new\n--- old\n+++ new\n@@ -1,1 +1,1 @@\n-foo\n+bar\n"}, {"old", "foo\n", "new", "foo\n", ""}, {"old", "foo\n", "new", "", "diff old new\n--- old\n+++ new\n@@ -1,1 +0,0 @@\n-foo\n"}, {"old", "foo\n", "new", nil, "diff old new\n--- old\n+++ new\n@@ -1,1 +0,0 @@\n-foo\n"}, {"old", "", "new", "", ""}, // errors {"old", tstNoStringer{}, "new", "foo", false}, {"old", "foo", "new", tstNoStringer{}, false}, } { result, err := ns.Diff(test.oldname, test.old, test.newname, test.new) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } } func TestTrimSpace(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { s any expect any }{ {"\n\r test \n\r", "test"}, {template.HTML("\n\r test \n\r"), "test"}, {[]byte("\n\r test \n\r"), "test"}, // errors {tstNoStringer{}, false}, } { result, err := ns.TrimSpace(test.s) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil)) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/strings/truncate_test.go
tpl/strings/truncate_test.go
// Copyright 2016 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package strings import ( "html/template" "reflect" "strings" "testing" ) func TestTruncate(t *testing.T) { t.Parallel() var err error cases := []struct { v1 any v2 any v3 any want any isErr bool }{ {10, "I am a test sentence", nil, template.HTML("I am a …"), false}, {10, "", "I am a test sentence", template.HTML("I am a"), false}, {10, "", "a b c d e f g h i j k", template.HTML("a b c d e"), false}, {12, "", "<b>Should be escaped</b>", template.HTML("&lt;b&gt;Should be"), false}, {10, template.HTML(" <a href='#'>Read more</a>"), "I am a test sentence", template.HTML("I am a <a href='#'>Read more</a>"), false}, {20, template.HTML("I have a <a href='/markdown'>Markdown link</a> inside."), nil, template.HTML("I have a <a href='/markdown'>Markdown …</a>"), false}, {10, "IamanextremelylongwordthatjustgoesonandonandonjusttoannoyyoualmostasifIwaswritteninGermanActuallyIbettheresagermanwordforthis", nil, template.HTML("Iamanextre …"), false}, {10, template.HTML("<p>IamanextremelylongwordthatjustgoesonandonandonjusttoannoyyoualmostasifIwaswritteninGermanActuallyIbettheresagermanwordforthis</p>"), nil, template.HTML("<p>Iamanextre …</p>"), false}, {13, template.HTML("With <a href=\"/markdown\">Markdown</a> inside."), nil, template.HTML("With <a href=\"/markdown\">Markdown …</a>"), false}, {14, "Hello中国 Good 好的", nil, template.HTML("Hello中国 Good 好 …"), false}, {12, "", "日本語でHugoを使います", template.HTML("日本語でHugoを使いま"), false}, {12, "", "日本語で Hugo を使います", template.HTML("日本語で Hugo を使"), false}, {8, "", "日本語でHugoを使います", template.HTML("日本語でHugo"), false}, {10, "", "日本語で Hugo を使います", template.HTML("日本語で Hugo"), false}, {9, "", "日本語で Hugo を使います", template.HTML("日本語で Hugo"), false}, {7, "", "日本語でHugoを使います", template.HTML("日本語で"), false}, {7, "", "日本語で Hugo を使います", template.HTML("日本語で"), false}, {6, "", "日本語でHugoを使います", template.HTML("日本語で"), false}, {6, "", "日本語で Hugo を使います", template.HTML("日本語で"), false}, {5, "", "日本語でHugoを使います", template.HTML("日本語で"), false}, {5, "", "日本語で Hugo を使います", template.HTML("日本語で"), false}, {4, "", "日本語でHugoを使います", template.HTML("日本語で"), false}, {4, "", "日本語で Hugo を使います", template.HTML("日本語で"), false}, {15, "", template.HTML("A <br> tag that's not closed"), template.HTML("A <br> tag that's"), false}, {14, template.HTML("<p>Hello中国 Good 好的</p>"), nil, template.HTML("<p>Hello中国 Good 好 …</p>"), false}, {2, template.HTML("<p>P1</p><p>P2</p>"), nil, template.HTML("<p>P1 …</p>"), false}, {3, template.HTML(strings.Repeat("<p>P</p>", 20)), nil, template.HTML("<p>P</p><p>P</p><p>P …</p>"), false}, {18, template.HTML("<p>test <b>hello</b> test something</p>"), nil, template.HTML("<p>test <b>hello</b> test …</p>"), false}, {4, template.HTML("<p>a<b><i>b</b>c d e</p>"), nil, template.HTML("<p>a<b><i>b</b>c …</p>"), false}, { 42, template.HTML(`With strangely formatted <a href="#" target="_blank" >HTML</a > inside.`), nil, template.HTML(`With strangely formatted <a href="#" target="_blank" >HTML …</a>`), false, }, {10, nil, nil, template.HTML(""), true}, {nil, nil, nil, template.HTML(""), true}, } for i, c := range cases { var result template.HTML if c.v2 == nil { result, err = ns.Truncate(c.v1) } else if c.v3 == nil { result, err = ns.Truncate(c.v1, c.v2) } else { result, err = ns.Truncate(c.v1, c.v2, c.v3) } if c.isErr { if err == nil { t.Errorf("[%d] Slice didn't return an expected error", i) } } else { if err != nil { t.Errorf("[%d] failed: %s", i, err) continue } if !reflect.DeepEqual(result, c.want) { t.Errorf("[%d] got '%s' but expected '%s'", i, result, c.want) } } } // Too many arguments _, err = ns.Truncate(10, " ...", "I am a test sentence", "wrong") if err == nil { t.Errorf("Should have errored") } } func BenchmarkTruncate(b *testing.B) { b.Run("Plain text", func(b *testing.B) { for b.Loop() { ns.Truncate(10, "I am a test sentence") } }) b.Run("With link", func(b *testing.B) { for b.Loop() { ns.Truncate(10, "I have a <a href='/markdown'>Markdown link</a> inside") } }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/strings/regexp.go
tpl/strings/regexp.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 strings import ( "github.com/gohugoio/hugo/common/hstrings" "github.com/spf13/cast" ) // FindRE returns a list of strings that match the regular expression. By default all matches // will be included. The number of matches can be limited with an optional third parameter. func (ns *Namespace) FindRE(expr string, content any, limit ...any) ([]string, error) { re, err := hstrings.GetOrCompileRegexp(expr) if err != nil { return nil, err } conv, err := cast.ToStringE(content) if err != nil { return nil, err } if len(limit) == 0 { return re.FindAllString(conv, -1), nil } lim, err := cast.ToIntE(limit[0]) if err != nil { return nil, err } return re.FindAllString(conv, lim), nil } // FindRESubmatch returns a slice of all successive matches of the regular // expression in content. Each element is a slice of strings holding the text // of the leftmost match of the regular expression and the matches, if any, of // its subexpressions. // // By default all matches will be included. The number of matches can be // limited with the optional limit parameter. A return value of nil indicates // no match. func (ns *Namespace) FindRESubmatch(expr string, content any, limit ...any) ([][]string, error) { re, err := hstrings.GetOrCompileRegexp(expr) if err != nil { return nil, err } conv, err := cast.ToStringE(content) if err != nil { return nil, err } n := -1 if len(limit) > 0 { n, err = cast.ToIntE(limit[0]) if err != nil { return nil, err } } return re.FindAllStringSubmatch(conv, n), nil } // ReplaceRE returns a copy of s, replacing all matches of the regular // expression pattern with the replacement text repl. The number of replacements // can be limited with an optional fourth parameter. func (ns *Namespace) ReplaceRE(pattern, repl, s any, n ...any) (_ string, err error) { sp, err := cast.ToStringE(pattern) if err != nil { return } sr, err := cast.ToStringE(repl) if err != nil { return } ss, err := cast.ToStringE(s) if err != nil { return } nn := -1 if len(n) > 0 { nn, err = cast.ToIntE(n[0]) if err != nil { return } } re, err := hstrings.GetOrCompileRegexp(sp) if err != nil { return "", err } return re.ReplaceAllStringFunc(ss, func(str string) string { if nn == 0 { return str } nn -= 1 return re.ReplaceAllString(str, sr) }), nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/strings/truncate.go
tpl/strings/truncate.go
// Copyright 2016 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package strings import ( "errors" "html" "html/template" "regexp" "strings" "unicode" "unicode/utf8" "github.com/spf13/cast" ) var ( tagRE = regexp.MustCompile(`^<(/)?([^ ]+?)(?:(\s*/)| .*?)?>`) htmlSinglets = map[string]bool{ "br": true, "col": true, "link": true, "base": true, "img": true, "param": true, "area": true, "hr": true, "input": true, } ) type htmlTag struct { name string pos int openTag bool } // Truncate truncates the string in s to the specified length. func (ns *Namespace) Truncate(s any, options ...any) (template.HTML, error) { length, err := cast.ToIntE(s) if err != nil { return "", err } var textParam any var ellipsis string switch len(options) { case 0: return "", errors.New("truncate requires a length and a string") case 1: textParam = options[0] ellipsis = " …" case 2: textParam = options[1] ellipsis, err = cast.ToStringE(options[0]) if err != nil { return "", errors.New("ellipsis must be a string") } if _, ok := options[0].(template.HTML); !ok { ellipsis = html.EscapeString(ellipsis) } default: return "", errors.New("too many arguments passed to truncate") } text, err := cast.ToStringE(textParam) if err != nil { return "", errors.New("text must be a string") } _, isHTML := textParam.(template.HTML) if utf8.RuneCountInString(text) <= length { if isHTML { return template.HTML(text), nil } return template.HTML(html.EscapeString(text)), nil } tags := []htmlTag{} var lastWordIndex, lastNonSpace, currentLen, endTextPos, nextTag int for i, r := range text { if i < nextTag { continue } if isHTML { // Make sure we keep tagname of HTML tags slice := text[i:] m := tagRE.FindStringSubmatchIndex(slice) if len(m) > 0 && m[0] == 0 { nextTag = i + m[1] tagname := strings.Fields(slice[m[4]:m[5]])[0] lastWordIndex = lastNonSpace _, singlet := htmlSinglets[tagname] if !singlet && m[6] == -1 { tags = append(tags, htmlTag{name: tagname, pos: i, openTag: m[2] == -1}) } continue } } currentLen++ if unicode.IsSpace(r) { lastWordIndex = lastNonSpace } else if unicode.In(r, unicode.Han, unicode.Hangul, unicode.Hiragana, unicode.Katakana) { lastWordIndex = lastNonSpace lastNonSpace = i + utf8.RuneLen(r) if currentLen <= length { lastWordIndex = lastNonSpace } } else { lastNonSpace = i + utf8.RuneLen(r) } if currentLen > length { if lastWordIndex == 0 { endTextPos = i } else { endTextPos = lastWordIndex } out := text[0:endTextPos] if isHTML { out += ellipsis // Close out any open HTML tags var currentTag *htmlTag for i := len(tags) - 1; i >= 0; i-- { tag := tags[i] if tag.pos >= endTextPos || currentTag != nil { if currentTag != nil && currentTag.name == tag.name { currentTag = nil } continue } if tag.openTag { out += ("</" + tag.name + ">") } else { currentTag = &tag } } return template.HTML(out), nil } return template.HTML(html.EscapeString(out) + ellipsis), nil } } if isHTML { return template.HTML(text), nil } return template.HTML(html.EscapeString(text)), nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/strings/strings.go
tpl/strings/strings.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 strings provides template functions for manipulating strings. package strings import ( "errors" "fmt" "html/template" "regexp" "strings" "unicode" "unicode/utf8" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/tpl" "github.com/rogpeppe/go-internal/diff" "github.com/spf13/cast" ) // New returns a new instance of the strings-namespaced template functions. func New(d *deps.Deps) *Namespace { return &Namespace{deps: d} } // Namespace provides template functions for the "strings" namespace. // Most functions mimic the Go stdlib, but the order of the parameters may be // different to ease their use in the Go template system. type Namespace struct { deps *deps.Deps } // CountRunes returns the number of runes in s, excluding whitespace. func (ns *Namespace) CountRunes(s any) (int, error) { ss, err := cast.ToStringE(s) if err != nil { return 0, fmt.Errorf("failed to convert content to string: %w", err) } counter := 0 for _, r := range tpl.StripHTML(ss) { if !helpers.IsWhitespace(r) { counter++ } } return counter, nil } // RuneCount returns the number of runes in s. func (ns *Namespace) RuneCount(s any) (int, error) { ss, err := cast.ToStringE(s) if err != nil { return 0, fmt.Errorf("failed to convert content to string: %w", err) } return utf8.RuneCountInString(ss), nil } // CountWords returns the approximate word count in s. func (ns *Namespace) CountWords(s any) (int, error) { ss, err := cast.ToStringE(s) if err != nil { return 0, fmt.Errorf("failed to convert content to string: %w", err) } isCJKLanguage, err := regexp.MatchString(`\p{Han}|\p{Hangul}|\p{Hiragana}|\p{Katakana}`, ss) if err != nil { return 0, fmt.Errorf("failed to match regex pattern against string: %w", err) } if !isCJKLanguage { return len(strings.Fields(tpl.StripHTML(ss))), nil } counter := 0 for word := range strings.FieldsSeq(tpl.StripHTML(ss)) { runeCount := utf8.RuneCountInString(word) if len(word) == runeCount { counter++ } else { counter += runeCount } } return counter, nil } // Count counts the number of non-overlapping instances of substr in s. // If substr is an empty string, Count returns 1 + the number of Unicode code points in s. func (ns *Namespace) Count(substr, s any) (int, error) { substrs, err := cast.ToStringE(substr) if err != nil { return 0, fmt.Errorf("failed to convert substr to string: %w", err) } ss, err := cast.ToStringE(s) if err != nil { return 0, fmt.Errorf("failed to convert s to string: %w", err) } return strings.Count(ss, substrs), nil } // Chomp returns a copy of s with all trailing newline characters removed. func (ns *Namespace) Chomp(s any) (any, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } res := text.Chomp(ss) switch s.(type) { case template.HTML: return template.HTML(res), nil default: return res, nil } } // Contains reports whether substr is in s. func (ns *Namespace) Contains(s, substr any) (bool, error) { ss, err := cast.ToStringE(s) if err != nil { return false, err } su, err := cast.ToStringE(substr) if err != nil { return false, err } return strings.Contains(ss, su), nil } // ContainsAny reports whether any Unicode code points in chars are within s. func (ns *Namespace) ContainsAny(s, chars any) (bool, error) { ss, err := cast.ToStringE(s) if err != nil { return false, err } sc, err := cast.ToStringE(chars) if err != nil { return false, err } return strings.ContainsAny(ss, sc), nil } // ContainsNonSpace reports whether s contains any non-space characters as defined // by Unicode's White Space property, // <docsmeta>{"newIn": "0.111.0" }</docsmeta> func (ns *Namespace) ContainsNonSpace(s any) (bool, error) { ss, err := cast.ToStringE(s) if err != nil { return false, err } for _, r := range ss { if !unicode.IsSpace(r) { return true, nil } } return false, nil } // Diff returns an anchored diff of the two texts old and new in the “unified // diff” format. If old and new are identical, Diff returns an empty string. func (ns *Namespace) Diff(oldname string, old any, newname string, new any) (string, error) { olds, err := cast.ToStringE(old) if err != nil { return "", err } news, err := cast.ToStringE(new) if err != nil { return "", err } return string(diff.Diff(oldname, []byte(olds), newname, []byte(news))), nil } // HasPrefix tests whether the input s begins with prefix. func (ns *Namespace) HasPrefix(s, prefix any) (bool, error) { ss, err := cast.ToStringE(s) if err != nil { return false, err } sx, err := cast.ToStringE(prefix) if err != nil { return false, err } return strings.HasPrefix(ss, sx), nil } // HasSuffix tests whether the input s begins with suffix. func (ns *Namespace) HasSuffix(s, suffix any) (bool, error) { ss, err := cast.ToStringE(s) if err != nil { return false, err } sx, err := cast.ToStringE(suffix) if err != nil { return false, err } return strings.HasSuffix(ss, sx), nil } // Replace returns a copy of the string s with all occurrences of old replaced // with new. The number of replacements can be limited with an optional fourth // parameter. func (ns *Namespace) Replace(s, old, new any, limit ...any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } so, err := cast.ToStringE(old) if err != nil { return "", err } sn, err := cast.ToStringE(new) if err != nil { return "", err } if len(limit) == 0 { return strings.ReplaceAll(ss, so, sn), nil } lim, err := cast.ToIntE(limit[0]) if err != nil { return "", err } return strings.Replace(ss, so, sn, lim), nil } // SliceString slices a string by specifying a half-open range with // two indices, start and end. 1 and 4 creates a slice including elements 1 through 3. // The end index can be omitted, it defaults to the string's length. func (ns *Namespace) SliceString(a any, startEnd ...any) (string, error) { aStr, err := cast.ToStringE(a) if err != nil { return "", err } var argStart, argEnd int argNum := len(startEnd) if argNum > 0 { if argStart, err = cast.ToIntE(startEnd[0]); err != nil { return "", errors.New("start argument must be integer") } } if argNum > 1 { if argEnd, err = cast.ToIntE(startEnd[1]); err != nil { return "", errors.New("end argument must be integer") } } if argNum > 2 { return "", errors.New("too many arguments") } asRunes := []rune(aStr) if argNum > 0 && (argStart < 0 || argStart >= len(asRunes)) { return "", errors.New("slice bounds out of range") } if argNum == 2 { if argEnd < 0 || argEnd > len(asRunes) { return "", errors.New("slice bounds out of range") } return string(asRunes[argStart:argEnd]), nil } else if argNum == 1 { return string(asRunes[argStart:]), nil } else { return string(asRunes[:]), nil } } // Split slices an input string into all substrings separated by delimiter. func (ns *Namespace) Split(a any, delimiter string) ([]string, error) { aStr, err := cast.ToStringE(a) if err != nil { return []string{}, err } return strings.Split(aStr, delimiter), nil } // Substr extracts parts of a string, beginning at the character at the specified // position, and returns the specified number of characters. // // It normally takes two parameters: start and length. // It can also take one parameter: start, i.e. length is omitted, in which case // the substring starting from start until the end of the string will be returned. // // To extract characters from the end of the string, use a negative start number. // // In addition, borrowing from the extended behavior described at http://php.net/substr, // if length is given and is negative, then that many characters will be omitted from // the end of string. func (ns *Namespace) Substr(a any, nums ...any) (string, error) { s, err := cast.ToStringE(a) if err != nil { return "", err } asRunes := []rune(s) rlen := len(asRunes) var start, length int switch len(nums) { case 0: return "", errors.New("too few arguments") case 1: if start, err = cast.ToIntE(nums[0]); err != nil { return "", errors.New("start argument must be an integer") } length = rlen case 2: if start, err = cast.ToIntE(nums[0]); err != nil { return "", errors.New("start argument must be an integer") } if length, err = cast.ToIntE(nums[1]); err != nil { return "", errors.New("length argument must be an integer") } default: return "", errors.New("too many arguments") } if rlen == 0 { return "", nil } if start < 0 { start += rlen } // start was originally negative beyond rlen if start < 0 { start = 0 } if start > rlen-1 { return "", nil } end := rlen switch { case length == 0: return "", nil case length < 0: end += length case length > 0: end = start + length } if start >= end { return "", nil } if end < 0 { return "", nil } if end > rlen { end = rlen } return string(asRunes[start:end]), nil } // Title returns a copy of the input s with all Unicode letters that begin words // mapped to their title case. func (ns *Namespace) Title(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return ns.deps.Conf.CreateTitle(ss), nil } // FirstUpper converts s making the first character upper case. func (ns *Namespace) FirstUpper(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return helpers.FirstUpper(ss), nil } // ToLower returns a copy of the input s with all Unicode letters mapped to their // lower case. func (ns *Namespace) ToLower(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return strings.ToLower(ss), nil } // ToUpper returns a copy of the input s with all Unicode letters mapped to their // upper case. func (ns *Namespace) ToUpper(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return strings.ToUpper(ss), nil } // Trim returns converts the strings s removing all leading and trailing characters defined // contained. func (ns *Namespace) Trim(s, cutset any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } sc, err := cast.ToStringE(cutset) if err != nil { return "", err } return strings.Trim(ss, sc), nil } // TrimSpace returns the given string, removing leading and trailing whitespace // as defined by Unicode. func (ns *Namespace) TrimSpace(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return strings.TrimSpace(ss), nil } // TrimLeft returns a slice of the string s with all leading characters // contained in cutset removed. func (ns *Namespace) TrimLeft(cutset, s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } sc, err := cast.ToStringE(cutset) if err != nil { return "", err } return strings.TrimLeft(ss, sc), nil } // TrimPrefix returns s without the provided leading prefix string. If s doesn't // start with prefix, s is returned unchanged. func (ns *Namespace) TrimPrefix(prefix, s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } sx, err := cast.ToStringE(prefix) if err != nil { return "", err } return strings.TrimPrefix(ss, sx), nil } // TrimRight returns a slice of the string s with all trailing characters // contained in cutset removed. func (ns *Namespace) TrimRight(cutset, s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } sc, err := cast.ToStringE(cutset) if err != nil { return "", err } return strings.TrimRight(ss, sc), nil } // TrimSuffix returns s without the provided trailing suffix string. If s // doesn't end with suffix, s is returned unchanged. func (ns *Namespace) TrimSuffix(suffix, s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } sx, err := cast.ToStringE(suffix) if err != nil { return "", err } return strings.TrimSuffix(ss, sx), nil } // Repeat returns a new string consisting of n copies of the string s. func (ns *Namespace) Repeat(n, s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } sn, err := cast.ToIntE(n) if err != nil { return "", err } if sn < 0 { return "", errors.New("strings: negative Repeat count") } return strings.Repeat(ss, sn), nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/partials/init.go
tpl/partials/init.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 partials import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const namespaceName = "partials" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New(d) ns := &internal.TemplateFuncsNamespace{ Name: namespaceName, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.Include, []string{"partial"}, [][2]string{ {`{{ partial "header.html" . }}`, `<title>Hugo Rocks!</title>`}, }, ) ns.AddMethodMapping(ctx.IncludeCached, []string{"partialCached"}, [][2]string{}, ) // TODO(bep) we need the return to be a valid identifiers, but // should consider another way of adding it. ns.AddMethodMapping(func() string { return "" }, []string{"return"}, [][2]string{}, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/partials/partials.go
tpl/partials/partials.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 partials provides template functions for working with reusable // templates. package partials import ( "context" "fmt" "html/template" "io" "strings" "time" "github.com/bep/lazycache" "github.com/gohugoio/hugo/common/constants" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/identity" texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/tpl/tplimpl" bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/deps" ) type partialCacheKey struct { Name string Variants []any } type includeResult struct { name string result any mangager identity.Manager err error } func (k partialCacheKey) Key() string { if k.Variants == nil { return k.Name } return hashing.HashString(append([]any{k.Name}, k.Variants...)...) } // partialCache represents a LRU cache of partials. type partialCache struct { cache *lazycache.Cache[string, includeResult] } func (p *partialCache) clear() { p.cache.DeleteFunc(func(s string, r includeResult) bool { return true }) } // New returns a new instance of the templates-namespaced template functions. func New(deps *deps.Deps) *Namespace { // This lazycache was introduced in Hugo 0.111.0. // We're going to expand and consolidate all memory caches in Hugo using this, // so just set a high limit for now. lru := lazycache.New(lazycache.Options[string, includeResult]{MaxEntries: 1000}) cache := &partialCache{cache: lru} deps.BuildStartListeners.Add( func(...any) bool { cache.clear() return false }) return &Namespace{ deps: deps, cachedPartials: cache, } } // Namespace provides template functions for the "templates" namespace. type Namespace struct { deps *deps.Deps cachedPartials *partialCache } // contextWrapper makes room for a return value in a partial invocation. type contextWrapper struct { Arg any Result any } // Set sets the return value and returns an empty string. func (c *contextWrapper) Set(in any) string { c.Result = in return "" } // Include executes the named partial. // If the partial contains a return statement, that value will be returned. // Else, the rendered output will be returned: // A string if the partial is a text/template, or template.HTML when html/template. // Note that ctx is provided by Hugo, not the end user. func (ns *Namespace) Include(ctx context.Context, name string, contextList ...any) (any, error) { res := ns.include(ctx, name, contextList...) if res.err != nil { return nil, res.err } if ns.deps.Metrics != nil { ns.deps.Metrics.TrackValue(res.name, res.result, false) } return res.result, nil } func (ns *Namespace) include(ctx context.Context, name string, dataList ...any) includeResult { v, err := ns.lookup(name) if err != nil { return includeResult{err: err} } return ns.doInclude(ctx, "", v, dataList...) } func (ns *Namespace) lookup(name string) (*tplimpl.TemplInfo, error) { if strings.HasPrefix(name, "partials/") { // This is most likely not what the user intended. // This worked before Hugo 0.146.0. ns.deps.Log.Warnidf(constants.WarnPartialSuperfluousPrefix, "Doubtful use of partial function in {{ partial \"%s\"}}), this is most likely not what you want. Consider removing superfluous prefix \"partials/\" from template name given as first function argument.", name) } v := ns.deps.TemplateStore.LookupPartial(name) if v == nil { return nil, fmt.Errorf("partial %q not found", name) } return v, nil } // include is a helper function that lookups and executes the named partial. // Returns the final template name and the rendered output. func (ns *Namespace) doInclude(ctx context.Context, key string, templ *tplimpl.TemplInfo, dataList ...any) includeResult { if templ.ParseInfo.HasPartialInner { stack := tpl.Context.PartialDecoratorIDStack.Get(ctx) if stack != nil { if id, ok := stack.Peek(); ok { // Signal that inner exists. id.Bool = true } } } var data any if len(dataList) > 0 { data = dataList[0] } info := templ.ParseInfo var w io.Writer if info.HasReturn { // Wrap the context sent to the template to capture the return value. // Note that the template is rewritten to make sure that the dot (".") // and the $ variable points to Arg. data = &contextWrapper{ Arg: data, } // We don't care about any template output. w = io.Discard } else { b := bp.GetBuffer() defer bp.PutBuffer(b) w = b } if err := ns.deps.GetTemplateStore().ExecuteWithContextAndKey(ctx, key, templ, w, data); err != nil { return includeResult{err: err} } var result any if ctx, ok := data.(*contextWrapper); ok { result = ctx.Result } else if _, ok := templ.Template.(*texttemplate.Template); ok { result = w.(fmt.Stringer).String() } else { result = template.HTML(w.(fmt.Stringer).String()) } return includeResult{ name: templ.Name(), result: result, } } // IncludeCached executes and caches partial templates. The cache is created with name+variants as the key. // Note that ctx is provided by Hugo, not the end user. func (ns *Namespace) IncludeCached(ctx context.Context, name string, context any, variants ...any) (any, error) { start := time.Now() key := partialCacheKey{ Name: name, Variants: variants, } keyString := key.Key() depsManagerIn := tpl.Context.GetDependencyManagerInCurrentScope(ctx) ti, err := ns.lookup(name) if err != nil { return nil, err } if parent := tpl.Context.CurrentTemplate.Get(ctx); parent != nil { for parent != nil { if parent.CurrentTemplateInfoOps == ti && parent.Key == keyString { // This will deadlock if we continue. return nil, fmt.Errorf("circular call stack detected in partial %q", ti.Filename()) } parent = parent.Parent } } r, found, err := ns.cachedPartials.cache.GetOrCreate(keyString, func(string) (includeResult, error) { var depsManagerShared identity.Manager if ns.deps.Conf.Watching() { // We need to create a shared dependency manager to pass downwards // and add those same dependencies to any cached invocation of this partial. depsManagerShared = identity.NewManager() ctx = tpl.Context.DependencyManagerScopedProvider.Set(ctx, depsManagerShared.(identity.DependencyManagerScopedProvider)) } r := ns.doInclude(ctx, keyString, ti, context) if ns.deps.Conf.Watching() { r.mangager = depsManagerShared } return r, r.err }) if err != nil { return nil, err } if ns.deps.Metrics != nil { if found { // The templates that gets executed is measured in Execute. // We need to track the time spent in the cache to // get the totals correct. ns.deps.Metrics.MeasureSince(r.name, start) } ns.deps.Metrics.TrackValue(r.name, r.result, found) } if r.mangager != nil && depsManagerIn != nil { depsManagerIn.AddIdentity(r.mangager) } return r.result, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/partials/partials_integration_test.go
tpl/partials/partials_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package partials_test import ( "bytes" "fmt" "regexp" "sort" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/htesting/hqt" "github.com/gohugoio/hugo/hugolib" ) func TestInclude(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.com/' -- layouts/home.html -- partial: {{ partials.Include "foo.html" . }} -- layouts/_partials/foo.html -- foo ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` partial: foo `) } func TestIncludeCached(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.com/' -- layouts/home.html -- partialCached: {{ partials.IncludeCached "foo.html" . }} partialCached: {{ partials.IncludeCached "foo.html" . }} -- layouts/_partials/foo.html -- foo ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` partialCached: foo partialCached: foo `) } // Issue 9519 func TestIncludeCachedRecursion(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.com/' -- layouts/home.html -- {{ partials.IncludeCached "p1.html" . }} -- layouts/_partials/p1.html -- {{ partials.IncludeCached "p2.html" . }} -- layouts/_partials/p2.html -- P2 ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` P2 `) } // Issue #588 func TestIncludeCachedRecursionShortcode(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.com/' -- content/_index.md -- --- title: "Index" --- {{< short >}} -- layouts/home.html -- {{ partials.IncludeCached "p1.html" . }} -- layouts/_partials/p1.html -- {{ .Content }} {{ partials.IncludeCached "p2.html" . }} -- layouts/_partials/p2.html -- -- layouts/_shortcodes/short.html -- SHORT {{ partials.IncludeCached "p2.html" . }} P2 ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` SHORT P2 `) } func TestIncludeCacheHints(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.com/' templateMetrics=true templateMetricsHints=true disableKinds = ["page", "section", "taxonomy", "term", "sitemap"] [outputs] home = ["HTML"] -- layouts/home.html -- {{ partials.IncludeCached "static1.html" . }} {{ partials.IncludeCached "static1.html" . }} {{ partials.Include "static2.html" . }} D1I: {{ partials.Include "dynamic1.html" . }} D1C: {{ partials.IncludeCached "dynamic1.html" . }} D1C: {{ partials.IncludeCached "dynamic1.html" . }} D1C: {{ partials.IncludeCached "dynamic1.html" . }} H1I: {{ partials.Include "halfdynamic1.html" . }} H1C: {{ partials.IncludeCached "halfdynamic1.html" . }} H1C: {{ partials.IncludeCached "halfdynamic1.html" . }} -- layouts/_partials/static1.html -- P1 -- layouts/_partials/static2.html -- P2 -- layouts/_partials/dynamic1.html -- {{ math.Counter }} -- layouts/_partials/halfdynamic1.html -- D1 {{ math.Counter }} ` b := hugolib.Test(t, files) // fmt.Println(b.FileContent("public/index.html")) var buf bytes.Buffer b.H.Metrics.WriteMetrics(&buf) got := buf.String() // Get rid of all the durations, they are never the same. durationRe := regexp.MustCompile(`\b[\.\d]*(ms|ns|µs|s)\b`) normalize := func(s string) string { s = durationRe.ReplaceAllString(s, "") linesIn := strings.Split(s, "\n")[3:] var lines []string for _, l := range linesIn { l = strings.TrimSpace(l) if l == "" { continue } lines = append(lines, l) } sort.Strings(lines) return strings.Join(lines, "\n") } got = normalize(got) expect := ` 0 0 0 1 home.html 100 0 0 1 _partials/static2.html 100 50 1 2 _partials/static1.html 25 50 2 4 _partials/dynamic1.html 66 33 1 3 _partials/halfdynamic1.html ` b.Assert(got, hqt.IsSameString, expect) } // gobench --package ./tpl/partials func BenchmarkIncludeCached(b *testing.B) { files := ` -- hugo.toml -- baseURL = 'http://example.com/' -- layouts/home.html -- -- layouts/single.html -- {{ partialCached "heavy.html" "foo" }} {{ partialCached "easy1.html" "bar" }} {{ partialCached "easy1.html" "baz" }} {{ partialCached "easy2.html" "baz" }} -- layouts/_partials/easy1.html -- ABCD -- layouts/_partials/easy2.html -- ABCDE -- layouts/_partials/heavy.html -- {{ $result := slice }} {{ range site.RegularPages }} {{ $result = $result | append (dict "title" .Title "link" .RelPermalink "readingTime" .ReadingTime) }} {{ end }} {{ range $result }} * {{ .title }} {{ .link }} {{ .readingTime }} {{ end }} ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/p%d.md --\n---\ntitle: page\n---\n"+strings.Repeat("FOO ", i), i) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } for b.Loop() { b.StopTimer() bb := hugolib.NewIntegrationTestBuilder(cfg) b.StartTimer() bb.Build() } } func TestIncludeTimeout(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.com/' -- layouts/home.html -- {{ partials.Include "foo.html" . }} -- layouts/_partials/foo.html -- {{ partial "foo.html" . }} ` b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, "maximum template call stack size exceeded") } func TestIncludeCachedTimeout(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.com/' timeout = '200ms' -- layouts/home.html -- {{ partials.IncludeCached "foo.html" . }} -- layouts/_partials/foo.html -- {{ partialCached "bar.html" . }} -- layouts/_partials/bar.html -- {{ partialCached "foo.html" . }} ` b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, `error calling partialCached: circular call stack detected in partial`) } // See Issue #13889 func TestIncludeCachedDifferentKey(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.com/' timeout = '200ms' -- layouts/home.html -- {{ partialCached "foo.html" "a" "a" }} -- layouts/_partials/foo.html -- {{ if eq . "a" }} {{ partialCached "bar.html" . }} {{ else }} DONE {{ end }} -- layouts/_partials/bar.html -- {{ partialCached "foo.html" "b" "b" }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` DONE `) } // See Issue #10789 func TestReturnExecuteFromTemplateInPartial(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.com/' -- layouts/home.html -- {{ $r := partial "foo" }} FOO:{{ $r.Content }} -- layouts/_partials/foo.html -- {{ $r := §§{{ partial "bar" }}§§ | resources.FromString "bar.html" | resources.ExecuteAsTemplate "bar.html" . }} {{ return $r }} -- layouts/_partials/bar.html -- BAR ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "OO:BAR") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/js/init.go
tpl/js/init.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 js import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const name = "js" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx, err := New(d) if err != nil { panic(err) } ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.Babel, []string{"babel"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Batch, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Build, nil, [][2]string{}, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/js/js.go
tpl/js/js.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package js provides functions for building JavaScript resources package js import ( "errors" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/internal/js" "github.com/gohugoio/hugo/internal/js/esbuild" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/resources/resource_transformers/babel" jstransform "github.com/gohugoio/hugo/resources/resource_transformers/js" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" ) // New returns a new instance of the js-namespaced template functions. func New(d *deps.Deps) (*Namespace, error) { if d.ResourceSpec == nil { return &Namespace{}, nil } return &Namespace{ d: d, jsTransformClient: jstransform.New(d.BaseFs.Assets, d.ResourceSpec), createClient: create.New(d.ResourceSpec), babelClient: babel.New(d.ResourceSpec), }, nil } // Namespace provides template functions for the "js" namespace. type Namespace struct { d *deps.Deps jsTransformClient *jstransform.Client createClient *create.Client babelClient *babel.Client } // Build processes the given Resource with ESBuild. func (ns *Namespace) Build(args ...any) (resource.Resource, error) { var ( r resources.ResourceTransformer m map[string]any targetPath string err error ok bool ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if targetPath != "" { m = map[string]any{"targetPath": targetPath} } return ns.jsTransformClient.Process(r, m) } // Batch creates a new Batcher with the given ID. // Repeated calls with the same ID will return the same Batcher. // The ID will be used to name the root directory of the batch. // Forward slashes in the ID is allowed. func (ns *Namespace) Batch(id string) (js.Batcher, error) { if err := esbuild.ValidateBatchID(id, true); err != nil { return nil, err } b, err := ns.d.JSBatcherClient.Store().GetOrCreate(id, func() (js.Batcher, error) { return ns.d.JSBatcherClient.New(id) }) if err != nil { return nil, err } return b, nil } // Babel processes the given Resource with Babel. func (ns *Namespace) Babel(args ...any) (resource.Resource, error) { if len(args) > 2 { return nil, errors.New("must not provide more arguments than resource object and options") } r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options babel.Options if m != nil { options, err = babel.DecodeOptions(m) if err != nil { return nil, err } } return ns.babelClient.Process(r, options) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/reflect/init.go
tpl/reflect/init.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 reflect provides template functions for run-time object reflection. package reflect import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const name = "reflect" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New() ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.IsMap, nil, [][2]string{ {`{{ if reflect.IsMap (dict "a" 1) }}Map{{ end }}`, `Map`}, }, ) ns.AddMethodMapping(ctx.IsSlice, nil, [][2]string{ {`{{ if reflect.IsSlice (slice 1 2 3) }}Slice{{ end }}`, `Slice`}, }, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/reflect/reflect_integration_test.go
tpl/reflect/reflect_integration_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reflect_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestIs(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- assets/a.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- assets/b.svg -- <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> </svg> -- assets/c.txt -- This is a text file. -- assets/d.avif -- AAAAHGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZgAAAOptZXRhAAAAAAAAACFoZGxyAAAAAAAAAABwaWN0AAAAAAAAAAAAAAAAAAAAAA5waXRtAAAAAAABAAAAImlsb2MAAAAAREAAAQABAAAAAAEOAAEAAAAAAAAAEgAAACNpaW5mAAAAAAABAAAAFWluZmUCAAAAAAEAAGF2MDEAAAAAamlwcnAAAABLaXBjbwAAABNjb2xybmNseAABAA0ABoAAAAAMYXYxQ4EgAgAAAAAUaXNwZQAAAAAAAAABAAAAAQAAABBwaXhpAAAAAAMICAgAAAAXaXBtYQAAAAAAAAABAAEEAYIDBAAAABptZGF0EgAKBzgABhAQ0GkyBRAAAAtA -- layouts/home.html -- {{ $a := resources.Get "a.png" }} {{ $a10 := $a.Fit "10x10" }} {{ $b := resources.Get "b.svg" }} {{ $c := resources.Get "c.txt" }} {{ $d := resources.Get "d.avif" }} PNG.ResourceType: {{ $a.ResourceType }} SVG.ResourceType: {{ $b.ResourceType }} Text.ResourceType: {{ $c.ResourceType }} AVIF.ResourceType: {{ $d.ResourceType }} IsSite: false: {{ reflect.IsSite . }}|true: {{ reflect.IsSite .Site }}|true: {{ reflect.IsSite site }} IsPage: true: {{ reflect.IsPage . }}|false: {{ reflect.IsPage .Site }}|false: {{ reflect.IsPage site }} IsResource: true: {{ reflect.IsResource . }}|true: {{ reflect.IsResource $a }}|true: {{ reflect.IsResource $b }}|true: {{ reflect.IsResource $c }} IsImageResource: false: {{ reflect.IsImageResource . }}|true: {{ reflect.IsImageResource $a }}|true: {{ reflect.IsImageResource $a10 }}|false: {{ reflect.IsImageResource $b }}|false: {{ reflect.IsImageResource $c }}|false: {{ reflect.IsImageResource $d }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` PNG.ResourceType: image SVG.ResourceType: image Text.ResourceType: text AVIF.ResourceType: image IsSite: false: false|true: true|true: true IsPage: true: true|false: false|false: false IsResource: true: true|true: true|true: true|true: true IsImageResource: false: false|true: true|true: true|false: false|false: false|false: false `) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/reflect/reflect.go
tpl/reflect/reflect.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 reflect import ( "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) // New returns a new instance of the reflect-namespaced template functions. func New() *Namespace { return &Namespace{} } // Namespace provides template functions for the "reflect" namespace. type Namespace struct{} // IsMap reports whether v is a map. func (ns *Namespace) IsMap(v any) bool { return hreflect.IsMap(v) } // IsSlice reports whether v is a slice. func (ns *Namespace) IsSlice(v any) bool { return hreflect.IsSlice(v) } // IsPage reports whether v is a Hugo Page. func (ns *Namespace) IsPage(v any) bool { _, ok := v.(page.Page) return ok } // IsResource reports whether v is a Hugo Resource. func (ns *Namespace) IsResource(v any) bool { _, ok := v.(resource.Resource) return ok } // IsSite reports whether v is a Hugo Site. func (ns *Namespace) IsSite(v any) bool { _, ok := v.(page.Site) return ok } // IsImageResource reports whether v is a Hugo Image Resource. // If this returns true, you may process it and get information about its width, height, etc. func (ns *Namespace) IsImageResource(v any) bool { return resources.IsImage(v) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/reflect/reflect_test.go
tpl/reflect/reflect_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package reflect import ( "testing" qt "github.com/frankban/quicktest" ) var ns = New() func TestIsMap(t *testing.T) { c := qt.New(t) for _, test := range []struct { v any expect any }{ {map[int]int{1: 1}, true}, {"foo", false}, {nil, false}, } { result := ns.IsMap(test.v) c.Assert(result, qt.Equals, test.expect) } } func TestIsSlice(t *testing.T) { c := qt.New(t) for _, test := range []struct { v any expect any }{ {[]int{1, 2}, true}, {"foo", false}, {nil, false}, } { result := ns.IsSlice(test.v) c.Assert(result, qt.Equals, test.expect) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/transform/init.go
tpl/transform/init.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 transform import ( "context" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const name = "transform" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New(d) ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.CanHighlight, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Emojify, []string{"emojify"}, [][2]string{ {`{{ "I :heart: Hugo" | emojify }}`, `I ❤️ Hugo`}, }, ) ns.AddMethodMapping(ctx.Highlight, []string{"highlight"}, [][2]string{}, ) ns.AddMethodMapping(ctx.HighlightCodeBlock, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.HTMLEscape, []string{"htmlEscape"}, [][2]string{ { `{{ htmlEscape "Cathal Garvey & The Sunshine Band <cathal@foo.bar>" | safeHTML }}`, `Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;`, }, { `{{ htmlEscape "Cathal Garvey & The Sunshine Band <cathal@foo.bar>" }}`, `Cathal Garvey &amp;amp; The Sunshine Band &amp;lt;cathal@foo.bar&amp;gt;`, }, { `{{ htmlEscape "Cathal Garvey & The Sunshine Band <cathal@foo.bar>" | htmlUnescape | safeHTML }}`, `Cathal Garvey & The Sunshine Band <cathal@foo.bar>`, }, }, ) ns.AddMethodMapping(ctx.HTMLToMarkdown, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.HTMLUnescape, []string{"htmlUnescape"}, [][2]string{ { `{{ htmlUnescape "Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;" | safeHTML }}`, `Cathal Garvey & The Sunshine Band <cathal@foo.bar>`, }, { `{{ "Cathal Garvey &amp;amp; The Sunshine Band &amp;lt;cathal@foo.bar&amp;gt;" | htmlUnescape | htmlUnescape | safeHTML }}`, `Cathal Garvey & The Sunshine Band <cathal@foo.bar>`, }, { `{{ "Cathal Garvey &amp;amp; The Sunshine Band &amp;lt;cathal@foo.bar&amp;gt;" | htmlUnescape | htmlUnescape }}`, `Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;`, }, { `{{ htmlUnescape "Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;" | htmlEscape | safeHTML }}`, `Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;`, }, }, ) ns.AddMethodMapping(ctx.Markdownify, []string{"markdownify"}, [][2]string{ {`{{ .Title | markdownify }}`, `<strong>BatMan</strong>`}, }, ) ns.AddMethodMapping(ctx.Plainify, []string{"plainify"}, [][2]string{ {`{{ plainify "Hello <strong>world</strong>, gophers!" }}`, `Hello world, gophers!`}, }, ) ns.AddMethodMapping(ctx.PortableText, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Remarshal, nil, [][2]string{ {`{{ "title = \"Hello World\"" | transform.Remarshal "json" | safeHTML }}`, "{\n \"title\": \"Hello World\"\n}\n"}, }, ) ns.AddMethodMapping(ctx.ToMath, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Unmarshal, []string{"unmarshal"}, [][2]string{ {`{{ "hello = \"Hello World\"" | transform.Unmarshal }}`, "map[hello:Hello World]"}, {`{{ "hello = \"Hello World\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }}`, "map[hello:Hello World]"}, }, ) ns.AddMethodMapping(ctx.XMLEscape, nil, [][2]string{ { `{{ transform.XMLEscape "<p>abc</p>" }}`, `&lt;p&gt;abc&lt;/p&gt;`, }, }, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/transform/remarshal_test.go
tpl/transform/remarshal_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package transform_test import ( "testing" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/tpl/transform" qt "github.com/frankban/quicktest" ) func TestRemarshal(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) c := qt.New(t) c.Run("Roundtrip variants", func(c *qt.C) { tomlExample := `title = 'Test Metadata' [[resources]] src = '**image-4.png' title = 'The Fourth Image!' [resources.params] byline = 'picasso' [[resources]] name = 'my-cool-image-:counter' src = '**.png' title = 'TOML: The Image #:counter' [resources.params] byline = 'bep' ` yamlExample := `resources: - params: byline: picasso src: '**image-4.png' title: The Fourth Image! - name: my-cool-image-:counter params: byline: bep src: '**.png' title: 'TOML: The Image #:counter' title: Test Metadata ` jsonExample := `{ "resources": [ { "params": { "byline": "picasso" }, "src": "**image-4.png", "title": "The Fourth Image!" }, { "name": "my-cool-image-:counter", "params": { "byline": "bep" }, "src": "**.png", "title": "TOML: The Image #:counter" } ], "title": "Test Metadata" } ` xmlExample := `<root> <resources> <params> <byline>picasso</byline> </params> <src>**image-4.png</src> <title>The Fourth Image!</title> </resources> <resources> <name>my-cool-image-:counter</name> <params> <byline>bep</byline> </params> <src>**.png</src> <title>TOML: The Image #:counter</title> </resources> <title>Test Metadata</title> </root> ` variants := []struct { format string data string }{ {"yaml", yamlExample}, {"json", jsonExample}, {"toml", tomlExample}, {"TOML", tomlExample}, {"Toml", tomlExample}, {" TOML ", tomlExample}, {"XML", xmlExample}, } for _, v1 := range variants { for _, v2 := range variants { // Both from and to may be the same here, but that is fine. fromTo := qt.Commentf("%s => %s", v2.format, v1.format) converted, err := ns.Remarshal(v1.format, v2.data) c.Assert(err, qt.IsNil, fromTo) diff := htesting.DiffStrings(v1.data, converted) if len(diff) > 0 { t.Errorf("[%s] Expected \n%v\ngot\n%v\ndiff:\n%v", fromTo, v1.data, converted, diff) } } } }) c.Run("Comments", func(c *qt.C) { input := ` Hugo = "Rules" # It really does! [m] # A comment a = "b" ` expected := `Hugo = 'Rules' [m] a = 'b' ` for _, format := range []string{"json", "yaml", "toml"} { fromTo := qt.Commentf("%s => %s", "toml", format) converted := input var err error // Do a round-trip conversion for _, toFormat := range []string{format, "toml"} { converted, err = ns.Remarshal(toFormat, converted) c.Assert(err, qt.IsNil, fromTo) } diff := htesting.DiffStrings(expected, converted) if len(diff) > 0 { t.Fatalf("[%s] Expected \n%v\ngot\n>>%v\ndiff:\n%v\n", fromTo, expected, converted, diff) } } }) // Issue 8850 c.Run("TOML Indent", func(c *qt.C) { input := ` [params] [params.variables] a = "b" ` converted, err := ns.Remarshal("toml", input) c.Assert(err, qt.IsNil) c.Assert(converted, qt.Equals, "[params]\n [params.variables]\n a = 'b'\n") }) c.Run("Map input", func(c *qt.C) { input := map[string]any{ "hello": "world", } output, err := ns.Remarshal("toml", input) c.Assert(err, qt.IsNil) c.Assert(output, qt.Equals, "hello = 'world'\n") }) c.Run("Error", func(c *qt.C) { _, err := ns.Remarshal("asdf", "asdf") c.Assert(err, qt.Not(qt.IsNil)) _, err = ns.Remarshal("json", "asdf") c.Assert(err, qt.Not(qt.IsNil)) }) } func TestRemarshaBillionLaughs(t *testing.T) { t.Parallel() yamlBillionLaughs := ` a: &a [_, _, _, _, _, _, _, _, _, _, _, _, _, _, _] b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a, *a] c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b, *b] d: &d [*c, *c, *c, *c, *c, *c, *c, *c, *c, *c] e: &e [*d, *d, *d, *d, *d, *d, *d, *d, *d, *d] f: &f [*e, *e, *e, *e, *e, *e, *e, *e, *e, *e] g: &g [*f, *f, *f, *f, *f, *f, *f, *f, *f, *f] h: &h [*g, *g, *g, *g, *g, *g, *g, *g, *g, *g] i: &i [*h, *h, *h, *h, *h, *h, *h, *h, *h, *h] ` yamlMillionLaughs := ` a: &a [_, _, _, _, _, _, _, _, _, _, _, _, _, _, _] b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a, *a] c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b, *b] d: &d [*c, *c, *c, *c, *c, *c, *c, *c, *c, *c] e: &e [*d, *d, *d, *d, *d, *d, *d, *d, *d, *d] f: &f [*e, *e, *e, *e, *e, *e, *e, *e, *e, *e] ` yamlTenThousandLaughs := ` a: &a [_, _, _, _, _, _, _, _, _, _, _, _, _, _, _] b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a, *a] c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b, *b] d: &d [*c, *c, *c, *c, *c, *c, *c, *c, *c, *c] ` yamlThousandLaughs := ` a: &a [_, _, _, _, _, _, _, _, _, _, _, _, _, _, _] b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a, *a] c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b, *b] ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) for _, test := range []struct { name string data string }{ {"10k", yamlTenThousandLaughs}, {"1M", yamlMillionLaughs}, {"1B", yamlBillionLaughs}, } { t.Run(test.name, func(t *testing.T) { t.Parallel() c := qt.New(t) _, err := ns.Remarshal("json", test.data) c.Assert(err, qt.Not(qt.IsNil)) }) } // Thousand laughs should be ok. // It produces about 29KB of JSON, // which is still a large output for such a large input, // but there may be use cases for this. _, err := ns.Remarshal("json", yamlThousandLaughs) c := qt.New(t) c.Assert(err, qt.IsNil) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/transform/unmarshal.go
tpl/transform/unmarshal.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 transform import ( "errors" "fmt" "io" "strings" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/types" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/cast" ) // Unmarshal unmarshals the data given, which can be either a string, json.RawMessage // or a Resource. Supported formats are JSON, TOML, YAML, and CSV. // You can optionally provide an options map as the first argument. func (ns *Namespace) Unmarshal(args ...any) (any, error) { if len(args) < 1 || len(args) > 2 { return nil, errors.New("unmarshal takes 1 or 2 arguments") } var data any decoder := metadecoders.Default if len(args) == 1 { data = args[0] } else { m, ok := args[0].(map[string]any) if !ok { return nil, errors.New("first argument must be a map") } var err error data = args[1] decoder, err = decodeDecoder(m) if err != nil { return nil, fmt.Errorf("failed to decode options: %w", err) } } if r, ok := data.(resource.UnmarshableResource); ok { key := r.Key() if key == "" { return nil, errors.New("no Key set in Resource") } if decoder != metadecoders.Default { key += decoder.OptionsKey() } v, err := ns.cacheUnmarshal.GetOrCreate(key, func(string) (*resources.StaleValue[any], error) { var f metadecoders.Format if decoder.Format != "" { f = metadecoders.FormatFromString(decoder.Format) if f == "" { return nil, fmt.Errorf("format %q not supported", decoder.Format) } } else { f = metadecoders.FormatFromStrings(r.MediaType().Suffixes()...) if f == "" { return nil, fmt.Errorf("MIME %q not supported", r.MediaType()) } } reader, err := r.ReadSeekCloser() if err != nil { return nil, err } defer reader.Close() b, err := io.ReadAll(reader) if err != nil { return nil, err } v, err := decoder.Unmarshal(b, f) if err != nil { return nil, err } return &resources.StaleValue[any]{ Value: v, StaleVersionFunc: func() uint32 { return resource.StaleVersion(r) }, }, nil }) if err != nil { return nil, err } return v.Value, nil } dataStr, err := types.ToStringE(data) if err != nil { return nil, fmt.Errorf("type %T not supported", data) } if strings.TrimSpace(dataStr) == "" { return nil, nil } key := hashing.MD5FromStringHexEncoded(dataStr) if decoder != metadecoders.Default { key += decoder.OptionsKey() } v, err := ns.cacheUnmarshal.GetOrCreate(key, func(string) (*resources.StaleValue[any], error) { var f metadecoders.Format if decoder.Format != "" { f = metadecoders.FormatFromString(decoder.Format) if f == "" { return nil, fmt.Errorf("format %q not supported", decoder.Format) } } else { f = decoder.FormatFromContentString(dataStr) if f == "" { return nil, errors.New("unknown format") } } v, err := decoder.Unmarshal([]byte(dataStr), f) if err != nil { return nil, err } return &resources.StaleValue[any]{ Value: v, StaleVersionFunc: func() uint32 { return 0 }, }, nil }) if err != nil { return nil, err } return v.Value, nil } func decodeDecoder(m map[string]any) (metadecoders.Decoder, error) { opts := metadecoders.Default if m == nil { return opts, nil } // mapstructure does not support string to rune conversion, so do that manually. // See https://github.com/mitchellh/mapstructure/issues/151 for k, v := range m { if strings.EqualFold(k, "Delimiter") { r, err := stringToRune(v) if err != nil { return opts, err } opts.Delimiter = r delete(m, k) } else if strings.EqualFold(k, "Comment") { r, err := stringToRune(v) if err != nil { return opts, err } opts.Comment = r delete(m, k) } } err := mapstructure.WeakDecode(m, &opts) return opts, err } func stringToRune(v any) (rune, error) { s, err := cast.ToStringE(v) if err != nil { return 0, err } if len(s) == 0 { return 0, nil } var r rune for i, rr := range s { if i == 0 { r = rr } else { return 0, fmt.Errorf("invalid character: %q", v) } } return r, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/transform/transform_test.go
tpl/transform/transform_test.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 transform_test import ( "context" "html/template" "strings" "testing" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/tpl/transform" qt "github.com/frankban/quicktest" ) type tstNoStringer struct{} func TestEmojify(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) for _, test := range []struct { s any expect any }{ {":notamoji:", template.HTML(":notamoji:")}, {"I :heart: Hugo", template.HTML("I ❤️ Hugo")}, // errors {tstNoStringer{}, false}, } { result, err := ns.Emojify(test.s) if bb, ok := test.expect.(bool); ok && !bb { b.Assert(err, qt.Not(qt.IsNil)) continue } b.Assert(err, qt.IsNil) b.Assert(result, qt.Equals, test.expect) } } func TestHighlight(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) for _, test := range []struct { s any lang string opts any expect any }{ {"func boo() {}", "go", "", "boo"}, {"func boo() {}", "go", nil, "boo"}, // Issue #4179 {`<Foo attr=" &lt; "></Foo>`, "xml", "", `&amp;lt;`}, {tstNoStringer{}, "go", "", false}, // Issue #9591 {strings.Repeat("AAA \n", 10), "bash", template.HTML("linenos=true,noClasses=false"), "line"}, } { result, err := ns.Highlight(test.s, test.lang, test.opts) if bb, ok := test.expect.(bool); ok && !bb { b.Assert(err, qt.Not(qt.IsNil)) continue } b.Assert(err, qt.IsNil) b.Assert(string(result), qt.Contains, test.expect.(string)) } } func TestCanHighlight(t *testing.T) { t.Parallel() c := qt.New(t) ns := &transform.Namespace{} c.Assert(ns.CanHighlight("go"), qt.Equals, true) c.Assert(ns.CanHighlight("foo"), qt.Equals, false) } func TestHTMLEscape(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) for _, test := range []struct { s any expect any }{ {`"Foo & Bar's Diner" <y@z>`, `&#34;Foo &amp; Bar&#39;s Diner&#34; &lt;y@z&gt;`}, {"Hugo & Caddy > Wordpress & Apache", "Hugo &amp; Caddy &gt; Wordpress &amp; Apache"}, // errors {tstNoStringer{}, false}, } { result, err := ns.HTMLEscape(test.s) if bb, ok := test.expect.(bool); ok && !bb { b.Assert(err, qt.Not(qt.IsNil)) continue } b.Assert(err, qt.IsNil) b.Assert(result, qt.Equals, test.expect) } } func TestHTMLUnescape(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) for _, test := range []struct { s any expect any }{ {`&quot;Foo &amp; Bar&#39;s Diner&quot; &lt;y@z&gt;`, `"Foo & Bar's Diner" <y@z>`}, {"Hugo &amp; Caddy &gt; Wordpress &amp; Apache", "Hugo & Caddy > Wordpress & Apache"}, // errors {tstNoStringer{}, false}, } { result, err := ns.HTMLUnescape(test.s) if bb, ok := test.expect.(bool); ok && !bb { b.Assert(err, qt.Not(qt.IsNil)) continue } b.Assert(err, qt.IsNil) b.Assert(result, qt.Equals, test.expect) } } func TestMarkdownify(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) for _, test := range []struct { s any expect any }{ {"Hello **World!**", template.HTML("Hello <strong>World!</strong>")}, {[]byte("Hello Bytes **World!**"), template.HTML("Hello Bytes <strong>World!</strong>")}, {tstNoStringer{}, false}, } { result, err := ns.Markdownify(context.Background(), test.s) if bb, ok := test.expect.(bool); ok && !bb { b.Assert(err, qt.Not(qt.IsNil)) continue } b.Assert(err, qt.IsNil) b.Assert(result, qt.Equals, test.expect) } } // Issue #3040 func TestMarkdownifyBlocksOfText(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) text := ` #First This is some *bold* text. ## Second This is some more text. And then some. ` result, err := ns.Markdownify(context.Background(), text) b.Assert(err, qt.IsNil) b.Assert(result, qt.Equals, template.HTML( "<p>#First</p>\n<p>This is some <em>bold</em> text.</p>\n<h2 id=\"second\">Second</h2>\n<p>This is some more text.</p>\n<p>And then some.</p>\n")) } func TestPlainify(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) for _, test := range []struct { s any expect any }{ {"<em>Note:</em> blah <b>blah</b>", "Note: blah blah"}, {"<div data-action='click->my-controller#doThing'>qwe</div>", "qwe"}, // errors {tstNoStringer{}, false}, } { result, err := ns.Plainify(test.s) if bb, ok := test.expect.(bool); ok && !bb { b.Assert(err, qt.Not(qt.IsNil)) continue } b.Assert(err, qt.IsNil) b.Assert(result, qt.Equals, template.HTML(test.expect.(string))) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/transform/remarshal.go
tpl/transform/remarshal.go
package transform import ( "bytes" "errors" "strings" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/cast" ) // Remarshal is used in the Hugo documentation to convert configuration // examples from YAML to JSON, TOML (and possibly the other way around). // The is primarily a helper for the Hugo docs site. // It is not a general purpose YAML to TOML converter etc., and may // change without notice if it serves a purpose in the docs. // Format is one of json, yaml or toml. func (ns *Namespace) Remarshal(format string, data any) (string, error) { var meta map[string]any format = strings.TrimSpace(strings.ToLower(format)) mark, err := toFormatMark(format) if err != nil { return "", err } if m, ok := data.(map[string]any); ok { meta = m } else { from, err := cast.ToStringE(data) if err != nil { return "", err } from = strings.TrimSpace(from) if from == "" { return "", nil } fromFormat := metadecoders.Default.FormatFromContentString(from) if fromFormat == "" { return "", errors.New("failed to detect format from content") } meta, err = metadecoders.Default.UnmarshalToMap([]byte(from), fromFormat) if err != nil { return "", err } } // Make it so 1.0 float64 prints as 1 etc. applyMarshalTypes(meta) var result bytes.Buffer if err := parser.InterfaceToConfig(meta, mark, &result); err != nil { return "", err } return result.String(), nil } // The unmarshal/marshal dance is extremely type lossy, and we need // to make sure that integer types prints as "43" and not "43.0" in // all formats, hence this hack. func applyMarshalTypes(m map[string]any) { for k, v := range m { switch t := v.(type) { case map[string]any: applyMarshalTypes(t) case float64: i := int64(t) if t == float64(i) { m[k] = i } } } } func toFormatMark(format string) (metadecoders.Format, error) { if f := metadecoders.FormatFromString(format); f != "" { return f, nil } return "", errors.New("failed to detect target data serialization format") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/transform/transform.go
tpl/transform/transform.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 transform provides template functions for transforming content. package transform import ( "bytes" "context" "encoding/json" "encoding/xml" "errors" "fmt" "html" "html/template" "io" "strings" "sync/atomic" htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2/converter" "github.com/JohannesKaufmann/html-to-markdown/v2/plugin/base" "github.com/JohannesKaufmann/html-to-markdown/v2/plugin/commonmark" "github.com/JohannesKaufmann/html-to-markdown/v2/plugin/table" bp "github.com/gohugoio/hugo/bufferpool" "github.com/bep/goportabletext" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/internal/warpc" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/highlight/chromalexers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/tpl" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/helpers" "github.com/spf13/cast" ) // New returns a new instance of the transform-namespaced template functions. func New(deps *deps.Deps) *Namespace { if deps.MemCache == nil { panic("must provide MemCache") } return &Namespace{ deps: deps, cacheUnmarshal: dynacache.GetOrCreatePartition[string, *resources.StaleValue[any]]( deps.MemCache, "/tmpl/transform/unmarshal", dynacache.OptionsPartition{Weight: 30, ClearWhen: dynacache.ClearOnChange}, ), cacheMath: dynacache.GetOrCreatePartition[string, template.HTML]( deps.MemCache, "/tmpl/transform/math", dynacache.OptionsPartition{Weight: 30, ClearWhen: dynacache.ClearNever}, ), } } // Namespace provides template functions for the "transform" namespace. type Namespace struct { cacheUnmarshal *dynacache.Partition[string, *resources.StaleValue[any]] cacheMath *dynacache.Partition[string, template.HTML] id atomic.Uint32 deps *deps.Deps } // Emojify returns a copy of s with all emoji codes replaced with actual emojis. // // See http://www.emoji-cheat-sheet.com/ func (ns *Namespace) Emojify(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return template.HTML(helpers.Emojify([]byte(ss))), nil } // Highlight returns a copy of s as an HTML string with syntax // highlighting applied. func (ns *Namespace) Highlight(s any, lang string, opts ...any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } var optsv any if len(opts) > 0 { optsv = opts[0] } hl := ns.deps.ContentSpec.Converters.GetHighlighter() highlighted, err := hl.Highlight(ss, lang, optsv) if err != nil { return "", err } return template.HTML(highlighted), nil } // HighlightCodeBlock highlights a code block on the form received in the codeblock render hooks. func (ns *Namespace) HighlightCodeBlock(ctx hooks.CodeblockContext, opts ...any) (highlight.HighlightResult, error) { var optsv any if len(opts) > 0 { optsv = opts[0] } hl := ns.deps.ContentSpec.Converters.GetHighlighter() return hl.HighlightCodeBlock(ctx, optsv) } // CanHighlight returns whether the given code language is supported by the Chroma highlighter. func (ns *Namespace) CanHighlight(language string) bool { return chromalexers.Get(language) != nil } // HTMLEscape returns a copy of s with reserved HTML characters escaped. func (ns *Namespace) HTMLEscape(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return html.EscapeString(ss), nil } // HTMLUnescape returns a copy of s with HTML escape requences converted to plain // text. func (ns *Namespace) HTMLUnescape(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return html.UnescapeString(ss), nil } // XMLEscape returns the given string, removing disallowed characters then // escaping the result to its XML equivalent. func (ns *Namespace) XMLEscape(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } // https://www.w3.org/TR/xml/#NT-Char cleaned := strings.Map(func(r rune) rune { if r == 0x9 || r == 0xA || r == 0xD || (r >= 0x20 && r <= 0xD7FF) || (r >= 0xE000 && r <= 0xFFFD) || (r >= 0x10000 && r <= 0x10FFFF) { return r } return -1 }, ss) var buf bytes.Buffer err = xml.EscapeText(&buf, []byte(cleaned)) if err != nil { return "", err } return buf.String(), nil } // Markdownify renders s from Markdown to HTML. func (ns *Namespace) Markdownify(ctx context.Context, s any) (template.HTML, error) { home := ns.deps.Site.Home() if home == nil { panic("home must not be nil") } ss, err := home.RenderString(ctx, s) if err != nil { return "", err } // Strip if this is a short inline type of text. bb := ns.deps.ContentSpec.TrimShortHTML([]byte(ss), "markdown") return helpers.BytesToHTML(bb), nil } // Plainify returns a copy of s with all HTML tags removed. func (ns *Namespace) Plainify(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return template.HTML(tpl.StripHTML(ss)), nil } // PortableText converts the portable text in v to Markdown. // We may add more options in the future. func (ns *Namespace) PortableText(v any) (string, error) { buf := bp.GetBuffer() defer bp.PutBuffer(buf) opts := goportabletext.ToMarkdownOptions{ Dst: buf, Src: v, } if err := goportabletext.ToMarkdown(opts); err != nil { return "", err } return buf.String(), nil } // ToMath converts a LaTeX string to math in the given format, default MathML. // This uses KaTeX to render the math, see https://katex.org/. func (ns *Namespace) ToMath(ctx context.Context, args ...any) (template.HTML, error) { if len(args) < 1 { return "", errors.New("must provide at least one argument") } expression, err := cast.ToStringE(args[0]) if err != nil { return "", err } katexInput := warpc.KatexInput{ Expression: expression, Options: warpc.KatexOptions{ Output: "mathml", MinRuleThickness: 0.04, ErrorColor: "#cc0000", ThrowOnError: true, Strict: "error", }, } if len(args) > 1 { if err := mapstructure.WeakDecode(args[1], &katexInput.Options); err != nil { return "", err } } switch katexInput.Options.Strict { case "error", "ignore", "warn": // Valid strict mode, continue default: return "", fmt.Errorf("invalid strict mode; expected one of error, ignore, or warn; received %s", katexInput.Options.Strict) } type fileCacheEntry struct { Version string `json:"version"` Output string `json:"output"` Warnings []string `json:"warnings,omitempty"` } const fileCacheEntryVersion = "v1" // Increment on incompatible changes. s := hashing.HashString(args...) key := "tomath/" + fileCacheEntryVersion + "/" + s[:2] + "/" + s[2:] fileCache := ns.deps.ResourceSpec.FileCaches.MiscCache() v, err := ns.cacheMath.GetOrCreate(key, func(string) (template.HTML, error) { _, r, err := fileCache.GetOrCreate(key, func() (io.ReadCloser, error) { message := warpc.Message[warpc.KatexInput]{ Header: warpc.Header{ Version: 1, ID: ns.id.Add(1), }, Data: katexInput, } k, err := ns.deps.WasmDispatchers.Katex() if err != nil { return nil, err } result, err := k.Execute(ctx, message) if err != nil { return nil, err } e := fileCacheEntry{ Version: fileCacheEntryVersion, Output: result.Data.Output, Warnings: result.Header.Warnings, } buf := &bytes.Buffer{} enc := json.NewEncoder(buf) enc.SetEscapeHTML(false) if err := enc.Encode(e); err != nil { return nil, fmt.Errorf("failed to encode file cache entry: %w", err) } return hugio.NewReadSeekerNoOpCloserFromBytes(buf.Bytes()), nil }) if err != nil { return "", err } var e fileCacheEntry if err := json.NewDecoder(r).Decode(&e); err != nil { return "", fmt.Errorf("failed to decode file cache entry: %w", err) } for _, warning := range e.Warnings { ns.deps.Log.Warnf("transform.ToMath: %s", warning) } return template.HTML(e.Output), err }) if err != nil { return "", err } return v, nil } // For internal use. func (ns *Namespace) Reset() { ns.cacheUnmarshal.Clear() } // This was added in Hugo v0.151.0 and should be considered experimental for now. // We need to test this out in the wild for a while before committing to this API, // and there will eventually be more options here. func (ns *Namespace) HTMLToMarkdown(ctx context.Context, args ...any) (string, error) { if len(args) < 1 { return "", errors.New("must provide at least one argument") } input, err := cast.ToStringE(args[0]) if err != nil { return "", err } plugins := []htmltomarkdown.Plugin{ base.NewBasePlugin(), commonmark.NewCommonmarkPlugin(), table.NewTablePlugin(), } conv := htmltomarkdown.NewConverter( htmltomarkdown.WithPlugins(plugins...), ) markdown, err := conv.ConvertString(input) if err != nil { return "", err } return markdown, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/transform/unmarshal_test.go
tpl/transform/unmarshal_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 transform_test import ( "context" "fmt" "math/rand" "strings" "testing" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/tpl/transform" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/media" qt "github.com/frankban/quicktest" ) const ( testJSON = ` { "ROOT_KEY": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } } ` ) var _ resource.ReadSeekCloserResource = (*testContentResource)(nil) type testContentResource struct { content string mime media.Type key string } func (t testContentResource) ReadSeekCloser() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(t.content), nil } func (t testContentResource) MediaType() media.Type { return t.mime } func (t testContentResource) Key() string { return t.key } func TestUnmarshal(t *testing.T) { b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t}, ).Build() ns := transform.New(b.H.Deps) assertSlogan := func(m map[string]any) { b.Assert(m["slogan"], qt.Equals, "Hugo Rocks!") } for _, test := range []struct { data any options any expect any }{ {`{ "slogan": "Hugo Rocks!" }`, nil, func(m map[string]any) { assertSlogan(m) }}, {`slogan: "Hugo Rocks!"`, nil, func(m map[string]any) { assertSlogan(m) }}, {`slogan = "Hugo Rocks!"`, nil, func(m map[string]any) { assertSlogan(m) }}, {testContentResource{key: "r1", content: `slogan: "Hugo Rocks!"`, mime: media.Builtin.YAMLType}, nil, func(m map[string]any) { assertSlogan(m) }}, {testContentResource{key: "r1", content: `{ "slogan": "Hugo Rocks!" }`, mime: media.Builtin.JSONType}, nil, func(m map[string]any) { assertSlogan(m) }}, {testContentResource{key: "r1", content: `slogan = "Hugo Rocks!"`, mime: media.Builtin.TOMLType}, nil, func(m map[string]any) { assertSlogan(m) }}, {testContentResource{key: "r1", content: `<root><slogan>Hugo Rocks!</slogan></root>"`, mime: media.Builtin.XMLType}, nil, func(m map[string]any) { assertSlogan(m) }}, {testContentResource{key: "r1", content: `1997,Ford,E350,"ac, abs, moon",3000.00 1999,Chevy,"Venture ""Extended Edition""","",4900.00`, mime: media.Builtin.CSVType}, nil, func(r [][]string) { b.Assert(len(r), qt.Equals, 2) first := r[0] b.Assert(len(first), qt.Equals, 5) b.Assert(first[1], qt.Equals, "Ford") }}, {testContentResource{key: "r1", content: `a;b;c`, mime: media.Builtin.CSVType}, map[string]any{"delimiter": ";"}, func(r [][]string) { b.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) }}, {testContentResource{key: "r1", content: `{p: [a, b]}`, mime: media.Builtin.JSONType}, map[string]any{"format": "yaml"}, func(m map[string]any) { b.Assert(m, qt.DeepEquals, map[string]any{"p": []any{"a", "b"}}) }}, {"a,b,c", nil, func(r [][]string) { b.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) }}, {"a;b;c", map[string]any{"delimiter": ";"}, func(r [][]string) { b.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) }}, {testContentResource{key: "r1", content: ` % This is a comment a;b;c`, mime: media.Builtin.CSVType}, map[string]any{"DElimiter": ";", "Comment": "%"}, func(r [][]string) { b.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) }}, {``, nil, nil}, {` `, nil, nil}, {`{p: [a, b]}`, map[string]any{"format": "yaml"}, func(m map[string]any) { b.Assert(m, qt.DeepEquals, map[string]any{"p": []any{"a", "b"}}) }}, // errors {"thisisnotavaliddataformat", nil, false}, {testContentResource{key: "r1", content: `invalid&toml"`, mime: media.Builtin.TOMLType}, nil, false}, {testContentResource{key: "r1", content: `unsupported: MIME"`, mime: media.Builtin.CalendarType}, nil, false}, {"thisisnotavaliddataformat", nil, false}, {`{ notjson }`, nil, false}, {tstNoStringer{}, nil, false}, {"<root><a>notjson</a></root>", map[string]any{"format": "json"}, false}, {"anything", map[string]any{"format": "invalidformat"}, false}, } { ns.Reset() var args []any if test.options != nil { args = []any{test.options, test.data} } else { args = []any{test.data} } result, err := ns.Unmarshal(args...) if bb, ok := test.expect.(bool); ok && !bb { b.Assert(err, qt.Not(qt.IsNil)) } else if fn, ok := test.expect.(func(m map[string]any)); ok { b.Assert(err, qt.IsNil) m, ok := result.(map[string]any) b.Assert(ok, qt.Equals, true) fn(m) } else if fn, ok := test.expect.(func(r [][]string)); ok { b.Assert(err, qt.IsNil) r, ok := result.([][]string) b.Assert(ok, qt.Equals, true) fn(r) } else { b.Assert(err, qt.IsNil) b.Assert(result, qt.Equals, test.expect) } } } func BenchmarkUnmarshalString(b *testing.B) { bb := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: b}, ).Build() ns := transform.New(bb.H.Deps) const numJsons = 100 var jsons [numJsons]string for i := range numJsons { jsons[i] = strings.Replace(testJSON, "ROOT_KEY", fmt.Sprintf("root%d", i), 1) } ctx := context.Background() for b.Loop() { result, err := ns.Unmarshal(ctx, jsons[rand.Intn(numJsons)]) if err != nil { b.Fatal(err) } if result == nil { b.Fatal("no result") } } } func BenchmarkUnmarshalResource(b *testing.B) { bb := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: b}, ).Build() ns := transform.New(bb.H.Deps) const numJsons = 100 var jsons [numJsons]testContentResource for i := range numJsons { key := fmt.Sprintf("root%d", i) jsons[i] = testContentResource{key: key, content: strings.Replace(testJSON, "ROOT_KEY", key, 1), mime: media.Builtin.JSONType} } ctx := context.Background() for b.Loop() { result, err := ns.Unmarshal(ctx, jsons[rand.Intn(numJsons)]) if err != nil { b.Fatal(err) } if result == nil { b.Fatal("no result") } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/transform/transform_integration_test.go
tpl/transform/transform_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package transform_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue #11698 func TestMarkdownifyIssue11698(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','section','rss','sitemap','taxonomy','term'] [markup.goldmark.parser.attribute] title = true block = true -- layouts/single.html -- _{{ markdownify .RawContent }}_ -- content/p1.md -- --- title: p1 --- foo bar -- content/p2.md -- --- title: p2 --- foo **bar** -- content/p3.md -- --- title: p3 --- ## foo bar -- content/p4.md -- --- title: p4 --- foo {#bar} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "_foo bar_") b.AssertFileContent("public/p2/index.html", "_<p>foo</p>\n<p><strong>bar</strong></p>\n_") b.AssertFileContent("public/p3/index.html", "_<h2 id=\"foo\">foo</h2>\n<p>bar</p>\n_") b.AssertFileContent("public/p4/index.html", "_<p id=\"bar\">foo</p>\n_") } func TestXMLEscape(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['section','sitemap','taxonomy','term'] -- content/p1.md -- --- title: p1 --- a **b** ` + "\v" + ` c <!--more--> ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.xml", ` <description>&lt;p&gt;a &lt;strong&gt;b&lt;/strong&gt; c&lt;/p&gt;</description> `) } // Issue #9642 func TestHighlightError(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ highlight "a" "b" 0 }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ) _, err := b.BuildE() b.Assert(err.Error(), qt.Contains, "error calling highlight: invalid Highlight option: 0") } // Issue #11884 func TestUnmarshalCSVLazyDecoding(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- assets/pets.csv -- name,description,age Spot,a nice dog,3 Rover,"a big dog",5 Felix,a "malicious" cat,7 Bella,"an "evil" cat",9 Scar,"a "dead cat",11 -- layouts/home.html -- {{ $opts := dict "lazyQuotes" true }} {{ $data := resources.Get "pets.csv" | transform.Unmarshal $opts }} {{ printf "%v" $data | safeHTML }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` [[name description age] [Spot a nice dog 3] [Rover a big dog 5] [Felix a "malicious" cat 7] [Bella an "evil" cat 9] [Scar a "dead cat 11]] `) } func TestToMath(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` <span class="katex"><math `) } func TestToMathError(t *testing.T) { t.Run("Default", func(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ transform.ToMath "c = \\foo{a^2 + b^2}" }} ` b, err := hugolib.TestE(t, files, hugolib.TestOptWarn()) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "KaTeX parse error: Undefined control sequence: \\foo") }) t.Run("Disable ThrowOnError", func(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ $opts := dict "throwOnError" false }} {{ transform.ToMath "c = \\foo{a^2 + b^2}" $opts }} ` b, err := hugolib.TestE(t, files, hugolib.TestOptWarn()) b.Assert(err, qt.IsNil) b.AssertFileContent("public/index.html", `#cc0000`) // Error color }) t.Run("Handle in template", func(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ with try (transform.ToMath "c = \\foo{a^2 + b^2}") }} {{ with .Err }} {{ warnf "error: %s" . }} {{ else }} {{ .Value }} {{ end }} {{ end }} ` b, err := hugolib.TestE(t, files, hugolib.TestOptWarn()) b.Assert(err, qt.IsNil) b.AssertLogContains("WARN error: template: home.html:1:22: executing \"home.html\" at <transform.ToMath>: error calling ToMath: KaTeX parse error: Undefined control sequence: \\foo at position 5: c = \\̲f̲o̲o̲{a^2 + b^2}") }) // See issue 13239. t.Run("Handle in template, old Err construct", func(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ with transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" }} {{ with .Err }} {{ warnf "error: %s" . }} {{ else }} {{ . }} {{ end }} {{ end }} ` b, err := hugolib.TestE(t, files, hugolib.TestOptWarn()) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "the return type of transform.ToMath was changed in Hugo v0.141.0 and the error handling replaced with a new try keyword, see https://gohugo.io/functions/go-template/try/") }) } func TestToMathBigAndManyExpressions(t *testing.T) { filesTemplate := ` -- hugo.toml -- disableKinds = ['rss','section','sitemap','taxonomy','term'] [markup.goldmark.extensions.passthrough] enable = true [markup.goldmark.extensions.passthrough.delimiters] block = [['\[', '\]'], ['$$', '$$']] inline = [['\(', '\)'], ['$', '$']] -- content/p1.md -- P1_CONTENT -- layouts/home.html -- Home. -- layouts/single.html -- Content: {{ .Content }}| -- layouts/_markup/render-passthrough.html -- {{ $opts := dict "throwOnError" false "displayMode" true }} {{ transform.ToMath .Inner $opts }} ` t.Run("Very large file with many complex KaTeX expressions", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "P1_CONTENT", "sourcefilename: testdata/large-katex.md") b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` <span class="katex"><math `) }) t.Run("Large and complex expression", func(t *testing.T) { // This is pulled from the file above, which times out for some reason. largeAndComplexeExpressions := `\begin{align*} \frac{\pi^2}{6}&=\frac{4}{3}\frac{(\arcsin 1)^2}{2}\\ &=\frac{4}{3}\int_0^1\frac{\arcsin x}{\sqrt{1-x^2}}\,dx\\ &=\frac{4}{3}\int_0^1\frac{x+\sum_{n=1}^{\infty}\frac{(2n-1)!!}{(2n)!!}\frac{x^{2n+1}}{2n+1}}{\sqrt{1-x^2}}\,dx\\ &=\frac{4}{3}\int_0^1\frac{x}{\sqrt{1-x^2}}\,dx +\frac{4}{3}\sum_{n=1}^{\infty}\frac{(2n-1)!!}{(2n)!!(2n+1)}\int_0^1x^{2n}\frac{x}{\sqrt{1-x^2}}\,dx\\ &=\frac{4}{3}+\frac{4}{3}\sum_{n=1}^{\infty}\frac{(2n-1)!!}{(2n)!!(2n+1)}\left[\frac{(2n)!!}{(2n+1)!!}\right]\\ &=\frac{4}{3}\sum_{n=0}^{\infty}\frac{1}{(2n+1)^2}\\ &=\frac{4}{3}\left(\sum_{n=1}^{\infty}\frac{1}{n^2}-\frac{1}{4}\sum_{n=1}^{\infty}\frac{1}{n^2}\right)\\ &=\sum_{n=1}^{\infty}\frac{1}{n^2} \end{align*}` files := strings.ReplaceAll(filesTemplate, "P1_CONTENT", fmt.Sprintf(`--- title: p1 --- $$%s$$ `, largeAndComplexeExpressions)) b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` <span class="katex"><math `) }) } // Issue #13406. func TestToMathRenderHookPosition(t *testing.T) { filesTemplate := ` -- hugo.toml -- disableKinds = ['rss','section','sitemap','taxonomy','term'] [markup.goldmark.extensions.passthrough] enable = true [markup.goldmark.extensions.passthrough.delimiters] block = [['\[', '\]'], ['$$', '$$']] inline = [['\(', '\)'], ['$', '$']] -- content/p1.md -- --- title: p1 --- Block: $$1+2$$ Some inline $1+3$ math. -- layouts/home.html -- Home. -- layouts/single.html -- Content: {{ .Content }}| -- layouts/_markup/render-passthrough.html -- {{ $opts := dict "throwOnError" true "displayMode" true }} {{- with try (transform.ToMath .Inner $opts ) }} {{- with .Err }} {{ errorf "KaTeX: %s: see %s." . $.Position }} {{- else }} {{- .Value }} {{- end }} {{- end -}} ` // Block math. files := strings.Replace(filesTemplate, "$$1+2$$", "$$\\foo1+2$$", 1) b, err := hugolib.TestE(t, files) b.Assert(err, qt.IsNotNil) b.AssertLogContains("p1.md:6:1") // Inline math. files = strings.Replace(filesTemplate, "$1+3$", "$\\foo1+3$", 1) b, err = hugolib.TestE(t, files) b.Assert(err, qt.IsNotNil) b.AssertLogContains("p1.md:8:13") } func TestToMathMacros(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ $macros := dict "\\addBar" "\\bar{#1}" "\\bold" "\\mathbf{#1}" }} {{ $opts := dict "macros" $macros }} {{ transform.ToMath "\\addBar{y} + \\bold{H}" $opts }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` <mi>y</mi> `) } // Issue #12977 func TestUnmarshalWithIndentedYAML(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ $yaml := "\n a:\n b: 1\n c:\n d: 2\n" }} {{ $yaml | transform.Unmarshal | encoding.Jsonify }} ` b := hugolib.Test(t, files) b.AssertFileExists("public/index.html", true) b.AssertFileContent("public/index.html", `{"a":{"b":1},"c":{"d":2}}`) } func TestPortableText(t *testing.T) { files := ` -- hugo.toml -- -- assets/sample.json -- [ { "_key": "a", "_type": "block", "children": [ { "_key": "b", "_type": "span", "marks": [], "text": "Heading 2" } ], "markDefs": [], "style": "h2" } ] -- layouts/home.html -- {{ $markdown := resources.Get "sample.json" | transform.Unmarshal | transform.PortableText }} Markdown: {{ $markdown }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "Markdown: ## Heading 2\n|") } func TestUnmarshalCSV(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/all.html -- {{ $opts := OPTS }} {{ with resources.Get "pets.csv" | transform.Unmarshal $opts }} {{ jsonify . }} {{ end }} -- assets/pets.csv -- DATA ` // targetType = map f := strings.ReplaceAll(files, "OPTS", `dict "targetType" "map"`) f = strings.ReplaceAll(f, "DATA", "name,type,breed,age\nSpot,dog,Collie,3\nFelix,cat,Malicious,7", ) b := hugolib.Test(t, f) b.AssertFileContent("public/index.html", `[{"age":"3","breed":"Collie","name":"Spot","type":"dog"},{"age":"7","breed":"Malicious","name":"Felix","type":"cat"}]`, ) // targetType = map (no data) f = strings.ReplaceAll(files, "OPTS", `dict "targetType" "map"`) f = strings.ReplaceAll(f, "DATA", "") b = hugolib.Test(t, f) b.AssertFileContent("public/index.html", "") // targetType = slice f = strings.ReplaceAll(files, "OPTS", `dict "targetType" "slice"`) f = strings.ReplaceAll(f, "DATA", "name,type,breed,age\nSpot,dog,Collie,3\nFelix,cat,Malicious,7", ) b = hugolib.Test(t, f) b.AssertFileContent("public/index.html", `[["name","type","breed","age"],["Spot","dog","Collie","3"],["Felix","cat","Malicious","7"]]`, ) // targetType = slice (no data) f = strings.ReplaceAll(files, "OPTS", `dict "targetType" "slice"`) f = strings.ReplaceAll(f, "DATA", "") b = hugolib.Test(t, f) b.AssertFileContent("public/index.html", "") // targetType not specified f = strings.ReplaceAll(files, "OPTS", "dict") f = strings.ReplaceAll(f, "DATA", "name,type,breed,age\nSpot,dog,Collie,3\nFelix,cat,Malicious,7", ) b = hugolib.Test(t, f) b.AssertFileContent("public/index.html", `[["name","type","breed","age"],["Spot","dog","Collie","3"],["Felix","cat","Malicious","7"]]`, ) // targetType not specified (no data) f = strings.ReplaceAll(files, "OPTS", "dict") f = strings.ReplaceAll(f, "DATA", "") b = hugolib.Test(t, f) b.AssertFileContent("public/index.html", "") // targetType = foo f = strings.ReplaceAll(files, "OPTS", `dict "targetType" "foo"`) _, err := hugolib.TestE(t, f) if err == nil { t.Errorf("expected error") } else { if !strings.Contains(err.Error(), `invalid targetType: expected either slice or map, received foo`) { t.Log(err.Error()) t.Errorf("error message does not match expected error message") } } // targetType = foo (no data) f = strings.ReplaceAll(files, "OPTS", `dict "targetType" "foo"`) f = strings.ReplaceAll(f, "DATA", "") _, err = hugolib.TestE(t, f) if err == nil { t.Errorf("expected error") } else { if !strings.Contains(err.Error(), `invalid targetType: expected either slice or map, received foo`) { t.Log(err.Error()) t.Errorf("error message does not match expected error message") } } // targetType = map (error: expected at least a header row and one data row) f = strings.ReplaceAll(files, "OPTS", `dict "targetType" "map"`) _, err = hugolib.TestE(t, f) if err == nil { t.Errorf("expected error") } else { if !strings.Contains(err.Error(), `expected at least a header row and one data row`) { t.Log(err.Error()) t.Errorf("error message does not match expected error message") } } // targetType = map (error: header row contains duplicate field names) f = strings.ReplaceAll(files, "OPTS", `dict "targetType" "map"`) f = strings.ReplaceAll(f, "DATA", "name,name,breed,age\nSpot,dog,Collie,3\nFelix,cat,Malicious,7", ) _, err = hugolib.TestE(t, f) if err == nil { t.Errorf("expected error") } else { if !strings.Contains(err.Error(), `header row contains duplicate field names`) { t.Log(err.Error()) t.Errorf("error message does not match expected error message") } } } // Issue 13729 func TestToMathStrictMode(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/all.html -- {{ transform.ToMath "a %" dict }} -- foo -- ` // strict mode: default f := strings.ReplaceAll(files, "dict", "") b, err := hugolib.TestE(t, f) b.Assert(err.Error(), qt.Contains, "[commentAtEnd]") // strict mode: error f = strings.ReplaceAll(files, "dict", `(dict "strict" "error")`) b, err = hugolib.TestE(t, f) b.Assert(err.Error(), qt.Contains, "[commentAtEnd]") // strict mode: ignore f = strings.ReplaceAll(files, "dict", `(dict "strict" "ignore")`) b = hugolib.Test(t, f, hugolib.TestOptWarn()) b.AssertLogMatches("") b.AssertFileContent("public/index.html", `<annotation encoding="application/x-tex">a %</annotation>`) // strict: warn f = strings.ReplaceAll(files, "dict", `(dict "strict" "warn")`) b = hugolib.Test(t, f, hugolib.TestOptWarn()) b.AssertLogMatches("[commentAtEnd]") b.AssertFileContent("public/index.html", `<annotation encoding="application/x-tex">a %</annotation>`) // strict mode: invalid value f = strings.ReplaceAll(files, "dict", `(dict "strict" "foo")`) b, err = hugolib.TestE(t, f) b.Assert(err.Error(), qt.Contains, "invalid strict mode") } func TestHTMLToMarkdown(t *testing.T) { t.Parallel() markdown := ` # Heading Some **bold** text. A [link](https://example.com). An image: ![alt text](https://example.com/image.jpg "Image Title") A list: - Item 1 - Item 2 - Item 2a - Item 2b A table: | Header 1 | Header 2 | |----------|----------| | Cell 1 | Cell 2 | | Cell 3 | Cell 4 | A blockquote: > This is a quote. ` files := ` -- hugo.toml -- disableKinds = ['rss','section','sitemap','taxonomy','term'] -- layouts/all.html -- All html. -- layouts/all.markdown -- {{ .Content | transform.HTMLToMarkdown | safeHTML }} -- content/p1.md -- --- title: p1 outputs: ["html", "markdown"] --- ` files += markdown b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", `All html.`) // There are some white space differences, so we cannot do an exact match. b.AssertFileContent("public/p1/index.md", markdown) } // See https://github.com/goccy/go-yaml/issues/461 func TestUnmarshalExcessiveYAMLStructureShouldFail(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- assets/ddos.yaml -- a: &a [_, _, _, _, _, _, _, _, _, _, _, _, _, _, _] b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a, *a] c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b, *b] d: &d [*c, *c, *c, *c, *c, *c, *c, *c, *c, *c] e: &e [*d, *d, *d, *d, *d, *d, *d, *d, *d, *d] f: &f [*e, *e, *e, *e, *e, *e, *e, *e, *e, *e] g: &g [*f, *f, *f, *f, *f, *f, *f, *f, *f, *f] h: &h [*g, *g, *g, *g, *g, *g, *g, *g, *g, *g] i: &i [*h, *h, *h, *h, *h, *h, *h, *h, *h, *h] -- layouts/home.html -- {{ $m := resources.Get "ddos.yaml" | transform.Unmarshal }} {{ printf "Length: %d" (len $m) }} ` b, err := hugolib.TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "too many YAML aliases for non-scalar nodes") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/merge.go
tpl/collections/merge.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 ( "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" ) // Merge creates a copy of the final parameter in params and merges the preceding // parameters into it in reverse order. // // Currently only maps are supported. Key handling is case insensitive. func (ns *Namespace) Merge(params ...any) (any, error) { if len(params) < 2 { return nil, errors.New("merge requires at least two parameters") } var err error result := params[len(params)-1] for i := len(params) - 2; i >= 0; i-- { result, err = ns.merge(params[i], result) if err != nil { return nil, err } } return result, nil } // merge creates a copy of dst and merges src into it. func (ns *Namespace) merge(src, dst any) (any, error) { vdst, vsrc := reflect.ValueOf(dst), reflect.ValueOf(src) if vdst.Kind() != reflect.Map { return nil, fmt.Errorf("destination must be a map, got %T", dst) } if !hreflect.IsTruthfulValue(vsrc) { return dst, nil } if vsrc.Kind() != reflect.Map { return nil, fmt.Errorf("source must be a map, got %T", src) } if vsrc.Type().Key() != vdst.Type().Key() { return nil, fmt.Errorf("incompatible map types, got %T to %T", src, dst) } return mergeMap(vdst, vsrc).Interface(), nil } func caseInsensitiveLookup(m, k reflect.Value) (reflect.Value, bool) { if m.Type().Key().Kind() != reflect.String || k.Kind() != reflect.String { // Fall back to direct lookup. v := m.MapIndex(k) return v, hreflect.IsTruthfulValue(v) } k2 := reflect.New(m.Type().Key()).Elem() iter := m.MapRange() for iter.Next() { k2.SetIterKey(iter) if strings.EqualFold(k.String(), k2.String()) { return iter.Value(), true } } return reflect.Value{}, false } func mergeMap(dst, src reflect.Value) reflect.Value { out := reflect.MakeMap(dst.Type()) // If the destination is Params, we must lower case all keys. _, lowerCase := dst.Interface().(maps.Params) k := reflect.New(dst.Type().Key()).Elem() v := reflect.New(dst.Type().Elem()).Elem() // Copy the destination map. iter := dst.MapRange() for iter.Next() { k.SetIterKey(iter) v.SetIterValue(iter) out.SetMapIndex(k, v) } // Add all keys in src not already in destination. // Maps of the same type will be merged. k = reflect.New(src.Type().Key()).Elem() sv := reflect.New(src.Type().Elem()).Elem() iter = src.MapRange() for iter.Next() { sv.SetIterValue(iter) k.SetIterKey(iter) dv, found := caseInsensitiveLookup(dst, k) if found { // If both are the same map key type, merge. dve := dv.Elem() if dve.Kind() == reflect.Map { sve := sv.Elem() if sve.Kind() != reflect.Map { continue } if dve.Type().Key() == sve.Type().Key() { out.SetMapIndex(k, mergeMap(dve, sve)) } } } else { kk := k if lowerCase && k.Kind() == reflect.String { kk = reflect.ValueOf(strings.ToLower(k.String())) } out.SetMapIndex(kk, sv) } } return out }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/init.go
tpl/collections/init.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" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/internal" ) const name = "collections" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { ctx := New(d) ns := &internal.TemplateFuncsNamespace{ Name: name, Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } ns.AddMethodMapping(ctx.After, []string{"after"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Append, []string{"append"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Apply, []string{"apply"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Complement, []string{"complement"}, [][2]string{ {`{{ slice "a" "b" "c" "d" "e" "f" | complement (slice "b" "c") (slice "d" "e") }}`, `[a f]`}, }, ) ns.AddMethodMapping(ctx.D, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Delimit, []string{"delimit"}, [][2]string{ {`{{ delimit (slice "A" "B" "C") ", " " and " }}`, `A, B and C`}, }, ) ns.AddMethodMapping(ctx.Dictionary, []string{"dict"}, [][2]string{}, ) ns.AddMethodMapping(ctx.First, []string{"first"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Group, []string{"group"}, [][2]string{}, ) ns.AddMethodMapping(ctx.In, []string{"in"}, [][2]string{ {`{{ if in "this string contains a substring" "substring" }}Substring found!{{ end }}`, `Substring found!`}, }, ) ns.AddMethodMapping(ctx.Index, []string{"index"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Intersect, []string{"intersect"}, [][2]string{}, ) ns.AddMethodMapping(ctx.IsSet, []string{"isSet", "isset"}, [][2]string{}, ) ns.AddMethodMapping(ctx.KeyVals, []string{"keyVals"}, [][2]string{ {`{{ keyVals "key" "a" "b" }}`, `key: [a b]`}, }, ) ns.AddMethodMapping(ctx.Last, []string{"last"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Merge, []string{"merge"}, [][2]string{ { `{{ dict "title" "Hugo Rocks!" | collections.Merge (dict "title" "Default Title" "description" "Yes, Hugo Rocks!") | sort }}`, `[Yes, Hugo Rocks! Hugo Rocks!]`, }, { `{{ merge (dict "title" "Default Title" "description" "Yes, Hugo Rocks!") (dict "title" "Hugo Rocks!") | sort }}`, `[Yes, Hugo Rocks! Hugo Rocks!]`, }, { `{{ merge (dict "title" "Default Title" "description" "Yes, Hugo Rocks!") (dict "title" "Hugo Rocks!") (dict "extra" "For reals!") | sort }}`, `[Yes, Hugo Rocks! For reals! Hugo Rocks!]`, }, }, ) ns.AddMethodMapping(ctx.NewScratch, []string{"newScratch"}, [][2]string{ {`{{ $scratch := newScratch }}{{ $scratch.Add "b" 2 }}{{ $scratch.Add "b" 2 }}{{ $scratch.Get "b" }}`, `4`}, }, ) ns.AddMethodMapping(ctx.Querify, []string{"querify"}, [][2]string{ { `{{ (querify "foo" 1 "bar" 2 "baz" "with spaces" "qux" "this&that=those") | safeHTML }}`, `bar=2&baz=with+spaces&foo=1&qux=this%26that%3Dthose`, }, { `<a href="https://www.google.com?{{ (querify "q" "test" "page" 3) | safeURL }}">Search</a>`, `<a href="https://www.google.com?page=3&amp;q=test">Search</a>`, }, { `{{ slice "foo" 1 "bar" 2 | querify | safeHTML }}`, `bar=2&foo=1`, }, }, ) ns.AddMethodMapping(ctx.Reverse, nil, [][2]string{}, ) ns.AddMethodMapping(ctx.Seq, []string{"seq"}, [][2]string{ {`{{ seq 3 }}`, `[1 2 3]`}, }, ) ns.AddMethodMapping(ctx.Shuffle, []string{"shuffle"}, [][2]string{}, ) ns.AddMethodMapping(ctx.Slice, []string{"slice"}, [][2]string{ {`{{ slice "B" "C" "A" | sort }}`, `[A B C]`}, }, ) ns.AddMethodMapping(ctx.Sort, []string{"sort"}, [][2]string{}, ) ns.AddMethodMapping(ctx.SymDiff, []string{"symdiff"}, [][2]string{ {`{{ slice 1 2 3 | symdiff (slice 3 4) }}`, `[1 2 4]`}, }, ) ns.AddMethodMapping(ctx.Union, []string{"union"}, [][2]string{ {`{{ union (slice 1 2 3) (slice 3 4 5) }}`, `[1 2 3 4 5]`}, }, ) ns.AddMethodMapping(ctx.Uniq, []string{"uniq"}, [][2]string{ {`{{ slice 1 2 3 2 | uniq }}`, `[1 2 3]`}, }, ) ns.AddMethodMapping(ctx.Where, []string{"where"}, [][2]string{}, ) return ns } internal.AddTemplateFuncsNamespace(f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/sort.go
tpl/collections/sort.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" "reflect" "sort" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/tpl/compare" "github.com/spf13/cast" ) // Sort returns a sorted copy of the list l. func (ns *Namespace) Sort(ctx context.Context, l any, args ...any) (any, error) { if l == nil { return nil, errors.New("sequence must be provided") } seqv, isNil := hreflect.Indirect(reflect.ValueOf(l)) if isNil { return nil, errors.New("can't iterate over a nil value") } ctxv := reflect.ValueOf(ctx) var sliceType reflect.Type switch seqv.Kind() { case reflect.Array, reflect.Slice: sliceType = seqv.Type() case reflect.Map: sliceType = reflect.SliceOf(seqv.Type().Elem()) default: return nil, errors.New("can't sort " + reflect.ValueOf(l).Type().String()) } collator := langs.GetCollator1(ns.deps.Conf.Language().(*langs.Language)) // Create a list of pairs that will be used to do the sort p := pairList{Collator: collator, sortComp: ns.sortComp, SortAsc: true, SliceType: sliceType} p.Pairs = make([]pair, seqv.Len()) var sortByField string for i, l := range args { dStr, err := cast.ToStringE(l) switch { case i == 0 && err != nil: sortByField = "" case i == 0 && err == nil: sortByField = dStr case i == 1 && err == nil && dStr == "desc": p.SortAsc = false case i == 1: p.SortAsc = true } } path := strings.Split(strings.Trim(sortByField, "."), ".") switch seqv.Kind() { case reflect.Array, reflect.Slice: for i := range seqv.Len() { p.Pairs[i].Value = seqv.Index(i) if sortByField == "" || sortByField == "value" { p.Pairs[i].Key = p.Pairs[i].Value } else { v := p.Pairs[i].Value var err error for i, elemName := range path { v, err = evaluateSubElem(ctxv, v, elemName) if err != nil { return nil, err } if !v.IsValid() { continue } // Special handling of lower cased maps. if params, ok := v.Interface().(maps.Params); ok { v = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } p.Pairs[i].Key = v } } case reflect.Map: iter := seqv.MapRange() i := 0 for iter.Next() { key := iter.Key() value := iter.Value() p.Pairs[i].Value = value if sortByField == "" { p.Pairs[i].Key = key } else if sortByField == "value" { p.Pairs[i].Key = p.Pairs[i].Value } else { v := p.Pairs[i].Value var err error for j, elemName := range path { v, err = evaluateSubElem(ctxv, v, elemName) if err != nil { return nil, err } if !v.IsValid() { continue } // Special handling of lower cased maps. if params, ok := v.Interface().(maps.Params); ok { v = reflect.ValueOf(params.GetNested(path[j+1:]...)) break } } p.Pairs[i].Key = v } i++ } } collator.Lock() defer collator.Unlock() return p.sort(), nil } // Credit for pair sorting method goes to Andrew Gerrand // https://groups.google.com/forum/#!topic/golang-nuts/FT7cjmcL7gw // A data structure to hold a key/value pair. type pair struct { Key reflect.Value Value reflect.Value } // A slice of pairs that implements sort.Interface to sort by Value. type pairList struct { Collator *langs.Collator sortComp *compare.Namespace Pairs []pair SortAsc bool SliceType reflect.Type } func (p pairList) Swap(i, j int) { p.Pairs[i], p.Pairs[j] = p.Pairs[j], p.Pairs[i] } func (p pairList) Len() int { return len(p.Pairs) } func (p pairList) Less(i, j int) bool { iv := p.Pairs[i].Key jv := p.Pairs[j].Key if iv.IsValid() { if jv.IsValid() { // can only call Interface() on valid reflect Values return p.sortComp.LtCollate(p.Collator, iv.Interface(), jv.Interface()) } // if j is invalid, test i against i's zero value return p.sortComp.LtCollate(p.Collator, iv.Interface(), reflect.Zero(iv.Type())) } if jv.IsValid() { // if i is invalid, test j against j's zero value return p.sortComp.LtCollate(p.Collator, reflect.Zero(jv.Type()), jv.Interface()) } return false } // sorts a pairList and returns a slice of sorted values func (p pairList) sort() any { if p.SortAsc { sort.Stable(p) } else { sort.Stable(sort.Reverse(p)) } sorted := reflect.MakeSlice(p.SliceType, len(p.Pairs), len(p.Pairs)) for i, v := range p.Pairs { sorted.Index(i).Set(v.Value) } return sorted.Interface() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/index.go
tpl/collections/index.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 ( "errors" "fmt" "reflect" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" ) // Index returns the result of indexing its first argument by the following // arguments. Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each // indexed item must be a map, slice, or array. // // Adapted from Go stdlib src/text/template/funcs.go. // // We deviate from the stdlib mostly because of https://github.com/golang/go/issues/14751. func (ns *Namespace) Index(item any, args ...any) (any, error) { v, err := ns.doIndex(item, args...) if err != nil { return nil, fmt.Errorf("index of type %T with args %v failed: %s", item, args, err) } return v, nil } func (ns *Namespace) doIndex(item any, args ...any) (any, error) { // TODO(moorereason): merge upstream changes. v := reflect.ValueOf(item) if !v.IsValid() { // See issue 10489 // This used to be an error. return nil, nil } var indices []any if len(args) == 1 { v := reflect.ValueOf(args[0]) if v.Kind() == reflect.Slice { for i := range v.Len() { indices = append(indices, v.Index(i).Interface()) } } else { indices = append(indices, args[0]) } } else { indices = args } lowerm, ok := item.(maps.Params) if ok { return lowerm.GetNested(cast.ToStringSlice(indices)...), nil } for _, i := range indices { index := reflect.ValueOf(i) var isNil bool if v, isNil = hreflect.Indirect(v); isNil { // See issue 10489 // This used to be an error. return nil, nil } switch v.Kind() { case reflect.Array, reflect.Slice, reflect.String: var x int64 switch index.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: x = index.Int() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: x = int64(index.Uint()) case reflect.Invalid: return nil, errors.New("cannot index slice/array with nil") default: return nil, fmt.Errorf("cannot index slice/array with type %s", index.Type()) } if x < 0 || x >= int64(v.Len()) { // We deviate from stdlib here. Don't return an error if the // index is out of range. return nil, nil } v = v.Index(int(x)) case reflect.Map: index, err := prepareArg(index, v.Type().Key()) if err != nil { return nil, err } if x := v.MapIndex(index); x.IsValid() { v = x } else { v = reflect.Zero(v.Type().Elem()) } case reflect.Invalid: // the loop holds invariant: v.IsValid() panic("unreachable") default: return nil, fmt.Errorf("can't index item of type %s", v.Type()) } } return v.Interface(), nil } // prepareArg checks if value can be used as an argument of type argType, and // converts an invalid value to appropriate zero if possible. // // Copied from Go stdlib src/text/template/funcs.go. func prepareArg(value reflect.Value, argType reflect.Type) (reflect.Value, error) { if !value.IsValid() { if !canBeNil(argType) { return reflect.Value{}, fmt.Errorf("value is nil; should be of type %s", argType) } value = reflect.Zero(argType) } if !value.Type().AssignableTo(argType) { return reflect.Value{}, fmt.Errorf("value has type %s; should be %s", value.Type(), argType) } return value, nil } // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero. // // Copied from Go stdlib src/text/template/exec.go. func canBeNil(typ reflect.Type) bool { switch typ.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return true } return false }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/symdiff_test.go
tpl/collections/symdiff_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package collections import ( "reflect" "testing" qt "github.com/frankban/quicktest" ) func TestSymDiff(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() s1 := []TstX{{A: "a"}, {A: "b"}} s2 := []TstX{{A: "a"}, {A: "e"}} xa, xb, xd, xe := &StructWithSlice{A: "a"}, &StructWithSlice{A: "b"}, &StructWithSlice{A: "d"}, &StructWithSlice{A: "e"} sp1 := []*StructWithSlice{xa, xb, xd, xe} sp2 := []*StructWithSlice{xb, xe} for i, test := range []struct { s1 any s2 any expected any }{ {[]string{"a", "x", "b", "c"}, []string{"a", "b", "y", "c"}, []string{"x", "y"}}, {[]string{"a", "b", "c"}, []string{"a", "b", "c"}, []string{}}, {[]any{"a", "b", nil}, []any{"a"}, []any{"b", nil}}, {[]int{1, 2, 3}, []int{3, 4}, []int{1, 2, 4}}, {[]int{1, 2, 3}, []int64{3, 4}, []int{1, 2, 4}}, {s1, s2, []TstX{{A: "b"}, {A: "e"}}}, {sp1, sp2, []*StructWithSlice{xa, xd}}, // Errors {"error", "error", false}, {[]int{1, 2, 3}, []string{"3", "4"}, false}, } { errMsg := qt.Commentf("[%d]", i) result, err := ns.SymDiff(test.s2, test.s1) if b, ok := test.expected.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil, errMsg) if !reflect.DeepEqual(test.expected, result) { t.Fatalf("%s got\n%T: %v\nexpected\n%T: %v", errMsg, result, result, test.expected, test.expected) } } _, err := ns.Complement() c.Assert(err, qt.Not(qt.IsNil)) _, err = ns.Complement([]string{"a", "b"}) c.Assert(err, qt.Not(qt.IsNil)) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/querify_test.go
tpl/collections/querify_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package collections import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/maps" ) func TestQuerify(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for _, test := range []struct { name string params []any expect any }{ // map {"01", []any{maps.Params{"a": "foo", "b": "bar"}}, `a=foo&b=bar`}, {"02", []any{maps.Params{"a": 6, "b": 7}}, `a=6&b=7`}, {"03", []any{maps.Params{"a": "foo", "b": 7}}, `a=foo&b=7`}, {"04", []any{map[string]any{"a": "foo", "b": "bar"}}, `a=foo&b=bar`}, {"05", []any{map[string]any{"a": 6, "b": 7}}, `a=6&b=7`}, {"06", []any{map[string]any{"a": "foo", "b": 7}}, `a=foo&b=7`}, // slice {"07", []any{[]string{"a", "foo", "b", "bar"}}, `a=foo&b=bar`}, {"08", []any{[]any{"a", 6, "b", 7}}, `a=6&b=7`}, {"09", []any{[]any{"a", "foo", "b", 7}}, `a=foo&b=7`}, // sequence of scalar values {"10", []any{"a", "foo", "b", "bar"}, `a=foo&b=bar`}, {"11", []any{"a", 6, "b", 7}, `a=6&b=7`}, {"12", []any{"a", "foo", "b", 7}, `a=foo&b=7`}, // empty map {"13", []any{map[string]any{}}, ``}, // empty slice {"14", []any{[]string{}}, ``}, {"15", []any{[]any{}}, ``}, // no arguments {"16", []any{}, ``}, // errors: zero key length {"17", []any{maps.Params{"": "foo"}}, false}, {"18", []any{map[string]any{"": "foo"}}, false}, {"19", []any{[]string{"", "foo"}}, false}, {"20", []any{[]any{"", 6}}, false}, {"21", []any{"", "foo"}, false}, // errors: odd number of values {"22", []any{[]string{"a", "foo", "b"}}, false}, {"23", []any{[]any{"a", 6, "b"}}, false}, {"24", []any{"a", "foo", "b"}, false}, // errors: value cannot be cast to string {"25", []any{map[string]any{"a": "foo", "b": tstNoStringer{}}}, false}, {"26", []any{[]any{"a", "foo", "b", tstNoStringer{}}}, false}, {"27", []any{"a", "foo", "b", tstNoStringer{}}, false}, } { errMsg := qt.Commentf("[%s] %v", test.name, test.params) result, err := ns.Querify(test.params...) if b, ok := test.expect.(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 BenchmarkQuerify(b *testing.B) { ns := newNs() params := []any{"a", "b", "c", "d", "f", " &"} for b.Loop() { _, err := ns.Querify(params...) if err != nil { b.Fatal(err) } } } func BenchmarkQuerifySlice(b *testing.B) { ns := newNs() params := []string{"a", "b", "c", "d", "f", " &"} for b.Loop() { _, err := ns.Querify(params) if err != nil { b.Fatal(err) } } } func BenchmarkQuerifyMap(b *testing.B) { ns := newNs() params := map[string]any{"a": "b", "c": "d", "f": " &"} for b.Loop() { _, err := ns.Querify(params) if err != nil { b.Fatal(err) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/where.go
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/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 := hreflect.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 %T", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := hreflect.Indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := hreflect.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.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: iv := int64(v.Uint()) ivp = &iv imv := int64(mv.Uint()) 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 hreflect.IsNumber(v.Kind()) && hreflect.IsNumber(mv.Kind()) { fv, err := hreflect.ToFloat64E(v) if err != nil { return false, err } fvp = &fv fmv, err := hreflect.ToFloat64E(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 { if op == "not in" { return true, nil } 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 := range mv.Len() { if anInt, err := hreflect.ToInt64E(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := range mv.Len() { if aString, err := hreflect.ToStringE(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := range mv.Len() { if aFloat, err := hreflect.ToFloat64E(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 := range mv.Len() { 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 := hreflect.Indirect(obj) // 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 !hreflect.IsInterfaceOrPointer(objPtr.Kind()) && objPtr.CanAddr() { objPtr = objPtr.Addr() } mt := hreflect.GetMethodByNameForType(objPtr.Type(), elemName) if mt.Func.IsValid() { // Receiver is the first argument. args := []reflect.Value{objPtr} num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && hreflect.IsContextType(mt.Type.In(1)) { args = append(args, 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 := mt.Func.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) } obj = reflect.Indirect(obj) 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 := range seqv.Len() { 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, _ := hreflect.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()) k := reflect.New(seqv.Type().Key()).Elem() elemv := reflect.New(seqv.Type().Elem()).Elem() iter := seqv.MapRange() for iter.Next() { k.SetIterKey(iter) elemv.SetIterValue(iter) 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 := hreflect.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 } // toString returns the string value if possible, "" if not. 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() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/merge_test.go
tpl/collections/merge_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 collections import ( "bytes" "reflect" "testing" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" qt "github.com/frankban/quicktest" ) func TestMerge(t *testing.T) { ns := newNs() simpleMap := map[string]any{"a": 1, "b": 2} for i, test := range []struct { name string params []any expect any isErr bool }{ { "basic", []any{ map[string]any{"a": 42, "c": 3}, map[string]any{"a": 1, "b": 2}, }, map[string]any{"a": 1, "b": 2, "c": 3}, false, }, { "multi", []any{ map[string]any{"a": 42, "c": 3, "e": 11}, map[string]any{"a": 1, "b": 2}, map[string]any{"a": 9, "c": 4, "d": 7}, }, map[string]any{"a": 9, "b": 2, "c": 4, "d": 7, "e": 11}, false, }, { "basic case insensitive", []any{ map[string]any{"A": 42, "c": 3}, map[string]any{"a": 1, "b": 2}, }, map[string]any{"a": 1, "b": 2, "c": 3}, false, }, { "nested", []any{ map[string]any{"a": 42, "c": 3, "b": map[string]any{"d": 55, "e": 66, "f": 3}}, map[string]any{"a": 1, "b": map[string]any{"d": 1, "e": 2}}, }, map[string]any{"a": 1, "b": map[string]any{"d": 1, "e": 2, "f": 3}, "c": 3}, false, }, { // https://github.com/gohugoio/hugo/issues/6633 "params dst", []any{ map[string]any{"a": 42, "c": 3}, maps.Params{"a": 1, "b": 2}, }, maps.Params{"a": int(1), "b": int(2), "c": int(3)}, false, }, { "params dst, upper case src", []any{ map[string]any{"a": 42, "C": 3}, maps.Params{"a": 1, "b": 2}, }, maps.Params{"a": int(1), "b": int(2), "c": int(3)}, false, }, { "params src", []any{ maps.Params{"a": 42, "c": 3}, map[string]any{"a": 1, "c": 2}, }, map[string]any{"a": int(1), "c": int(2)}, false, }, { "params src, upper case dst", []any{ maps.Params{"a": 42, "c": 3}, map[string]any{"a": 1, "C": 2}, }, map[string]any{"a": int(1), "C": int(2)}, false, }, { "nested, params dst", []any{ map[string]any{"a": 42, "c": 3, "b": map[string]any{"d": 55, "e": 66, "f": 3}}, maps.Params{"a": 1, "b": maps.Params{"d": 1, "e": 2}}, }, maps.Params{"a": 1, "b": maps.Params{"d": 1, "e": 2, "f": 3}, "c": 3}, false, }, { // https://github.com/gohugoio/hugo/issues/7899 "matching keys with non-map src value", []any{ map[string]any{"k": "v"}, map[string]any{"k": map[string]any{"k2": "v2"}}, }, map[string]any{"k": map[string]any{"k2": "v2"}}, false, }, {"src nil", []any{nil, simpleMap}, simpleMap, false}, // Error cases. {"dst not a map", []any{nil, "not a map"}, nil, true}, {"src not a map", []any{"not a map", simpleMap}, nil, true}, {"different map types", []any{map[int]any{32: "a"}, simpleMap}, nil, true}, {"all nil", []any{nil, nil}, nil, true}, } { t.Run(test.name, func(t *testing.T) { t.Parallel() errMsg := qt.Commentf("[%d] %v", i, test) c := qt.New(t) result, err := ns.Merge(test.params...) if test.isErr { c.Assert(err, qt.Not(qt.IsNil), errMsg) return } c.Assert(err, qt.IsNil) c.Assert(result, qt.DeepEquals, test.expect, errMsg) }) } } func BenchmarkMerge(b *testing.B) { ns := newNs() for b.Loop() { ns.Merge( map[string]any{"a": 42, "c": 3, "e": 11}, map[string]any{"a": 1, "b": 2}, map[string]any{"a": 9, "c": 4, "d": 7}, ) } } func TestMergeDataFormats(t *testing.T) { c := qt.New(t) ns := newNs() toml1 := ` V1 = "v1_1" [V2s] V21 = "v21_1" ` toml2 := ` V1 = "v1_2" V2 = "v2_2" [V2s] V21 = "v21_2" V22 = "v22_2" ` meta1, err := metadecoders.Default.UnmarshalToMap([]byte(toml1), metadecoders.TOML) c.Assert(err, qt.IsNil) meta2, err := metadecoders.Default.UnmarshalToMap([]byte(toml2), metadecoders.TOML) c.Assert(err, qt.IsNil) for _, format := range []metadecoders.Format{metadecoders.JSON, metadecoders.YAML, metadecoders.TOML} { var dataStr1, dataStr2 bytes.Buffer err = parser.InterfaceToConfig(meta1, format, &dataStr1) c.Assert(err, qt.IsNil) err = parser.InterfaceToConfig(meta2, format, &dataStr2) c.Assert(err, qt.IsNil) dst, err := metadecoders.Default.UnmarshalToMap(dataStr1.Bytes(), format) c.Assert(err, qt.IsNil) src, err := metadecoders.Default.UnmarshalToMap(dataStr2.Bytes(), format) c.Assert(err, qt.IsNil) merged, err := ns.Merge(src, dst) c.Assert(err, qt.IsNil) c.Assert( merged, qt.DeepEquals, map[string]any{ "V1": "v1_1", "V2": "v2_2", "V2s": map[string]any{"V21": "v21_1", "V22": "v22_2"}, }) } } func TestCaseInsensitiveMapLookup(t *testing.T) { c := qt.New(t) m1 := reflect.ValueOf(map[string]any{ "a": 1, "B": 2, }) m2 := reflect.ValueOf(map[int]any{ 1: 1, 2: 2, }) var found bool a, found := caseInsensitiveLookup(m1, reflect.ValueOf("A")) c.Assert(found, qt.Equals, true) c.Assert(a.Interface(), qt.Equals, 1) b, found := caseInsensitiveLookup(m1, reflect.ValueOf("b")) c.Assert(found, qt.Equals, true) c.Assert(b.Interface(), qt.Equals, 2) two, found := caseInsensitiveLookup(m2, reflect.ValueOf(2)) c.Assert(found, qt.Equals, true) c.Assert(two.Interface(), qt.Equals, 2) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/collections_test.go
tpl/collections/collections_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 collections import ( "context" "errors" "fmt" "html/template" "math/rand" "reflect" "testing" "time" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config/testconfig" qt "github.com/frankban/quicktest" ) type tstNoStringer struct{} func TestAfter(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { index any seq any expect any }{ {int(2), []string{"a", "b", "c", "d"}, []string{"c", "d"}}, {int32(3), []string{"a", "b"}, []string{}}, {int64(2), []int{100, 200, 300}, []int{300}}, {100, []int{100, 200}, []int{}}, {"1", []int{100, 200, 300}, []int{200, 300}}, {0, []int{100, 200, 300, 400, 500}, []int{100, 200, 300, 400, 500}}, {0, []string{"a", "b", "c", "d", "e"}, []string{"a", "b", "c", "d", "e"}}, {int64(-1), []int{100, 200, 300}, false}, {"noint", []int{100, 200, 300}, false}, {2, []string{}, []string{}}, {1, nil, false}, {nil, []int{100}, false}, {1, t, false}, {1, (*string)(nil), false}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.After(test.index, test.seq) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil, errMsg) c.Assert(result, qt.DeepEquals, test.expect, errMsg) } } type tstGrouper struct{} type tstGroupers []*tstGrouper func (g tstGrouper) Group(key any, items any) (any, error) { ilen := reflect.ValueOf(items).Len() return fmt.Sprintf("%v(%d)", key, ilen), nil } type tstGrouper2 struct{} func (g *tstGrouper2) Group(key any, items any) (any, error) { ilen := reflect.ValueOf(items).Len() return fmt.Sprintf("%v(%d)", key, ilen), nil } func TestGroup(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { key any items any expect any }{ {"a", []*tstGrouper{{}, {}}, "a(2)"}, {"b", tstGroupers{&tstGrouper{}, &tstGrouper{}}, "b(2)"}, {"a", []tstGrouper{{}, {}}, "a(2)"}, {"a", []*tstGrouper2{{}, {}}, "a(2)"}, {"b", []tstGrouper2{{}, {}}, "b(2)"}, {"a", []*tstGrouper{}, "a(0)"}, {"a", []string{"a", "b"}, false}, {"a", "asdf", false}, {"a", nil, false}, {nil, []*tstGrouper{{}, {}}, false}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.Group(test.key, test.items) if b, ok := test.expect.(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 TestDelimit(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { seq any delimiter any last any expect string }{ {[]string{"class1", "class2", "class3"}, " ", nil, "class1 class2 class3"}, {[]int{1, 2, 3, 4, 5}, ",", nil, "1,2,3,4,5"}, {[]int{1, 2, 3, 4, 5}, ", ", nil, "1, 2, 3, 4, 5"}, {[]string{"class1", "class2", "class3"}, " ", " and ", "class1 class2 and class3"}, {[]int{1, 2, 3, 4, 5}, ",", ",", "1,2,3,4,5"}, {[]int{1, 2, 3, 4, 5}, ", ", ", and ", "1, 2, 3, 4, and 5"}, // test maps with and without sorting required {map[string]int{"1": 10, "2": 20, "3": 30, "4": 40, "5": 50}, "--", nil, "10--20--30--40--50"}, {map[string]int{"3": 10, "2": 20, "1": 30, "4": 40, "5": 50}, "--", nil, "30--20--10--40--50"}, {map[string]string{"1": "10", "2": "20", "3": "30", "4": "40", "5": "50"}, "--", nil, "10--20--30--40--50"}, {map[string]string{"3": "10", "2": "20", "1": "30", "4": "40", "5": "50"}, "--", nil, "30--20--10--40--50"}, {map[string]string{"one": "10", "two": "20", "three": "30", "four": "40", "five": "50"}, "--", nil, "50--40--10--30--20"}, {map[int]string{1: "10", 2: "20", 3: "30", 4: "40", 5: "50"}, "--", nil, "10--20--30--40--50"}, {map[int]string{3: "10", 2: "20", 1: "30", 4: "40", 5: "50"}, "--", nil, "30--20--10--40--50"}, {map[float64]string{3.3: "10", 2.3: "20", 1.3: "30", 4.3: "40", 5.3: "50"}, "--", nil, "30--20--10--40--50"}, // test maps with a last delimiter {map[string]int{"1": 10, "2": 20, "3": 30, "4": 40, "5": 50}, "--", "--and--", "10--20--30--40--and--50"}, {map[string]int{"3": 10, "2": 20, "1": 30, "4": 40, "5": 50}, "--", "--and--", "30--20--10--40--and--50"}, {map[string]string{"1": "10", "2": "20", "3": "30", "4": "40", "5": "50"}, "--", "--and--", "10--20--30--40--and--50"}, {map[string]string{"3": "10", "2": "20", "1": "30", "4": "40", "5": "50"}, "--", "--and--", "30--20--10--40--and--50"}, {map[string]string{"one": "10", "two": "20", "three": "30", "four": "40", "five": "50"}, "--", "--and--", "50--40--10--30--and--20"}, {map[int]string{1: "10", 2: "20", 3: "30", 4: "40", 5: "50"}, "--", "--and--", "10--20--30--40--and--50"}, {map[int]string{3: "10", 2: "20", 1: "30", 4: "40", 5: "50"}, "--", "--and--", "30--20--10--40--and--50"}, {map[float64]string{3.5: "10", 2.5: "20", 1.5: "30", 4.5: "40", 5.5: "50"}, "--", "--and--", "30--20--10--40--and--50"}, } { errMsg := qt.Commentf("[%d] %v", i, test) var result string var err error if test.last == nil { result, err = ns.Delimit(context.Background(), test.seq, test.delimiter) } else { result, err = ns.Delimit(context.Background(), test.seq, test.delimiter, test.last) } c.Assert(err, qt.IsNil, errMsg) c.Assert(result, qt.Equals, test.expect, errMsg) } } func TestDictionary(t *testing.T) { c := qt.New(t) ns := newNs() for i, test := range []struct { values []any expect any }{ {[]any{"a", "b"}, map[string]any{"a": "b"}}, {[]any{[]string{"a", "b"}, "c"}, map[string]any{"a": map[string]any{"b": "c"}}}, { []any{[]string{"a", "b"}, "c", []string{"a", "b2"}, "c2", "b", "c"}, map[string]any{"a": map[string]any{"b": "c", "b2": "c2"}, "b": "c"}, }, {[]any{"a", 12, "b", []int{4}}, map[string]any{"a": 12, "b": []int{4}}}, // errors {[]any{5, "b"}, false}, {[]any{"a", "b", "c"}, false}, } { c.Run(fmt.Sprint(i), func(c *qt.C) { c.Parallel() errMsg := qt.Commentf("[%d] %v", i, test.values) result, err := ns.Dictionary(test.values...) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil), errMsg) return } c.Assert(err, qt.IsNil, errMsg) c.Assert(result, qt.DeepEquals, test.expect, qt.Commentf(fmt.Sprint(result))) }) } } func TestReverse(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() s := []string{"a", "b", "c"} reversed, err := ns.Reverse(s) c.Assert(err, qt.IsNil) c.Assert(reversed, qt.DeepEquals, []string{"c", "b", "a"}, qt.Commentf(fmt.Sprint(reversed))) c.Assert(s, qt.DeepEquals, []string{"a", "b", "c"}) reversed, err = ns.Reverse(nil) c.Assert(err, qt.IsNil) c.Assert(reversed, qt.IsNil) _, err = ns.Reverse(43) c.Assert(err, qt.Not(qt.IsNil)) } func TestFirst(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { limit any seq any expect any }{ {int(2), []string{"a", "b", "c"}, []string{"a", "b"}}, {int32(3), []string{"a", "b"}, []string{"a", "b"}}, {int64(2), []int{100, 200, 300}, []int{100, 200}}, {100, []int{100, 200}, []int{100, 200}}, {"1", []int{100, 200, 300}, []int{100}}, {0, []string{"h", "u", "g", "o"}, []string{}}, {int64(-1), []int{100, 200, 300}, false}, {"noint", []int{100, 200, 300}, false}, {1, nil, false}, {nil, []int{100}, false}, {1, t, false}, {1, (*string)(nil), false}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.First(test.limit, test.seq) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil) c.Assert(result, qt.DeepEquals, test.expect, errMsg) } } func TestIn(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { l1 any l2 any expect bool }{ {[]string{"a", "b", "c"}, "b", true}, {[]any{"a", "b", "c"}, "b", true}, {[]any{"a", "b", "c"}, "d", false}, {[]string{"a", "b", "c"}, "d", false}, {[]string{"a", "12", "c"}, 12, false}, {[]string{"a", "b", "c"}, nil, false}, {[]int{1, 2, 4}, 2, true}, {[]any{1, 2, 4}, 2, true}, {[]any{1, 2, 4}, nil, false}, {[]any{nil}, nil, false}, {[]int{1, 2, 4}, 3, false}, {[]float64{1.23, 2.45, 4.67}, 1.23, true}, {[]float64{1.234567, 2.45, 4.67}, 1.234568, false}, {[]float64{1, 2, 3}, 1, true}, {[]float32{1, 2, 3}, 1, true}, {"this substring should be found", "substring", true}, {"this substring should not be found", "subseastring", false}, {nil, "foo", false}, // Pointers {pagesPtr{p1, p2, p3, p2}, p2, true}, {pagesPtr{p1, p2, p3, p2}, p4, false}, // Structs {pagesVals{p3v, p2v, p3v, p2v}, p2v, true}, {pagesVals{p3v, p2v, p3v, p2v}, p4v, false}, // template.HTML {template.HTML("this substring should be found"), "substring", true}, {template.HTML("this substring should not be found"), "subseastring", false}, // Uncomparable, use hashstructure {[]string{"a", "b"}, []string{"a", "b"}, false}, {[][]string{{"a", "b"}}, []string{"a", "b"}, true}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.In(test.l1, test.l2) c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, test.expect, errMsg) } } type testPage struct { Title string } func (p testPage) String() string { return "p-" + p.Title } type ( pagesPtr []*testPage pagesVals []testPage ) var ( p1 = &testPage{"A"} p2 = &testPage{"B"} p3 = &testPage{"C"} p4 = &testPage{"D"} p1v = testPage{"A"} p2v = testPage{"B"} p3v = testPage{"C"} p4v = testPage{"D"} ) func TestIntersect(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { l1, l2 any expect any }{ {[]string{"a", "b", "c", "c"}, []string{"a", "b", "b"}, []string{"a", "b"}}, {[]string{"a", "b"}, []string{"a", "b", "c"}, []string{"a", "b"}}, {[]string{"a", "b", "c"}, []string{"d", "e"}, []string{}}, {[]string{}, []string{}, []string{}}, {[]string{"a", "b"}, nil, []any{}}, {nil, []string{"a", "b"}, []any{}}, {nil, nil, []any{}}, {[]string{"1", "2"}, []int{1, 2}, []string{}}, {[]int{1, 2}, []string{"1", "2"}, []int{}}, {[]int{1, 2, 4}, []int{2, 4}, []int{2, 4}}, {[]int{2, 4}, []int{1, 2, 4}, []int{2, 4}}, {[]int{1, 2, 4}, []int{3, 6}, []int{}}, {[]float64{2.2, 4.4}, []float64{1.1, 2.2, 4.4}, []float64{2.2, 4.4}}, // []interface{} ∩ []interface{} {[]any{"a", "b", "c"}, []any{"a", "b", "b"}, []any{"a", "b"}}, {[]any{1, 2, 3}, []any{1, 2, 2}, []any{1, 2}}, {[]any{int8(1), int8(2), int8(3)}, []any{int8(1), int8(2), int8(2)}, []any{int8(1), int8(2)}}, {[]any{int16(1), int16(2), int16(3)}, []any{int16(1), int16(2), int16(2)}, []any{int16(1), int16(2)}}, {[]any{int32(1), int32(2), int32(3)}, []any{int32(1), int32(2), int32(2)}, []any{int32(1), int32(2)}}, {[]any{int64(1), int64(2), int64(3)}, []any{int64(1), int64(2), int64(2)}, []any{int64(1), int64(2)}}, {[]any{float32(1), float32(2), float32(3)}, []any{float32(1), float32(2), float32(2)}, []any{float32(1), float32(2)}}, {[]any{float64(1), float64(2), float64(3)}, []any{float64(1), float64(2), float64(2)}, []any{float64(1), float64(2)}}, // []interface{} ∩ []T {[]any{"a", "b", "c"}, []string{"a", "b", "b"}, []any{"a", "b"}}, {[]any{1, 2, 3}, []int{1, 2, 2}, []any{1, 2}}, {[]any{int8(1), int8(2), int8(3)}, []int8{1, 2, 2}, []any{int8(1), int8(2)}}, {[]any{int16(1), int16(2), int16(3)}, []int16{1, 2, 2}, []any{int16(1), int16(2)}}, {[]any{int32(1), int32(2), int32(3)}, []int32{1, 2, 2}, []any{int32(1), int32(2)}}, {[]any{int64(1), int64(2), int64(3)}, []int64{1, 2, 2}, []any{int64(1), int64(2)}}, {[]any{uint(1), uint(2), uint(3)}, []uint{1, 2, 2}, []any{uint(1), uint(2)}}, {[]any{float32(1), float32(2), float32(3)}, []float32{1, 2, 2}, []any{float32(1), float32(2)}}, {[]any{float64(1), float64(2), float64(3)}, []float64{1, 2, 2}, []any{float64(1), float64(2)}}, // []T ∩ []interface{} {[]string{"a", "b", "c"}, []any{"a", "b", "b"}, []string{"a", "b"}}, {[]int{1, 2, 3}, []any{1, 2, 2}, []int{1, 2}}, {[]int8{1, 2, 3}, []any{int8(1), int8(2), int8(2)}, []int8{1, 2}}, {[]int16{1, 2, 3}, []any{int16(1), int16(2), int16(2)}, []int16{1, 2}}, {[]int32{1, 2, 3}, []any{int32(1), int32(2), int32(2)}, []int32{1, 2}}, {[]int64{1, 2, 3}, []any{int64(1), int64(2), int64(2)}, []int64{1, 2}}, {[]float32{1, 2, 3}, []any{float32(1), float32(2), float32(2)}, []float32{1, 2}}, {[]float64{1, 2, 3}, []any{float64(1), float64(2), float64(2)}, []float64{1, 2}}, // Structs {pagesPtr{p1, p4, p2, p3}, pagesPtr{p4, p2, p2}, pagesPtr{p4, p2}}, {pagesVals{p1v, p4v, p2v, p3v}, pagesVals{p1v, p3v, p3v}, pagesVals{p1v, p3v}}, {[]any{p1, p4, p2, p3}, []any{p4, p2, p2}, []any{p4, p2}}, {[]any{p1v, p4v, p2v, p3v}, []any{p1v, p3v, p3v}, []any{p1v, p3v}}, {pagesPtr{p1, p4, p2, p3}, pagesPtr{}, pagesPtr{}}, {pagesVals{}, pagesVals{p1v, p3v, p3v}, pagesVals{}}, {[]any{p1, p4, p2, p3}, []any{}, []any{}}, {[]any{}, []any{p1v, p3v, p3v}, []any{}}, // errors {"not array or slice", []string{"a"}, false}, {[]string{"a"}, "not array or slice", false}, // uncomparable types - #3820 {[]map[int]int{{1: 1}, {2: 2}}, []map[int]int{{2: 2}, {3: 3}}, false}, {[][]int{{1, 1}, {1, 2}}, [][]int{{1, 2}, {1, 2}, {1, 3}}, false}, {[]int{1, 1}, [][]int{{1, 2}, {1, 2}, {1, 3}}, false}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.Intersect(test.l1, test.l2) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil, errMsg) if !reflect.DeepEqual(result, test.expect) { t.Fatalf("[%d] Got\n%v expected\n%v", i, result, test.expect) } } } func TestIsSet(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { a any key any expect bool isErr bool }{ {[]any{1, 2, 3, 5}, 2, true, false}, {[]any{1, 2, 3, 5}, "2", true, false}, {[]any{1, 2, 3, 5}, 2.0, true, false}, {[]any{1, 2, 3, 5}, 22, false, false}, {map[string]any{"a": 1, "b": 2}, "b", true, false}, {map[string]any{"a": 1, "b": 2}, "bc", false, false}, {time.Now(), "Day", false, false}, {nil, "nil", false, false}, {[]any{1, 2, 3, 5}, TstX{}, false, true}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.IsSet(test.a, test.key) if test.isErr { continue } c.Assert(err, qt.IsNil, errMsg) c.Assert(result, qt.Equals, test.expect, errMsg) } } func TestLast(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { limit any seq any expect any }{ {int(2), []string{"a", "b", "c"}, []string{"b", "c"}}, {int32(3), []string{"a", "b"}, []string{"a", "b"}}, {int64(2), []int{100, 200, 300}, []int{200, 300}}, {100, []int{100, 200}, []int{100, 200}}, {"1", []int{100, 200, 300}, []int{300}}, {"0", []int{100, 200, 300}, []int{}}, {"0", []string{"a", "b", "c"}, []string{}}, // errors {int64(-1), []int{100, 200, 300}, false}, {"noint", []int{100, 200, 300}, false}, {1, nil, false}, {nil, []int{100}, false}, {1, t, false}, {1, (*string)(nil), false}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.Last(test.limit, test.seq) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil, errMsg) c.Assert(result, qt.DeepEquals, test.expect, errMsg) } } func TestSeq(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { args []any expect any }{ {[]any{-2, 5}, []int{-2, -1, 0, 1, 2, 3, 4, 5}}, {[]any{1, 2, 4}, []int{1, 3}}, {[]any{1}, []int{1}}, {[]any{3}, []int{1, 2, 3}}, {[]any{3.2}, []int{1, 2, 3}}, {[]any{0}, []int{}}, {[]any{-1}, []int{-1}}, {[]any{-3}, []int{-1, -2, -3}}, {[]any{3, -2}, []int{3, 2, 1, 0, -1, -2}}, {[]any{6, -2, 2}, []int{6, 4, 2}}, // errors {[]any{1, 0, 2}, false}, {[]any{1, -1, 2}, false}, {[]any{2, 1, 1}, false}, {[]any{2, 1, 1, 1}, false}, {[]any{-1000001}, false}, {[]any{}, false}, {[]any{0, -1000000}, false}, {[]any{tstNoStringer{}}, false}, {nil, false}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.Seq(test.args...) if b, ok := test.expect.(bool); ok && !b { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil, errMsg) c.Assert(result, qt.DeepEquals, test.expect, errMsg) } } func TestShuffle(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { seq any success bool }{ {[]string{"a", "b", "c", "d"}, true}, {[]int{100, 200, 300}, true}, {[]int{100, 200, 300}, true}, {[]int{100, 200}, true}, {[]string{"a", "b"}, true}, {[]int{100, 200, 300}, true}, {[]int{100, 200, 300}, true}, {[]int{100}, true}, // errors {nil, false}, {t, false}, {(*string)(nil), false}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.Shuffle(test.seq) if !test.success { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil, errMsg) resultv := reflect.ValueOf(result) seqv := reflect.ValueOf(test.seq) c.Assert(seqv.Len(), qt.Equals, resultv.Len(), errMsg) } } func TestShuffleRandomising(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() // Note that this test can fail with false negative result if the shuffle // of the sequence happens to be the same as the original sequence. However // the probability of the event is 10^-158 which is negligible. seqLen := 100 for _, test := range []struct { seq []int }{ {rand.Perm(seqLen)}, } { result, err := ns.Shuffle(test.seq) resultv := reflect.ValueOf(result) c.Assert(err, qt.IsNil) allSame := true for i, v := range test.seq { allSame = allSame && (resultv.Index(i).Interface() == v) } c.Assert(allSame, qt.Equals, false) } } // Also see tests in commons/collection. func TestSlice(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { args []any expected any }{ {[]any{"a", "b"}, []string{"a", "b"}}, {[]any{}, []any{}}, {[]any{nil}, []any{nil}}, {[]any{5, "b"}, []any{5, "b"}}, {[]any{tstNoStringer{}}, []tstNoStringer{{}}}, } { errMsg := qt.Commentf("[%d] %v", i, test.args) result := ns.Slice(test.args...) c.Assert(result, qt.DeepEquals, test.expected, errMsg) } } func TestUnion(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { l1 any l2 any expect any isErr bool }{ {nil, nil, []any{}, false}, {nil, []string{"a", "b"}, []string{"a", "b"}, false}, {[]string{"a", "b"}, nil, []string{"a", "b"}, false}, // []A ∪ []B {[]string{"1", "2"}, []int{3}, []string{}, false}, {[]int{1, 2}, []string{"1", "2"}, []int{}, false}, // []T ∪ []T {[]string{"a", "b", "c", "c"}, []string{"a", "b", "b"}, []string{"a", "b", "c"}, false}, {[]string{"a", "b"}, []string{"a", "b", "c"}, []string{"a", "b", "c"}, false}, {[]string{"a", "b", "c"}, []string{"d", "e"}, []string{"a", "b", "c", "d", "e"}, false}, {[]string{}, []string{}, []string{}, false}, {[]int{1, 2, 3}, []int{3, 4, 5}, []int{1, 2, 3, 4, 5}, false}, {[]int{1, 2, 3}, []int{1, 2, 3}, []int{1, 2, 3}, false}, {[]int{1, 2, 4}, []int{2, 4}, []int{1, 2, 4}, false}, {[]int{2, 4}, []int{1, 2, 4}, []int{2, 4, 1}, false}, {[]int{1, 2, 4}, []int{3, 6}, []int{1, 2, 4, 3, 6}, false}, {[]float64{2.2, 4.4}, []float64{1.1, 2.2, 4.4}, []float64{2.2, 4.4, 1.1}, false}, {[]any{"a", "b", "c", "c"}, []any{"a", "b", "b"}, []any{"a", "b", "c"}, false}, // []T ∪ []interface{} {[]string{"1", "2"}, []any{"9"}, []string{"1", "2", "9"}, false}, {[]int{2, 4}, []any{1, 2, 4}, []int{2, 4, 1}, false}, {[]int8{2, 4}, []any{int8(1), int8(2), int8(4)}, []int8{2, 4, 1}, false}, {[]int8{2, 4}, []any{1, 2, 4}, []int8{2, 4, 1}, false}, {[]int16{2, 4}, []any{1, 2, 4}, []int16{2, 4, 1}, false}, {[]int32{2, 4}, []any{1, 2, 4}, []int32{2, 4, 1}, false}, {[]int64{2, 4}, []any{1, 2, 4}, []int64{2, 4, 1}, false}, {[]float64{2.2, 4.4}, []any{1.1, 2.2, 4.4}, []float64{2.2, 4.4, 1.1}, false}, {[]float32{2.2, 4.4}, []any{1.1, 2.2, 4.4}, []float32{2.2, 4.4, 1.1}, false}, // []interface{} ∪ []T {[]any{"a", "b", "c", "c"}, []string{"a", "b", "d"}, []any{"a", "b", "c", "d"}, false}, {[]any{}, []string{}, []any{}, false}, {[]any{1, 2}, []int{2, 3}, []any{1, 2, 3}, false}, {[]any{1, 2}, []int8{2, 3}, []any{1, 2, 3}, false}, // 28 {[]any{uint(1), uint(2)}, []uint{2, 3}, []any{uint(1), uint(2), uint(3)}, false}, {[]any{1.1, 2.2}, []float64{2.2, 3.3}, []any{1.1, 2.2, 3.3}, false}, // Structs {pagesPtr{p1, p4}, pagesPtr{p4, p2, p2}, pagesPtr{p1, p4, p2}, false}, {pagesVals{p1v}, pagesVals{p3v, p3v}, pagesVals{p1v, p3v}, false}, {[]any{p1, p4}, []any{p4, p2, p2}, []any{p1, p4, p2}, false}, {[]any{p1v}, []any{p3v, p3v}, []any{p1v, p3v}, false}, // #3686 {[]any{p1v}, []any{}, []any{p1v}, false}, {[]any{}, []any{p1v}, []any{p1v}, false}, {pagesPtr{p1}, pagesPtr{}, pagesPtr{p1}, false}, {pagesVals{p1v}, pagesVals{}, pagesVals{p1v}, false}, {pagesPtr{}, pagesPtr{p1}, pagesPtr{p1}, false}, {pagesVals{}, pagesVals{p1v}, pagesVals{p1v}, false}, // errors {"not array or slice", []string{"a"}, false, true}, {[]string{"a"}, "not array or slice", false, true}, // uncomparable types - #3820 {[]map[string]int{{"K1": 1}}, []map[string]int{{"K2": 2}, {"K2": 2}}, false, true}, {[][]int{{1, 1}, {1, 2}}, [][]int{{2, 1}, {2, 2}}, false, true}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.Union(test.l1, test.l2) if test.isErr { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil, errMsg) if !reflect.DeepEqual(result, test.expect) { t.Fatalf("[%d] Got\n%v expected\n%v", i, result, test.expect) } } } func TestUniq(t *testing.T) { t.Parallel() c := qt.New(t) ns := newNs() for i, test := range []struct { l any expect any isErr bool }{ {[]string{"a", "b", "c"}, []string{"a", "b", "c"}, false}, {[]string{"a", "b", "c", "c"}, []string{"a", "b", "c"}, false}, {[]string{"a", "b", "b", "c"}, []string{"a", "b", "c"}, false}, {[]string{"a", "b", "c", "b"}, []string{"a", "b", "c"}, false}, {[]int{1, 2, 3}, []int{1, 2, 3}, false}, {[]int{1, 2, 3, 3}, []int{1, 2, 3}, false}, {[]int{1, 2, 2, 3}, []int{1, 2, 3}, false}, {[]int{1, 2, 3, 2}, []int{1, 2, 3}, false}, {[4]int{1, 2, 3, 2}, []int{1, 2, 3}, false}, {nil, make([]any, 0), false}, // Pointers {pagesPtr{p1, p2, p3, p2}, pagesPtr{p1, p2, p3}, false}, {pagesPtr{}, pagesPtr{}, false}, // Structs {pagesVals{p3v, p2v, p3v, p2v}, pagesVals{p3v, p2v}, false}, // not Comparable(), use hashstructure {[]map[string]int{ {"K1": 1}, {"K2": 2}, {"K1": 1}, {"K2": 1}, }, []map[string]int{ {"K1": 1}, {"K2": 2}, {"K2": 1}, }, false}, // should fail {1, 1, true}, {"foo", "fo", true}, } { errMsg := qt.Commentf("[%d] %v", i, test) result, err := ns.Uniq(test.l) if test.isErr { c.Assert(err, qt.Not(qt.IsNil), errMsg) continue } c.Assert(err, qt.IsNil, errMsg) c.Assert(result, qt.DeepEquals, test.expect, errMsg) } } func TestD(t *testing.T) { t.Parallel() ns := newNs() const ( errNumberOfRequestedValuesRegexPattern = `.*the number of requested values.*` errMaximumRequestedValueRegexPattern = `.*the maximum requested value.*` errSeedValueRegexPattern = `.*the seed value.*` ) tests := []struct { name string seed any n any hi any wantResult []int wantErrText string }{ // n <= hi {"seed_eq_42", 42, 5, 100, []int{24, 34, 66, 82, 96}, ""}, {"seed_eq_31", 31, 5, 100, []int{12, 37, 38, 69, 98}, ""}, {"n_lt_hi", 42, 9, 10, []int{0, 1, 2, 3, 4, 6, 7, 8, 9}, ""}, {"n_eq_hi", 42, 10, 10, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, ""}, {"hi_eq_max_size", 42, 5, maxSeqSize, []int{240121, 347230, 669726, 829701, 957989}, ""}, // n > hi {"n_gt_hi", 42, 11, 10, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, ""}, // zero values {"seed_eq_0", 0, 5, 100, []int{0, 2, 29, 50, 72}, ""}, {"n_eq_0", 42, 0, 100, []int{}, ""}, {"hi_eq_0", 42, 5, 0, []int{}, ""}, // errors: values < 0 {"seed_lt_0", -42, 5, 100, nil, errSeedValueRegexPattern}, {"n_lt_0", 42, -1, 100, nil, errNumberOfRequestedValuesRegexPattern}, {"hi_lt_0", 42, 5, -100, nil, errMaximumRequestedValueRegexPattern}, // errors: values that can't be cast to int {"seed_invalid_type", "foo", 5, 100, nil, errSeedValueRegexPattern}, {"n_invalid_type", 42, "bar", 100, nil, errNumberOfRequestedValuesRegexPattern}, {"hi_invalid_type", 42, 5, "baz", nil, errMaximumRequestedValueRegexPattern}, // errors: values that exceed maxSeqSize {"n_gt_max_size", 42, maxSeqSize + 1, 10, nil, errNumberOfRequestedValuesRegexPattern}, {"hi_gt_max_size", 42, 5, maxSeqSize + 1, nil, errMaximumRequestedValueRegexPattern}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() c := qt.New(t) got, err := ns.D(tt.seed, tt.n, tt.hi) if tt.wantErrText != "" { c.Assert(err, qt.ErrorMatches, tt.wantErrText, qt.Commentf("n=%d, hi=%d", tt.n, tt.hi)) c.Assert(got, qt.IsNil, qt.Commentf("Expected nil result on error")) return } c.Assert(err, qt.IsNil, qt.Commentf("Did not expect an error, but got: %v", err)) c.Assert(got, qt.DeepEquals, tt.wantResult) }) } } func BenchmarkD2(b *testing.B) { ns := newNs() runBenchmark := func(seed, n, max any) { name := fmt.Sprintf("n=%d,max=%d", n, max) b.Run(name, func(b *testing.B) { for b.Loop() { _, _ = ns.D(seed, n, max) } }) } runBenchmark(32, 5, 100) runBenchmark(32, 50, 1000) runBenchmark(32, 10, 10000) runBenchmark(32, 500, 10000) runBenchmark(32, 10, 500000) runBenchmark(32, 5000, 500000) } func (x *TstX) TstRp() string { return "r" + x.A } func (x TstX) TstRv() string { return "r" + x.B } func (x TstX) TstRv2() string { return "r" + x.B } //lint:ignore U1000 reflect test func (x TstX) unexportedMethod() string { return x.unexported } func (x TstX) MethodWithArg(s string) string { return s } func (x TstX) MethodReturnNothing() {} func (x TstX) MethodReturnErrorOnly() error { return errors.New("some error occurred") } func (x TstX) MethodReturnTwoValues() (string, string) { return "foo", "bar" } func (x TstX) MethodReturnValueWithError() (string, error) { return "", errors.New("some error occurred") } func (x TstX) String() string { return fmt.Sprintf("A: %s, B: %s", x.A, x.B) } type TstX struct { A, B string unexported string //lint:ignore U1000 reflect test } type TstParams struct { params maps.Params } func (x TstParams) Params() maps.Params { return x.params } type TstXIHolder struct { XI TstXI } // Partially implemented by the TstX struct. type TstXI interface { TstRv2() string } func ToTstXIs(slice any) []TstXI { s := reflect.ValueOf(slice) if s.Kind() != reflect.Slice { return nil } tis := make([]TstXI, s.Len()) for i := range s.Len() { tsti, ok := s.Index(i).Interface().(TstXI) if !ok { return nil } tis[i] = tsti } return tis } func newNs() *Namespace { return New(testconfig.GetTestDeps(nil, nil)) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/querify.go
tpl/collections/querify.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package collections import ( "errors" "net/url" "github.com/gohugoio/hugo/common/maps" "github.com/spf13/cast" ) var ( errWrongArgStructure = errors.New("expected a map, a slice with an even number of elements, or an even number of scalar values, and each key must be a string") errKeyIsEmptyString = errors.New("one of the keys is an empty string") ) // Querify returns a URL query string composed of the given key-value pairs, // encoded and sorted by key. func (ns *Namespace) Querify(params ...any) (string, error) { if len(params) == 0 { return "", nil } if len(params) == 1 { switch v := params[0].(type) { case map[string]any: // created with collections.Dictionary return mapToQueryString(v) case maps.Params: // site configuration or page parameters return mapToQueryString(v) case []string: return stringSliceToQueryString(v) case []any: s, err := interfaceSliceToStringSlice(v) if err != nil { return "", err } return stringSliceToQueryString(s) default: return "", errWrongArgStructure } } if len(params)%2 != 0 { return "", errWrongArgStructure } s, err := interfaceSliceToStringSlice(params) if err != nil { return "", err } return stringSliceToQueryString(s) } // mapToQueryString returns a URL query string derived from the given string // map, encoded and sorted by key. The function returns an error if it cannot // convert an element value to a string. func mapToQueryString[T map[string]any | maps.Params](m T) (string, error) { if len(m) == 0 { return "", nil } qs := url.Values{} for k, v := range m { if len(k) == 0 { return "", errKeyIsEmptyString } vs, err := cast.ToStringE(v) if err != nil { return "", err } qs.Add(k, vs) } return qs.Encode(), nil } // sliceToQueryString returns a URL query string derived from the given slice // of strings, encoded and sorted by key. The function returns an error if // there are an odd number of elements. func stringSliceToQueryString(s []string) (string, error) { if len(s) == 0 { return "", nil } if len(s)%2 != 0 { return "", errWrongArgStructure } qs := url.Values{} for i := 0; i < len(s); i += 2 { if len(s[i]) == 0 { return "", errKeyIsEmptyString } qs.Add(s[i], s[i+1]) } return qs.Encode(), nil } // interfaceSliceToStringSlice converts a slice of interfaces to a slice of // strings, returning an error if it cannot convert an element to a string. func interfaceSliceToStringSlice(s []any) ([]string, error) { if len(s) == 0 { return []string{}, nil } ss := make([]string, 0, len(s)) for _, v := range s { vs, err := cast.ToStringE(v) if err != nil { return []string{}, err } ss = append(ss, vs) } return ss, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/collections/where_test.go
tpl/collections/where_test.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" "fmt" "html/template" "math/rand" "reflect" "strings" "testing" "time" "github.com/gohugoio/hugo/common/maps" ) func TestWhere(t *testing.T) { t.Parallel() ns := newNs() type Mid struct { Tst TstX } d1 := time.Now() d2 := d1.Add(1 * time.Hour) d3 := d2.Add(1 * time.Hour) d4 := d3.Add(1 * time.Hour) d5 := d4.Add(1 * time.Hour) d6 := d5.Add(1 * time.Hour) type testt struct { seq any key any op string match any expect any } createTestVariants := func(test testt) []testt { testVariants := []testt{test} if islice := ToTstXIs(test.seq); islice != nil { variant := test variant.seq = islice expect := ToTstXIs(test.expect) if expect != nil { variant.expect = expect } testVariants = append(testVariants, variant) } return testVariants } for i, test := range []testt{ { seq: []map[int]string{ {1: "a", 2: "m"}, {1: "c", 2: "d"}, {1: "e", 3: "m"}, }, key: 2, match: "m", expect: []map[int]string{ {1: "a", 2: "m"}, }, }, { seq: []map[string]int{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4}, }, key: "b", match: 4, expect: []map[string]int{ {"a": 3, "b": 4}, }, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4}, }, key: "b", match: 4.0, expect: []map[string]float64{{"a": 3, "b": 4}}, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4}, }, key: "b", match: 4.0, op: "!=", expect: []map[string]float64{{"a": 1, "b": 2}, {"a": 5, "x": 4}}, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4}, }, key: "b", match: 4.0, op: "<", expect: []map[string]float64{{"a": 1, "b": 2}}, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4}, }, key: "b", match: 4, op: "<", expect: []map[string]float64{{"a": 1, "b": 2}}, }, { seq: []map[string]int{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4}, }, key: "b", match: 4.0, op: "<", expect: []map[string]int{{"a": 1, "b": 2}}, }, { seq: []map[string]int{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4}, }, key: "b", match: 4.2, op: "<", expect: []map[string]int{{"a": 1, "b": 2}, {"a": 3, "b": 4}}, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4}, }, key: "b", match: 4.0, op: "<=", expect: []map[string]float64{{"a": 1, "b": 2}, {"a": 3, "b": 4}}, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 3}, {"a": 5, "x": 4}, }, key: "b", match: 2.0, op: ">", expect: []map[string]float64{{"a": 3, "b": 3}}, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 3}, {"a": 5, "x": 4}, }, key: "b", match: 2.0, op: ">=", expect: []map[string]float64{{"a": 1, "b": 2}, {"a": 3, "b": 3}}, }, // Issue #8353 // String type mismatch. { seq: []map[string]any{ {"a": "1", "b": "2"}, {"a": "3", "b": template.HTML("4")}, {"a": "5", "x": "4"}, }, key: "b", match: "4", expect: []map[string]any{ {"a": "3", "b": template.HTML("4")}, }, }, { seq: []TstX{ {A: "a", B: "b"}, {A: "c", B: "d"}, {A: "e", B: "f"}, }, key: "B", match: "f", expect: []TstX{ {A: "e", B: "f"}, }, }, { seq: []*map[int]string{ {1: "a", 2: "m"}, {1: "c", 2: "d"}, {1: "e", 3: "m"}, }, key: 2, match: "m", expect: []*map[int]string{ {1: "a", 2: "m"}, }, }, // Case insensitive maps.Params // Slice of structs { seq: []TstParams{{params: maps.Params{"i": 0, "color": "indigo"}}, {params: maps.Params{"i": 1, "color": "blue"}}, {params: maps.Params{"i": 2, "color": "green"}}, {params: maps.Params{"i": 3, "color": "blue"}}}, key: ".Params.COLOR", match: "blue", expect: []TstParams{{params: maps.Params{"i": 1, "color": "blue"}}, {params: maps.Params{"i": 3, "color": "blue"}}}, }, { seq: []TstParams{{params: maps.Params{"nested": map[string]any{"color": "indigo"}}}, {params: maps.Params{"nested": map[string]any{"color": "blue"}}}}, key: ".Params.NEsTED.COLOR", match: "blue", expect: []TstParams{{params: maps.Params{"nested": map[string]any{"color": "blue"}}}}, }, { seq: []TstParams{{params: maps.Params{"i": 0, "color": "indigo"}}, {params: maps.Params{"i": 1, "color": "blue"}}, {params: maps.Params{"i": 2, "color": "green"}}, {params: maps.Params{"i": 3, "color": "blue"}}}, key: ".Params", match: "blue", expect: []TstParams{}, }, // Slice of maps { seq: []maps.Params{ {"a": "a1", "b": "b1"}, {"a": "a2", "b": "b2"}, }, key: "B", match: "b2", expect: []maps.Params{ {"a": "a2", "b": "b2"}, }, }, { seq: []maps.Params{ { "a": map[string]any{ "b": "b1", }, }, { "a": map[string]any{ "b": "b2", }, }, }, key: "A.B", match: "b2", expect: []maps.Params{ { "a": map[string]any{ "b": "b2", }, }, }, }, { seq: []*TstX{ {A: "a", B: "b"}, {A: "c", B: "d"}, {A: "e", B: "f"}, }, key: "B", match: "f", expect: []*TstX{ {A: "e", B: "f"}, }, }, { seq: []*TstX{ {A: "a", B: "b"}, {A: "c", B: "d"}, {A: "e", B: "c"}, }, key: "TstRp", match: "rc", expect: []*TstX{ {A: "c", B: "d"}, }, }, { seq: []TstX{ {A: "a", B: "b"}, {A: "c", B: "d"}, {A: "e", B: "c"}, }, key: "TstRv", match: "rc", expect: []TstX{ {A: "e", B: "c"}, }, }, { seq: []map[string]TstX{ {"foo": TstX{A: "a", B: "b"}}, {"foo": TstX{A: "c", B: "d"}}, {"foo": TstX{A: "e", B: "f"}}, }, key: "foo.B", match: "d", expect: []map[string]TstX{ {"foo": TstX{A: "c", B: "d"}}, }, }, { seq: []map[string]TstX{ {"baz": TstX{A: "a", B: "b"}}, {"foo": TstX{A: "a", B: "b"}}, {"foo": TstX{A: "c", B: "d"}}, {"foo": TstX{A: "e", B: "f"}}, }, key: "foo.B", match: "d", expect: []map[string]TstX{ {"foo": TstX{A: "c", B: "d"}}, }, }, { seq: []map[string]TstX{ {"foo": TstX{A: "a", B: "b"}}, {"foo": TstX{A: "c", B: "d"}}, {"foo": TstX{A: "e", B: "f"}}, }, key: ".foo.B", match: "d", expect: []map[string]TstX{ {"foo": TstX{A: "c", B: "d"}}, }, }, { seq: []map[string]TstX{ {"foo": TstX{A: "a", B: "b"}}, {"foo": TstX{A: "c", B: "d"}}, {"foo": TstX{A: "e", B: "f"}}, }, key: "foo.TstRv", match: "rd", expect: []map[string]TstX{ {"foo": TstX{A: "c", B: "d"}}, }, }, { seq: []map[string]*TstX{ {"foo": &TstX{A: "a", B: "b"}}, {"foo": &TstX{A: "c", B: "d"}}, {"foo": &TstX{A: "e", B: "f"}}, }, key: "foo.TstRp", match: "rc", expect: []map[string]*TstX{ {"foo": &TstX{A: "c", B: "d"}}, }, }, { seq: []TstXIHolder{ {&TstX{A: "a", B: "b"}}, {&TstX{A: "c", B: "d"}}, {&TstX{A: "e", B: "f"}}, }, key: "XI.TstRp", match: "rc", expect: []TstXIHolder{ {&TstX{A: "c", B: "d"}}, }, }, { seq: []TstXIHolder{ {&TstX{A: "a", B: "b"}}, {&TstX{A: "c", B: "d"}}, {&TstX{A: "e", B: "f"}}, }, key: "XI.A", match: "e", expect: []TstXIHolder{ {&TstX{A: "e", B: "f"}}, }, }, { seq: []map[string]Mid{ {"foo": Mid{Tst: TstX{A: "a", B: "b"}}}, {"foo": Mid{Tst: TstX{A: "c", B: "d"}}}, {"foo": Mid{Tst: TstX{A: "e", B: "f"}}}, }, key: "foo.Tst.B", match: "d", expect: []map[string]Mid{ {"foo": Mid{Tst: TstX{A: "c", B: "d"}}}, }, }, { seq: []map[string]Mid{ {"foo": Mid{Tst: TstX{A: "a", B: "b"}}}, {"foo": Mid{Tst: TstX{A: "c", B: "d"}}}, {"foo": Mid{Tst: TstX{A: "e", B: "f"}}}, }, key: "foo.Tst.TstRv", match: "rd", expect: []map[string]Mid{ {"foo": Mid{Tst: TstX{A: "c", B: "d"}}}, }, }, { seq: []map[string]*Mid{ {"foo": &Mid{Tst: TstX{A: "a", B: "b"}}}, {"foo": &Mid{Tst: TstX{A: "c", B: "d"}}}, {"foo": &Mid{Tst: TstX{A: "e", B: "f"}}}, }, key: "foo.Tst.TstRp", match: "rc", expect: []map[string]*Mid{ {"foo": &Mid{Tst: TstX{A: "c", B: "d"}}}, }, }, { seq: []map[string]int{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}, }, key: "b", op: ">", match: 3, expect: []map[string]int{ {"a": 3, "b": 4}, {"a": 5, "b": 6}, }, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}, }, key: "b", op: ">", match: 3.0, expect: []map[string]float64{ {"a": 3, "b": 4}, {"a": 5, "b": 6}, }, }, { seq: []TstX{ {A: "a", B: "b"}, {A: "c", B: "d"}, {A: "e", B: "f"}, }, key: "B", op: "!=", match: "f", expect: []TstX{ {A: "a", B: "b"}, {A: "c", B: "d"}, }, }, { seq: []map[string]int{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}, }, key: "b", op: "in", match: []int{3, 4, 5}, expect: []map[string]int{ {"a": 3, "b": 4}, }, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}, }, key: "b", op: "in", match: []float64{3, 4, 5}, expect: []map[string]float64{ {"a": 3, "b": 4}, }, }, { seq: []map[string][]string{ {"a": []string{"A", "B", "C"}, "b": []string{"D", "E", "F"}}, {"a": []string{"G", "H", "I"}, "b": []string{"J", "K", "L"}}, {"a": []string{"M", "N", "O"}, "b": []string{"P", "Q", "R"}}, }, key: "b", op: "intersect", match: []string{"D", "P", "Q"}, expect: []map[string][]string{ {"a": []string{"A", "B", "C"}, "b": []string{"D", "E", "F"}}, {"a": []string{"M", "N", "O"}, "b": []string{"P", "Q", "R"}}, }, }, { seq: []map[string][]int{ {"a": []int{1, 2, 3}, "b": []int{4, 5, 6}}, {"a": []int{7, 8, 9}, "b": []int{10, 11, 12}}, {"a": []int{13, 14, 15}, "b": []int{16, 17, 18}}, }, key: "b", op: "intersect", match: []int{4, 10, 12}, expect: []map[string][]int{ {"a": []int{1, 2, 3}, "b": []int{4, 5, 6}}, {"a": []int{7, 8, 9}, "b": []int{10, 11, 12}}, }, }, { seq: []map[string][]int8{ {"a": []int8{1, 2, 3}, "b": []int8{4, 5, 6}}, {"a": []int8{7, 8, 9}, "b": []int8{10, 11, 12}}, {"a": []int8{13, 14, 15}, "b": []int8{16, 17, 18}}, }, key: "b", op: "intersect", match: []int8{4, 10, 12}, expect: []map[string][]int8{ {"a": []int8{1, 2, 3}, "b": []int8{4, 5, 6}}, {"a": []int8{7, 8, 9}, "b": []int8{10, 11, 12}}, }, }, { seq: []map[string][]int16{ {"a": []int16{1, 2, 3}, "b": []int16{4, 5, 6}}, {"a": []int16{7, 8, 9}, "b": []int16{10, 11, 12}}, {"a": []int16{13, 14, 15}, "b": []int16{16, 17, 18}}, }, key: "b", op: "intersect", match: []int16{4, 10, 12}, expect: []map[string][]int16{ {"a": []int16{1, 2, 3}, "b": []int16{4, 5, 6}}, {"a": []int16{7, 8, 9}, "b": []int16{10, 11, 12}}, }, }, { seq: []map[string][]int32{ {"a": []int32{1, 2, 3}, "b": []int32{4, 5, 6}}, {"a": []int32{7, 8, 9}, "b": []int32{10, 11, 12}}, {"a": []int32{13, 14, 15}, "b": []int32{16, 17, 18}}, }, key: "b", op: "intersect", match: []int32{4, 10, 12}, expect: []map[string][]int32{ {"a": []int32{1, 2, 3}, "b": []int32{4, 5, 6}}, {"a": []int32{7, 8, 9}, "b": []int32{10, 11, 12}}, }, }, { seq: []map[string][]int64{ {"a": []int64{1, 2, 3}, "b": []int64{4, 5, 6}}, {"a": []int64{7, 8, 9}, "b": []int64{10, 11, 12}}, {"a": []int64{13, 14, 15}, "b": []int64{16, 17, 18}}, }, key: "b", op: "intersect", match: []int64{4, 10, 12}, expect: []map[string][]int64{ {"a": []int64{1, 2, 3}, "b": []int64{4, 5, 6}}, {"a": []int64{7, 8, 9}, "b": []int64{10, 11, 12}}, }, }, { seq: []map[string][]float32{ {"a": []float32{1.0, 2.0, 3.0}, "b": []float32{4.0, 5.0, 6.0}}, {"a": []float32{7.0, 8.0, 9.0}, "b": []float32{10.0, 11.0, 12.0}}, {"a": []float32{13.0, 14.0, 15.0}, "b": []float32{16.0, 17.0, 18.0}}, }, key: "b", op: "intersect", match: []float32{4, 10, 12}, expect: []map[string][]float32{ {"a": []float32{1.0, 2.0, 3.0}, "b": []float32{4.0, 5.0, 6.0}}, {"a": []float32{7.0, 8.0, 9.0}, "b": []float32{10.0, 11.0, 12.0}}, }, }, { seq: []map[string][]float64{ {"a": []float64{1.0, 2.0, 3.0}, "b": []float64{4.0, 5.0, 6.0}}, {"a": []float64{7.0, 8.0, 9.0}, "b": []float64{10.0, 11.0, 12.0}}, {"a": []float64{13.0, 14.0, 15.0}, "b": []float64{16.0, 17.0, 18.0}}, }, key: "b", op: "intersect", match: []float64{4, 10, 12}, expect: []map[string][]float64{ {"a": []float64{1.0, 2.0, 3.0}, "b": []float64{4.0, 5.0, 6.0}}, {"a": []float64{7.0, 8.0, 9.0}, "b": []float64{10.0, 11.0, 12.0}}, }, }, { seq: []map[string]int{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}, }, key: "b", op: "in", match: ns.Slice(3, 4, 5), expect: []map[string]int{ {"a": 3, "b": 4}, }, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}, }, key: "b", op: "in", match: ns.Slice(3.0, 4.0, 5.0), expect: []map[string]float64{ {"a": 3, "b": 4}, }, }, { seq: []map[string]time.Time{ {"a": d1, "b": d2}, {"a": d3, "b": d4}, {"a": d5, "b": d6}, }, key: "b", op: "in", match: ns.Slice(d3, d4, d5), expect: []map[string]time.Time{ {"a": d3, "b": d4}, }, }, { seq: []TstX{ {A: "a", B: "b"}, {A: "c", B: "d"}, {A: "e", B: "f"}, }, key: "B", op: "not in", match: []string{"c", "d", "e"}, expect: []TstX{ {A: "a", B: "b"}, {A: "e", B: "f"}, }, }, { seq: []TstX{ {A: "a", B: "b"}, {A: "c", B: "d"}, {A: "e", B: "f"}, }, key: "B", op: "not in", match: ns.Slice("c", t, "d", "e"), expect: []TstX{ {A: "a", B: "b"}, {A: "e", B: "f"}, }, }, { seq: []map[string]int{ {"a": 1, "b": 2}, {"a": 3}, {"a": 5, "b": 6}, }, key: "b", op: "", match: nil, expect: []map[string]int{ {"a": 3}, }, }, { seq: []map[string]int{ {"a": 1, "b": 2}, {"a": 3}, {"a": 5, "b": 6}, }, key: "b", op: "!=", match: nil, expect: []map[string]int{ {"a": 1, "b": 2}, {"a": 5, "b": 6}, }, }, { seq: []map[string]int{ {"a": 1, "b": 2}, {"a": 3}, {"a": 5, "b": 6}, }, key: "b", op: ">", match: nil, expect: []map[string]int{}, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3}, {"a": 5, "b": 6}, }, key: "b", op: "", match: nil, expect: []map[string]float64{ {"a": 3}, }, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3}, {"a": 5, "b": 6}, }, key: "b", op: "!=", match: nil, expect: []map[string]float64{ {"a": 1, "b": 2}, {"a": 5, "b": 6}, }, }, { seq: []map[string]float64{ {"a": 1, "b": 2}, {"a": 3}, {"a": 5, "b": 6}, }, key: "b", op: ">", match: nil, expect: []map[string]float64{}, }, { seq: []map[string]bool{ {"a": true, "b": false}, {"c": true, "b": true}, {"d": true, "b": false}, }, key: "b", op: "", match: true, expect: []map[string]bool{ {"c": true, "b": true}, }, }, { seq: []map[string]bool{ {"a": true, "b": false}, {"c": true, "b": true}, {"d": true, "b": false}, }, key: "b", op: "!=", match: true, expect: []map[string]bool{ {"a": true, "b": false}, {"d": true, "b": false}, }, }, { seq: []map[string]bool{ {"a": true, "b": false}, {"c": true, "b": true}, {"d": true, "b": false}, }, key: "b", op: ">", match: false, expect: []map[string]bool{}, }, { seq: []map[string]bool{ {"a": true, "b": false}, {"c": true, "b": true}, {"d": true, "b": false}, }, key: "b.z", match: false, expect: []map[string]bool{}, }, {seq: (*[]TstX)(nil), key: "A", match: "a", expect: false}, {seq: TstX{A: "a", B: "b"}, key: "A", match: "a", expect: false}, {seq: []map[string]*TstX{{"foo": nil}}, key: "foo.B", match: "d", expect: []map[string]*TstX{}}, {seq: []map[string]*TstX{{"foo": nil}}, key: "foo.B.Z", match: "d", expect: []map[string]*TstX{}}, { seq: []TstX{ {A: "a", B: "b"}, {A: "c", B: "d"}, {A: "e", B: "f"}, }, key: "B", op: "op", match: "f", expect: false, }, { seq: map[string]any{ "foo": []any{map[any]any{"a": 1, "b": 2}}, "bar": []any{map[any]any{"a": 3, "b": 4}}, "zap": []any{map[any]any{"a": 5, "b": 6}}, }, key: "b", op: "in", match: ns.Slice(3, 4, 5), expect: map[string]any{ "bar": []any{map[any]any{"a": 3, "b": 4}}, }, }, { seq: map[string]any{ "foo": []any{map[any]any{"a": 1, "b": 2}}, "bar": []any{map[any]any{"a": 3, "b": 4}}, "zap": []any{map[any]any{"a": 5, "b": 6}}, }, key: "b", op: ">", match: 3, expect: map[string]any{ "bar": []any{map[any]any{"a": 3, "b": 4}}, "zap": []any{map[any]any{"a": 5, "b": 6}}, }, }, { seq: map[string]any{ "foo": []any{maps.Params{"a": 1, "b": 2}}, "bar": []any{maps.Params{"a": 3, "b": 4}}, "zap": []any{maps.Params{"a": 5, "b": 6}}, }, key: "B", op: ">", match: 3, expect: map[string]any{ "bar": []any{maps.Params{"a": 3, "b": 4}}, "zap": []any{maps.Params{"a": 5, "b": 6}}, }, }, } { testVariants := createTestVariants(test) for j, test := range testVariants { name := fmt.Sprintf("%d/%d %T %s %s", i, j, test.seq, test.op, test.key) name = strings.ReplaceAll(name, "[]", "slice-of-") t.Run(name, func(t *testing.T) { var results any var err error if len(test.op) > 0 { results, err = ns.Where(context.Background(), test.seq, test.key, test.op, test.match) } else { results, err = ns.Where(context.Background(), test.seq, test.key, test.match) } if b, ok := test.expect.(bool); ok && !b { if err == nil { t.Fatalf("[%d] Where didn't return an expected error", i) } } else { if err != nil { t.Fatalf("[%d] failed: %s", i, err) } if !reflect.DeepEqual(results, test.expect) { t.Fatalf("Where clause matching %v with %v in seq %v (%T),\ngot\n%v (%T) but expected\n%v (%T)", test.key, test.match, test.seq, test.seq, results, results, test.expect, test.expect) } } }) } } var err error _, err = ns.Where(context.Background(), map[string]int{"a": 1, "b": 2}, "a", []byte("="), 1) if err == nil { t.Errorf("Where called with none string op value didn't return an expected error") } _, err = ns.Where(context.Background(), map[string]int{"a": 1, "b": 2}, "a", []byte("="), 1, 2) if err == nil { t.Errorf("Where called with more than two variable arguments didn't return an expected error") } _, err = ns.Where(context.Background(), map[string]int{"a": 1, "b": 2}, "a") if err == nil { t.Errorf("Where called with no variable arguments didn't return an expected error") } } func TestCheckCondition(t *testing.T) { t.Parallel() ns := newNs() type expect struct { result bool isError bool } for i, test := range []struct { value reflect.Value match reflect.Value op string expect }{ {reflect.ValueOf(123), reflect.ValueOf(123), "", expect{true, false}}, {reflect.ValueOf("foo"), reflect.ValueOf("foo"), "", expect{true, false}}, { reflect.ValueOf(time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC)), reflect.ValueOf(time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC)), "", expect{true, false}, }, {reflect.ValueOf(true), reflect.ValueOf(true), "", expect{true, false}}, {reflect.ValueOf(nil), reflect.ValueOf(nil), "", expect{true, false}}, {reflect.ValueOf(123), reflect.ValueOf(456), "!=", expect{true, false}}, {reflect.ValueOf("foo"), reflect.ValueOf("bar"), "!=", expect{true, false}}, { reflect.ValueOf(time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC)), reflect.ValueOf(time.Date(2015, time.April, 26, 19, 18, 56, 12345, time.UTC)), "!=", expect{true, false}, }, {reflect.ValueOf(true), reflect.ValueOf(false), "!=", expect{true, false}}, {reflect.ValueOf(123), reflect.ValueOf(nil), "!=", expect{true, false}}, {reflect.ValueOf(456), reflect.ValueOf(123), ">=", expect{true, false}}, {reflect.ValueOf("foo"), reflect.ValueOf("bar"), ">=", expect{true, false}}, { reflect.ValueOf(time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC)), reflect.ValueOf(time.Date(2015, time.April, 26, 19, 18, 56, 12345, time.UTC)), ">=", expect{true, false}, }, {reflect.ValueOf(456), reflect.ValueOf(123), ">", expect{true, false}}, {reflect.ValueOf("foo"), reflect.ValueOf("bar"), ">", expect{true, false}}, { reflect.ValueOf(time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC)), reflect.ValueOf(time.Date(2015, time.April, 26, 19, 18, 56, 12345, time.UTC)), ">", expect{true, false}, }, {reflect.ValueOf(123), reflect.ValueOf(456), "<=", expect{true, false}}, {reflect.ValueOf("bar"), reflect.ValueOf("foo"), "<=", expect{true, false}}, { reflect.ValueOf(time.Date(2015, time.April, 26, 19, 18, 56, 12345, time.UTC)), reflect.ValueOf(time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC)), "<=", expect{true, false}, }, {reflect.ValueOf(123), reflect.ValueOf(456), "<", expect{true, false}}, {reflect.ValueOf("bar"), reflect.ValueOf("foo"), "<", expect{true, false}}, { reflect.ValueOf(time.Date(2015, time.April, 26, 19, 18, 56, 12345, time.UTC)), reflect.ValueOf(time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC)), "<", expect{true, false}, }, {reflect.ValueOf(123), reflect.ValueOf([]int{123, 45, 678}), "in", expect{true, false}}, {reflect.ValueOf("foo"), reflect.ValueOf([]string{"foo", "bar", "baz"}), "in", expect{true, false}}, { reflect.ValueOf(time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC)), reflect.ValueOf([]time.Time{ time.Date(2015, time.April, 26, 19, 18, 56, 12345, time.UTC), time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC), time.Date(2015, time.June, 26, 19, 18, 56, 12345, time.UTC), }), "in", expect{true, false}, }, {reflect.ValueOf(123), reflect.ValueOf([]int{45, 678}), "not in", expect{true, false}}, {reflect.ValueOf(123), reflect.ValueOf([]int{}), "not in", expect{true, false}}, {reflect.ValueOf("foo"), reflect.ValueOf([]string{"bar", "baz"}), "not in", expect{true, false}}, { reflect.ValueOf(time.Date(2015, time.May, 26, 19, 18, 56, 12345, time.UTC)), reflect.ValueOf([]time.Time{ time.Date(2015, time.February, 26, 19, 18, 56, 12345, time.UTC), time.Date(2015, time.March, 26, 19, 18, 56, 12345, time.UTC), time.Date(2015, time.April, 26, 19, 18, 56, 12345, time.UTC), }), "not in", expect{true, false}, }, {reflect.ValueOf("foo"), reflect.ValueOf("bar-foo-baz"), "in", expect{true, false}}, {reflect.ValueOf("foo"), reflect.ValueOf("bar--baz"), "not in", expect{true, false}}, {reflect.Value{}, reflect.ValueOf("foo"), "", expect{false, false}}, {reflect.ValueOf("foo"), reflect.Value{}, "", expect{false, false}}, {reflect.ValueOf((*TstX)(nil)), reflect.ValueOf("foo"), "", expect{false, false}}, {reflect.ValueOf("foo"), reflect.ValueOf((*TstX)(nil)), "", expect{false, false}}, {reflect.ValueOf(true), reflect.ValueOf("foo"), "", expect{false, false}}, {reflect.ValueOf("foo"), reflect.ValueOf(true), "", expect{false, false}}, {reflect.ValueOf("foo"), reflect.ValueOf(map[int]string{}), "", expect{false, false}}, {reflect.ValueOf("foo"), reflect.ValueOf([]int{1, 2}), "", expect{false, false}}, {reflect.ValueOf((*TstX)(nil)), reflect.ValueOf((*TstX)(nil)), ">", expect{false, false}}, {reflect.ValueOf(true), reflect.ValueOf(false), ">", expect{false, false}}, {reflect.ValueOf(123), reflect.ValueOf([]int{}), "in", expect{false, false}}, {reflect.ValueOf(123), reflect.ValueOf(123), "op", expect{false, true}}, // Issue #3718 {reflect.ValueOf([]any{"a"}), reflect.ValueOf([]string{"a", "b"}), "intersect", expect{true, false}}, {reflect.ValueOf([]string{"a"}), reflect.ValueOf([]any{"a", "b"}), "intersect", expect{true, false}}, {reflect.ValueOf([]any{1, 2}), reflect.ValueOf([]int{1}), "intersect", expect{true, false}}, {reflect.ValueOf([]int{1}), reflect.ValueOf([]any{1, 2}), "intersect", expect{true, false}}, } { result, err := ns.checkCondition(test.value, test.match, test.op) if test.expect.isError { if err == nil { t.Errorf("[%d] checkCondition didn't return an expected error", i) } } else { if err != nil { t.Errorf("[%d] failed: %s", i, err) continue } if result != test.expect.result { t.Errorf("[%d] check condition %v %s %v, got %v but expected %v", i, test.value, test.op, test.match, result, test.expect.result) } } } } func TestEvaluateSubElem(t *testing.T) { t.Parallel() tstx := TstX{A: "foo", B: "bar"} var inner struct { S fmt.Stringer } inner.S = tstx interfaceValue := reflect.ValueOf(&inner).Elem().Field(0) for i, test := range []struct { value reflect.Value key string expect any }{ {reflect.ValueOf(tstx), "A", "foo"}, {reflect.ValueOf(&tstx), "TstRp", "rfoo"}, {reflect.ValueOf(tstx), "TstRv", "rbar"}, //{reflect.ValueOf(map[int]string{1: "foo", 2: "bar"}), 1, "foo"}, {reflect.ValueOf(map[string]string{"key1": "foo", "key2": "bar"}), "key1", "foo"}, {interfaceValue, "String", "A: foo, B: bar"}, {reflect.Value{}, "foo", false}, //{reflect.ValueOf(map[int]string{1: "foo", 2: "bar"}), 1.2, false}, {reflect.ValueOf(tstx), "unexported", false}, {reflect.ValueOf(tstx), "unexportedMethod", false}, {reflect.ValueOf(tstx), "MethodWithArg", false}, {reflect.ValueOf(tstx), "MethodReturnNothing", false}, {reflect.ValueOf(tstx), "MethodReturnErrorOnly", false}, {reflect.ValueOf(tstx), "MethodReturnTwoValues", false}, {reflect.ValueOf(tstx), "MethodReturnValueWithError", false}, {reflect.ValueOf((*TstX)(nil)), "A", false}, {reflect.ValueOf(tstx), "C", false}, {reflect.ValueOf(map[int]string{1: "foo", 2: "bar"}), "1", false}, {reflect.ValueOf([]string{"foo", "bar"}), "1", false}, } { result, err := evaluateSubElem(reflect.ValueOf(context.Background()), test.value, test.key) if b, ok := test.expect.(bool); ok && !b { if err == nil { t.Errorf("[%d] evaluateSubElem didn't return an expected error", i) } } else { if err != nil { t.Errorf("[%d] failed: %s", i, err) continue } if result.Kind() != reflect.String || result.String() != test.expect { t.Errorf("[%d] evaluateSubElem with %v got %v but expected %v", i, test.key, result, test.expect) } } } } func BenchmarkWhereOps(b *testing.B) { ns := newNs() var seq []map[string]string ctx := context.Background() for range 500 { seq = append(seq, map[string]string{"foo": "bar"}) } for range 500 { seq = append(seq, map[string]string{"foo": "baz"}) } // Shuffle the sequence. for i := range seq { j := rand.Intn(i + 1) seq[i], seq[j] = seq[j], seq[i] } // results, err = ns.Where(context.Background(), test.seq, test.key, test.op, test.match) runOps := func(b *testing.B, op, match string) { _, err := ns.Where(ctx, seq, "foo", op, match) if err != nil { b.Fatal(err) } } b.Run("eq", func(b *testing.B) { for b.Loop() { runOps(b, "eq", "bar") } }) b.Run("ne", func(b *testing.B) { for b.Loop() { runOps(b, "ne", "baz") } }) b.Run("like", func(b *testing.B) { for b.Loop() { runOps(b, "like", "^bar") } }) } func BenchmarkWhereMap(b *testing.B) { ns := newNs() seq := map[string]string{} for i := range 1000 { seq[fmt.Sprintf("key%d", i)] = "value" } for b.Loop() { _, err := ns.Where(context.Background(), seq, "key", "eq", "value") if err != nil { b.Fatal(err) } } } func BenchmarkWhereSliceOfStructPointersWithMethod(b *testing.B) { // TstRv2 ns := newNs() seq := []*TstX{} for i := range 1000 { seq = append(seq, &TstX{A: "foo", B: "bar"}) if i%2 == 0 { seq = append(seq, &TstX{A: "baz", B: "qux"}) } } for b.Loop() { _, err := ns.Where(context.Background(), seq, "TstRv2", "eq", "bar") if err != nil { b.Fatal(err) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false