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/common/loggers/handlersmisc.go
common/loggers/handlersmisc.go
// Copyright 2024 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 loggers import ( "fmt" "strings" "sync" "github.com/bep/logg" "github.com/gohugoio/hugo/common/hashing" ) // PanicOnWarningHook panics on warnings. var PanicOnWarningHook = func(e *logg.Entry) error { if e.Level != logg.LevelWarn { return nil } panic(e.Message) } func newLogLevelCounter() *logLevelCounter { return &logLevelCounter{ counters: make(map[logg.Level]int), } } func newLogOnceHandler(threshold logg.Level) *logOnceHandler { return &logOnceHandler{ threshold: threshold, seen: make(map[uint64]bool), } } func newStopHandler(h ...logg.Handler) *stopHandler { return &stopHandler{ handlers: h, } } func newSuppressStatementsHandler(statements map[string]bool) *suppressStatementsHandler { return &suppressStatementsHandler{ statements: statements, } } type logLevelCounter struct { mu sync.RWMutex counters map[logg.Level]int } func (h *logLevelCounter) HandleLog(e *logg.Entry) error { h.mu.Lock() defer h.mu.Unlock() h.counters[e.Level]++ return nil } var errStop = fmt.Errorf("stop") type logOnceHandler struct { threshold logg.Level mu sync.Mutex seen map[uint64]bool } func (h *logOnceHandler) HandleLog(e *logg.Entry) error { if e.Level < h.threshold { // We typically only want to enable this for warnings and above. // The common use case is that many go routines may log the same error. return nil } h.mu.Lock() defer h.mu.Unlock() hash := hashing.HashUint64(e.Level, e.Message, e.Fields) if h.seen[hash] { return errStop } h.seen[hash] = true return nil } func (h *logOnceHandler) reset() { h.mu.Lock() defer h.mu.Unlock() h.seen = make(map[uint64]bool) } type stopHandler struct { handlers []logg.Handler } // HandleLog implements logg.Handler. func (h *stopHandler) HandleLog(e *logg.Entry) error { for _, handler := range h.handlers { if err := handler.HandleLog(e); err != nil { if err == errStop { return nil } return err } } return nil } type suppressStatementsHandler struct { statements map[string]bool } func (h *suppressStatementsHandler) HandleLog(e *logg.Entry) error { for _, field := range e.Fields { if field.Name == FieldNameStatementID { if h.statements[field.Value.(string)] { return errStop } } } return nil } // whiteSpaceTrimmer creates a new log handler that trims whitespace from log messages and string fields. func whiteSpaceTrimmer() logg.Handler { return logg.HandlerFunc(func(e *logg.Entry) error { e.Message = strings.TrimSpace(e.Message) for i, field := range e.Fields { if s, ok := field.Value.(string); ok { e.Fields[i].Value = strings.TrimSpace(s) } } return nil }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/common/rungroup/rungroup.go
common/rungroup/rungroup.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 rungroup import ( "context" "golang.org/x/sync/errgroup" ) // Group is a group of workers that can be used to enqueue work and wait for // them to finish. type Group[T any] interface { Enqueue(T) error Wait() error } type runGroup[T any] struct { ctx context.Context g *errgroup.Group ch chan T } // Config is the configuration for a new Group. type Config[T any] struct { NumWorkers int Handle func(context.Context, T) error } // Run creates a new Group with the given configuration. func Run[T any](ctx context.Context, cfg Config[T]) Group[T] { if cfg.NumWorkers <= 0 { cfg.NumWorkers = 1 } if cfg.Handle == nil { panic("Handle must be set") } g, ctx := errgroup.WithContext(ctx) // Buffered for performance. ch := make(chan T, cfg.NumWorkers) for range cfg.NumWorkers { g.Go(func() error { for { select { case <-ctx.Done(): return nil case v, ok := <-ch: if !ok { return nil } if err := cfg.Handle(ctx, v); err != nil { return err } } } }) } return &runGroup[T]{ ctx: ctx, g: g, ch: ch, } } // Enqueue enqueues a new item to be handled by the workers. func (r *runGroup[T]) Enqueue(t T) error { select { case <-r.ctx.Done(): return nil case r.ch <- t: } return nil } // Wait waits for all workers to finish and returns the first error. func (r *runGroup[T]) Wait() error { close(r.ch) return r.g.Wait() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/common/rungroup/rungroup_test.go
common/rungroup/rungroup_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 rungroup import ( "context" "testing" qt "github.com/frankban/quicktest" ) func TestNew(t *testing.T) { c := qt.New(t) var result int adder := func(ctx context.Context, i int) error { result += i return nil } g := Run[int]( context.Background(), Config[int]{ Handle: adder, }, ) c.Assert(g, qt.IsNotNil) g.Enqueue(32) g.Enqueue(33) c.Assert(g.Wait(), qt.IsNil) c.Assert(result, qt.Equals, 65) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/transform/chain_test.go
transform/chain_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 import ( "bytes" "strings" "testing" qt "github.com/frankban/quicktest" ) func TestChainZeroTransformers(t *testing.T) { tr := New() in := new(bytes.Buffer) out := new(bytes.Buffer) if err := tr.Apply(in, out); err != nil { t.Errorf("A zero transformer chain returned an error.") } } func TestChainingMultipleTransformers(t *testing.T) { f1 := func(ct FromTo) error { _, err := ct.To().Write(bytes.Replace(ct.From().Bytes(), []byte("f1"), []byte("f1r"), -1)) return err } f2 := func(ct FromTo) error { _, err := ct.To().Write(bytes.Replace(ct.From().Bytes(), []byte("f2"), []byte("f2r"), -1)) return err } f3 := func(ct FromTo) error { _, err := ct.To().Write(bytes.Replace(ct.From().Bytes(), []byte("f3"), []byte("f3r"), -1)) return err } f4 := func(ct FromTo) error { _, err := ct.To().Write(bytes.Replace(ct.From().Bytes(), []byte("f4"), []byte("f4r"), -1)) return err } tr := New(f1, f2, f3, f4) out := new(bytes.Buffer) if err := tr.Apply(out, strings.NewReader("Test: f4 f3 f1 f2 f1 The End.")); err != nil { t.Errorf("Multi transformer chain returned an error: %s", err) } expected := "Test: f4r f3r f1r f2r f1r The End." if out.String() != expected { t.Errorf("Expected %s got %s", expected, out.String()) } } func TestNewEmptyTransforms(t *testing.T) { c := qt.New(t) transforms := NewEmpty() c.Assert(cap(transforms), qt.Equals, 20) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/transform/chain.go
transform/chain.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 import ( "bytes" "io" "os" bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/hugofs" ) // Transformer is the func that needs to be implemented by a transformation step. type Transformer func(ft FromTo) error // BytesReader wraps the Bytes method, usually implemented by bytes.Buffer, and an // io.Reader. type BytesReader interface { // The slice given by Bytes is valid for use only until the next buffer modification. // That is, if you want to use this value outside of the current transformer step, // you need to take a copy. Bytes() []byte io.Reader } // FromTo is sent to each transformation step in the chain. type FromTo interface { From() BytesReader To() io.Writer } // Chain is an ordered processing chain. The next transform operation will // receive the output from the previous. type Chain []Transformer // New creates a content transformer chain given the provided transform funcs. func New(trs ...Transformer) Chain { return trs } // NewEmpty creates a new slice of transformers with a capacity of 20. func NewEmpty() Chain { return make(Chain, 0, 20) } // Implements contentTransformer // Content is read from the from-buffer and rewritten to to the to-buffer. type fromToBuffer struct { from *bytes.Buffer to *bytes.Buffer } func (ft fromToBuffer) From() BytesReader { return ft.from } func (ft fromToBuffer) To() io.Writer { return ft.to } // Apply passes the given from io.Reader through the transformation chain. // The result is written to to. func (c *Chain) Apply(to io.Writer, from io.Reader) error { if len(*c) == 0 { _, err := io.Copy(to, from) return err } b1 := bp.GetBuffer() defer bp.PutBuffer(b1) if _, err := b1.ReadFrom(from); err != nil { return err } b2 := bp.GetBuffer() defer bp.PutBuffer(b2) fb := &fromToBuffer{from: b1, to: b2} for i, tr := range *c { if i > 0 { if fb.from == b1 { fb.from = b2 fb.to = b1 fb.to.Reset() } else { fb.from = b1 fb.to = b2 fb.to.Reset() } } if err := tr(fb); err != nil { // Write output to a temp file so it can be read by the user for trouble shooting. filename := "output.html" tempfile, ferr := os.CreateTemp("", "hugo-transform-error") if ferr == nil { filename = tempfile.Name() defer tempfile.Close() _, _ = io.Copy(tempfile, fb.from) return herrors.NewFileErrorFromFile(err, filename, hugofs.Os, nil) } return herrors.NewFileErrorFromName(err, filename).UpdateContent(fb.from, nil) } } _, err := fb.to.WriteTo(to) return err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/transform/livereloadinject/livereloadinject_test.go
transform/livereloadinject/livereloadinject_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 livereloadinject import ( "bytes" "io" "net/url" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/transform" ) func TestLiveReloadInject(t *testing.T) { c := qt.New(t) lrurl, err := url.Parse("http://localhost:1234/subpath") if err != nil { t.Errorf("Parsing test URL failed") return } expectBase := `<script src="/subpath/livereload.js?mindelay=10&amp;v=2&amp;port=1234&amp;path=subpath/livereload" data-no-instant defer></script>` apply := func(s string) string { out := new(bytes.Buffer) in := strings.NewReader(s) tr := transform.New(New(lrurl)) tr.Apply(out, in) return out.String() } c.Run("Inject after head tag", func(c *qt.C) { c.Assert(apply("<!doctype html><html><head>after"), qt.Equals, "<!doctype html><html><head>"+expectBase+"after") }) c.Run("Inject after head tag when doctype and html omitted", func(c *qt.C) { c.Assert(apply("<head>after"), qt.Equals, "<head>"+expectBase+"after") }) c.Run("Inject after html when head omitted", func(c *qt.C) { c.Assert(apply("<html>after"), qt.Equals, "<html>"+expectBase+"after") }) c.Run("Inject after doctype when head and html omitted", func(c *qt.C) { c.Assert(apply("<!doctype html>after"), qt.Equals, "<!doctype html>"+expectBase+"after") }) c.Run("Inject nothing if no doctype, html or head found", func(c *qt.C) { c.Assert(apply("<title>after</title>"), qt.Equals, "<title>after</title>") }) c.Run("Inject nothing if no tag found", func(c *qt.C) { c.Assert(apply("after"), qt.Equals, "after") }) c.Run("Inject after HeAd tag MiXed CaSe", func(c *qt.C) { c.Assert(apply("<HeAd>AfTer"), qt.Equals, "<HeAd>"+expectBase+"AfTer") }) c.Run("Inject after HtMl tag MiXed CaSe", func(c *qt.C) { c.Assert(apply("<HtMl>AfTer"), qt.Equals, "<HtMl>"+expectBase+"AfTer") }) c.Run("Inject after doctype mixed case", func(c *qt.C) { c.Assert(apply("<!DocType HtMl>AfTer"), qt.Equals, "<!DocType HtMl>"+expectBase+"AfTer") }) c.Run("Inject after html tag with attributes", func(c *qt.C) { c.Assert(apply(`<html lang="en">after`), qt.Equals, `<html lang="en">`+expectBase+"after") }) c.Run("Inject after html tag with newline", func(c *qt.C) { c.Assert(apply("<html\n>after"), qt.Equals, "<html\n>"+expectBase+"after") }) c.Run("Skip comments and whitespace", func(c *qt.C) { c.Assert( apply(" <!--x--> <!doctype html>\n<?xml instruction ?> <head>after"), qt.Equals, " <!--x--> <!doctype html>\n<?xml instruction ?> <head>"+expectBase+"after", ) }) c.Run("Do not search inside comment", func(c *qt.C) { c.Assert(apply("<html><!--<head>-->"), qt.Equals, "<html><!--<head>-->"+expectBase) }) c.Run("Do not search inside scripts", func(c *qt.C) { c.Assert(apply("<html><script>`<head>`</script>"), qt.Equals, "<html>"+expectBase+"<script>`<head>`</script>") }) c.Run("Do not search inside templates", func(c *qt.C) { c.Assert(apply("<html><template><head></template>"), qt.Not(qt.Equals), "<html><template><head>"+expectBase+"</template>") }) c.Run("Search from the start of the input", func(c *qt.C) { c.Assert(apply("<head>after<head>"), qt.Equals, "<head>"+expectBase+"after<head>") }) c.Run("Do not mistake header for head", func(c *qt.C) { c.Assert(apply("<html><header>"), qt.Equals, "<html>"+expectBase+"<header>") }) c.Run("Do not mistake custom elements for head", func(c *qt.C) { c.Assert(apply("<html><head-custom>"), qt.Equals, "<html>"+expectBase+"<head-custom>") }) } func BenchmarkLiveReloadInject(b *testing.B) { s := ` <html> <head> </head> <body> </body> </html> ` in := strings.NewReader(s) lrurl, err := url.Parse("http://localhost:1234/subpath") if err != nil { b.Fatalf("Parsing test URL failed") } tr := transform.New(New(lrurl)) for b.Loop() { in.Seek(0, 0) tr.Apply(io.Discard, in) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/transform/livereloadinject/livereloadinject.go
transform/livereloadinject/livereloadinject.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package livereloadinject import ( "fmt" "html" "net/url" "regexp" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ( ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`) tagsBeforeHead = []*regexp.Regexp{ regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`), regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`), regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`), } ) // New creates a function that can be used to inject a script tag for // the livereload JavaScript at the start of an HTML document's head. func New(baseURL *url.URL) transform.Transformer { return func(ft transform.FromTo) error { b := ft.From().Bytes() // We find the start of the head by reading past (in order) // the doctype declaration, HTML start tag and head start tag, // all of which are optional, and any whitespace, comments, or // XML instructions in-between. idx := 0 for _, tag := range tagsBeforeHead { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } if idx == 0 { // doctype is required for HTML5, we did not find it, // and neither did we find html or head tags, so // skip injection. // This allows us to render partial HTML documents to be used in // e.g. JS frameworks. ft.To().Write(b) return nil } path := strings.TrimSuffix(baseURL.Path, "/") src := path + "/livereload.js?mindelay=10&v=2" src += "&port=" + baseURL.Port() src += "&path=" + strings.TrimPrefix(path+"/livereload", "/") script := fmt.Appendf(nil, `<script src="%s" data-no-instant defer></script>`, html.EscapeString(src)) c := make([]byte, len(b)+len(script)) copy(c, b[:idx]) copy(c[idx:], script) copy(c[idx+len(script):], b[idx:]) if _, err := ft.To().Write(c); err != nil { loggers.Log().Warnf("Failed to inject LiveReload script:", err) } return nil } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/transform/metainject/hugogenerator.go
transform/metainject/hugogenerator.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 metainject import ( "bytes" "fmt" "regexp" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ( metaTagsCheck = regexp.MustCompile(`(?i)<meta\s+name=['|"]?generator['|"]?`) hugoGeneratorTag = fmt.Sprintf(`<meta name="generator" content="Hugo %s">`, hugo.CurrentVersion) ) // HugoGenerator injects a meta generator tag for Hugo if none present. func HugoGenerator(ft transform.FromTo) error { b := ft.From().Bytes() if metaTagsCheck.Match(b) { if _, err := ft.To().Write(b); err != nil { loggers.Log().Warnf("Failed to inject Hugo generator tag: %s", err) } return nil } head := "<head>" replace := fmt.Appendf(nil, "%s\n\t%s", head, hugoGeneratorTag) newcontent := bytes.Replace(b, []byte(head), replace, 1) if len(newcontent) == len(b) { head := "<HEAD>" replace := fmt.Appendf(nil, "%s\n\t%s", head, hugoGeneratorTag) newcontent = bytes.Replace(b, []byte(head), replace, 1) } if _, err := ft.To().Write(newcontent); err != nil { loggers.Log().Warnf("Failed to inject Hugo generator tag: %s", err) } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/transform/metainject/hugogenerator_test.go
transform/metainject/hugogenerator_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 metainject import ( "bytes" "strings" "testing" "github.com/gohugoio/hugo/transform" ) func TestHugoGeneratorInject(t *testing.T) { hugoGeneratorTag = "META" for i, this := range []struct { in string expect string }{ {`<head> <foo /> </head>`, `<head> META <foo /> </head>`}, {`<HEAD> <foo /> </HEAD>`, `<HEAD> META <foo /> </HEAD>`}, {`<head><meta name="generator" content="Jekyll"></head>`, `<head><meta name="generator" content="Jekyll"></head>`}, {`<head><meta name='generator' content='Jekyll'></head>`, `<head><meta name='generator' content='Jekyll'></head>`}, {`<head><meta name=generator content=Jekyll></head>`, `<head><meta name=generator content=Jekyll></head>`}, {`<head><META NAME="GENERATOR" content="Jekyll"></head>`, `<head><META NAME="GENERATOR" content="Jekyll"></head>`}, {"", ""}, {"</head>", "</head>"}, {"<head>", "<head>\n\tMETA"}, } { in := strings.NewReader(this.in) out := new(bytes.Buffer) tr := transform.New(HugoGenerator) tr.Apply(out, in) if out.String() != this.expect { t.Errorf("[%d] Expected \n%q got \n%q", i, this.expect, out.String()) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/transform/urlreplacers/absurlreplacer_test.go
transform/urlreplacers/absurlreplacer_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 urlreplacers import ( "path/filepath" "testing" bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/transform" ) const ( h5JsContentDoubleQuote = "<!DOCTYPE html><html><head><script src=\"foobar.js\"></script><script src=\"/barfoo.js\"></script></head><body><nav><h1>title</h1></nav><article>content <a href=\"foobar\">foobar</a>. <a href=\"/foobar\">Follow up</a></article></body></html>" h5JsContentSingleQuote = "<!DOCTYPE html><html><head><script src='foobar.js'></script><script src='/barfoo.js'></script></head><body><nav><h1>title</h1></nav><article>content <a href='foobar'>foobar</a>. <a href='/foobar'>Follow up</a></article></body></html>" h5JsContentAbsURL = "<!DOCTYPE html><html><head><script src=\"http://user@host:10234/foobar.js\"></script></head><body><nav><h1>title</h1></nav><article>content <a href=\"https://host/foobar\">foobar</a>. Follow up</article></body></html>" h5JsContentAbsURLSchemaless = "<!DOCTYPE html><html><head><script src=\"//host/foobar.js\"></script><script src='//host2/barfoo.js'></head><body><nav><h1>title</h1></nav><article>content <a href=\"//host/foobar\">foobar</a>. <a href='//host2/foobar'>Follow up</a></article></body></html>" correctOutputSrcHrefDq = "<!DOCTYPE html><html><head><script src=\"foobar.js\"></script><script src=\"http://base/barfoo.js\"></script></head><body><nav><h1>title</h1></nav><article>content <a href=\"foobar\">foobar</a>. <a href=\"http://base/foobar\">Follow up</a></article></body></html>" correctOutputSrcHrefSq = "<!DOCTYPE html><html><head><script src='foobar.js'></script><script src='http://base/barfoo.js'></script></head><body><nav><h1>title</h1></nav><article>content <a href='foobar'>foobar</a>. <a href='http://base/foobar'>Follow up</a></article></body></html>" h5XMLContentAbsURL = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?><feed xmlns=\"http://www.w3.org/2005/Atom\"><entry><content type=\"html\">&lt;p&gt;&lt;a href=&#34;/foobar&#34;&gt;foobar&lt;/a&gt;&lt;/p&gt; &lt;p&gt;A video: &lt;iframe src=&#39;/foo&#39;&gt;&lt;/iframe&gt;&lt;/p&gt;</content></entry></feed>" correctOutputSrcHrefInXML = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?><feed xmlns=\"http://www.w3.org/2005/Atom\"><entry><content type=\"html\">&lt;p&gt;&lt;a href=&#34;http://base/foobar&#34;&gt;foobar&lt;/a&gt;&lt;/p&gt; &lt;p&gt;A video: &lt;iframe src=&#39;http://base/foo&#39;&gt;&lt;/iframe&gt;&lt;/p&gt;</content></entry></feed>" h5XMLContentGuarded = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?><feed xmlns=\"http://www.w3.org/2005/Atom\"><entry><content type=\"html\">&lt;p&gt;&lt;a href=&#34;//foobar&#34;&gt;foobar&lt;/a&gt;&lt;/p&gt; &lt;p&gt;A video: &lt;iframe src=&#39;//foo&#39;&gt;&lt;/iframe&gt;&lt;/p&gt;</content></entry></feed>" ) const ( // additional sanity tests for replacements testing replace1 = "No replacements." replace2 = "ᚠᛇᚻ ᛒᛦᚦ ᚠᚱᚩᚠᚢᚱ\nᚠᛁᚱᚪ ᚷᛖᚻᚹᛦᛚᚳᚢᛗ" replace3 = `End of file: src="/` replace5 = `Srcsett with no closing quote: srcset="/img/small.jpg do be do be do.` // Issue: 816, schemaless links combined with others replaceSchemalessHTML = `Pre. src='//schemaless' src='/normal' <a href="//schemaless">Schemaless</a>. <a href="/normal">normal</a>. Post.` replaceSchemalessHTMLCorrect = `Pre. src='//schemaless' src='http://base/normal' <a href="//schemaless">Schemaless</a>. <a href="http://base/normal">normal</a>. Post.` replaceSchemalessXML = `Pre. src=&#39;//schemaless&#39; src=&#39;/normal&#39; <a href=&#39;//schemaless&#39;>Schemaless</a>. <a href=&#39;/normal&#39;>normal</a>. Post.` replaceSchemalessXMLCorrect = `Pre. src=&#39;//schemaless&#39; src=&#39;http://base/normal&#39; <a href=&#39;//schemaless&#39;>Schemaless</a>. <a href=&#39;http://base/normal&#39;>normal</a>. Post.` ) const ( // srcset= srcsetBasic = `Pre. <img srcset="/img/small.jpg 200w, /img/medium.jpg 300w, /img/big.jpg 700w" alt="text" src="/img/foo.jpg">` srcsetBasicCorrect = `Pre. <img srcset="http://base/img/small.jpg 200w, http://base/img/medium.jpg 300w, http://base/img/big.jpg 700w" alt="text" src="http://base/img/foo.jpg">` srcsetSingleQuote = `Pre. <img srcset='/img/small.jpg 200w, /img/big.jpg 700w' alt="text" src="/img/foo.jpg"> POST.` srcsetSingleQuoteCorrect = `Pre. <img srcset='http://base/img/small.jpg 200w, http://base/img/big.jpg 700w' alt="text" src="http://base/img/foo.jpg"> POST.` srcsetXMLBasic = `Pre. <img srcset=&#34;/img/small.jpg 200w, /img/big.jpg 700w&#34; alt=&#34;text&#34; src=&#34;/img/foo.jpg&#34;>` srcsetXMLBasicCorrect = `Pre. <img srcset=&#34;http://base/img/small.jpg 200w, http://base/img/big.jpg 700w&#34; alt=&#34;text&#34; src=&#34;http://base/img/foo.jpg&#34;>` srcsetXMLSingleQuote = `Pre. <img srcset=&#34;/img/small.jpg 200w, /img/big.jpg 700w&#34; alt=&#34;text&#34; src=&#34;/img/foo.jpg&#34;>` srcsetXMLSingleQuoteCorrect = `Pre. <img srcset=&#34;http://base/img/small.jpg 200w, http://base/img/big.jpg 700w&#34; alt=&#34;text&#34; src=&#34;http://base/img/foo.jpg&#34;>` srcsetVariations = `Pre. Missing start quote: <img srcset=/img/small.jpg 200w, /img/big.jpg 700w" alt="text"> src='/img/foo.jpg'> FOO. <img srcset='/img.jpg'> schemaless: <img srcset='//img.jpg' src='//basic.jpg'> schemaless2: <img srcset="//img.jpg" src="//basic.jpg2> POST ` ) const ( srcsetVariationsCorrect = `Pre. Missing start quote: <img srcset=/img/small.jpg 200w, /img/big.jpg 700w" alt="text"> src='http://base/img/foo.jpg'> FOO. <img srcset='http://base/img.jpg'> schemaless: <img srcset='//img.jpg' src='//basic.jpg'> schemaless2: <img srcset="//img.jpg" src="//basic.jpg2> POST ` srcsetXMLVariations = `Pre. Missing start quote: &lt;img srcset=/img/small.jpg 200w /img/big.jpg 700w&quot; alt=&quot;text&quot;&gt; src=&#39;/img/foo.jpg&#39;&gt; FOO. &lt;img srcset=&#39;/img.jpg&#39;&gt; schemaless: &lt;img srcset=&#39;//img.jpg&#39; src=&#39;//basic.jpg&#39;&gt; schemaless2: &lt;img srcset=&quot;//img.jpg&quot; src=&quot;//basic.jpg2&gt; POST ` srcsetXMLVariationsCorrect = `Pre. Missing start quote: &lt;img srcset=/img/small.jpg 200w /img/big.jpg 700w&quot; alt=&quot;text&quot;&gt; src=&#39;http://base/img/foo.jpg&#39;&gt; FOO. &lt;img srcset=&#39;http://base/img.jpg&#39;&gt; schemaless: &lt;img srcset=&#39;//img.jpg&#39; src=&#39;//basic.jpg&#39;&gt; schemaless2: &lt;img srcset=&quot;//img.jpg&quot; src=&quot;//basic.jpg2&gt; POST ` relPathVariations = `PRE. a href="/img/small.jpg" input action="/foo.html" meta url=/redirect/to/page/ POST.` relPathVariationsCorrect = `PRE. a href="../../img/small.jpg" input action="../../foo.html" meta url=../../redirect/to/page/ POST.` testBaseURL = "http://base/" ) var ( absURLlBenchTests = []test{ {h5JsContentDoubleQuote, correctOutputSrcHrefDq}, {h5JsContentSingleQuote, correctOutputSrcHrefSq}, {h5JsContentAbsURL, h5JsContentAbsURL}, {h5JsContentAbsURLSchemaless, h5JsContentAbsURLSchemaless}, } xmlAbsURLBenchTests = []test{ {h5XMLContentAbsURL, correctOutputSrcHrefInXML}, {h5XMLContentGuarded, h5XMLContentGuarded}, } sanityTests = []test{{replace1, replace1}, {replace2, replace2}, {replace3, replace3}, {replace3, replace3}, {replace5, replace5}} extraTestsHTML = []test{{replaceSchemalessHTML, replaceSchemalessHTMLCorrect}} absURLTests = append(absURLlBenchTests, append(sanityTests, extraTestsHTML...)...) extraTestsXML = []test{{replaceSchemalessXML, replaceSchemalessXMLCorrect}} xmlAbsURLTests = append(xmlAbsURLBenchTests, append(sanityTests, extraTestsXML...)...) srcsetTests = []test{{srcsetBasic, srcsetBasicCorrect}, {srcsetSingleQuote, srcsetSingleQuoteCorrect}, {srcsetVariations, srcsetVariationsCorrect}} srcsetXMLTests = []test{ {srcsetXMLBasic, srcsetXMLBasicCorrect}, {srcsetXMLSingleQuote, srcsetXMLSingleQuoteCorrect}, {srcsetXMLVariations, srcsetXMLVariationsCorrect}, } relurlTests = []test{{relPathVariations, relPathVariationsCorrect}} ) func BenchmarkAbsURL(b *testing.B) { tr := transform.New(NewAbsURLTransformer(testBaseURL)) for b.Loop() { apply(b.Errorf, tr, absURLlBenchTests) } } func BenchmarkAbsURLSrcset(b *testing.B) { tr := transform.New(NewAbsURLTransformer(testBaseURL)) for b.Loop() { apply(b.Errorf, tr, srcsetTests) } } func BenchmarkXMLAbsURLSrcset(b *testing.B) { tr := transform.New(NewAbsURLInXMLTransformer(testBaseURL)) for b.Loop() { apply(b.Errorf, tr, srcsetXMLTests) } } func TestAbsURL(t *testing.T) { tr := transform.New(NewAbsURLTransformer(testBaseURL)) apply(t.Errorf, tr, absURLTests) } func TestAbsURLUnquoted(t *testing.T) { tr := transform.New(NewAbsURLTransformer(testBaseURL)) apply(t.Errorf, tr, []test{ { content: `Link: <a href=/asdf>ASDF</a>`, expected: `Link: <a href=http://base/asdf>ASDF</a>`, }, { content: `Link: <a href=/asdf >ASDF</a>`, expected: `Link: <a href=http://base/asdf >ASDF</a>`, }, }) } func TestRelativeURL(t *testing.T) { tr := transform.New(NewAbsURLTransformer(helpers.GetDottedRelativePath(filepath.FromSlash("/post/sub/")))) applyWithPath(t.Errorf, tr, relurlTests) } func TestAbsURLSrcSet(t *testing.T) { tr := transform.New(NewAbsURLTransformer(testBaseURL)) apply(t.Errorf, tr, srcsetTests) } func TestAbsXMLURLSrcSet(t *testing.T) { tr := transform.New(NewAbsURLInXMLTransformer(testBaseURL)) apply(t.Errorf, tr, srcsetXMLTests) } func BenchmarkXMLAbsURL(b *testing.B) { tr := transform.New(NewAbsURLInXMLTransformer(testBaseURL)) for b.Loop() { apply(b.Errorf, tr, xmlAbsURLBenchTests) } } func TestXMLAbsURL(t *testing.T) { tr := transform.New(NewAbsURLInXMLTransformer(testBaseURL)) apply(t.Errorf, tr, xmlAbsURLTests) } func apply(ef errorf, tr transform.Chain, tests []test) { applyWithPath(ef, tr, tests) } func applyWithPath(ef errorf, tr transform.Chain, tests []test) { out := bp.GetBuffer() defer bp.PutBuffer(out) in := bp.GetBuffer() defer bp.PutBuffer(in) for _, test := range tests { var err error in.WriteString(test.content) err = tr.Apply(out, in) if err != nil { ef("Unexpected error: %s", err) } if test.expected != out.String() { ef("Expected:\n%s\nGot:\n%s", test.expected, out.String()) } out.Reset() in.Reset() } } type test struct { content string expected string } type errorf func(string, ...any)
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/transform/urlreplacers/absurlreplacer.go
transform/urlreplacers/absurlreplacer.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 urlreplacers import ( "bytes" "io" "net/url" "unicode" "unicode/utf8" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/transform" ) type absurllexer struct { // the source to absurlify content []byte // the target for the new absurlified content w io.Writer // path may be set to a "." relative path path []byte // The root path, without leading slash. root []byte pos int // input position start int // item start position quotes [][]byte } type prefix struct { disabled bool b []byte f func(l *absurllexer) nextPos int } func (p *prefix) find(bs []byte, start int) bool { if p.disabled { return false } if p.nextPos == -1 { idx := bytes.Index(bs[start:], p.b) if idx == -1 { p.disabled = true // Find the closest match return false } p.nextPos = start + idx + len(p.b) } return true } func newPrefixState() []*prefix { return []*prefix{ {b: []byte("src="), f: checkCandidateBase}, {b: []byte("href="), f: checkCandidateBase}, {b: []byte("url="), f: checkCandidateBase}, {b: []byte("action="), f: checkCandidateBase}, {b: []byte("srcset="), f: checkCandidateSrcset}, } } func (l *absurllexer) emit() { l.w.Write(l.content[l.start:l.pos]) l.start = l.pos } var ( relURLPrefix = []byte("/") relURLPrefixLen = len(relURLPrefix) ) func (l *absurllexer) consumeQuote() []byte { for _, q := range l.quotes { if bytes.HasPrefix(l.content[l.pos:], q) { l.pos += len(q) l.emit() return q } } return nil } // handle URLs in src and href. func checkCandidateBase(l *absurllexer) { l.consumeQuote() if !bytes.HasPrefix(l.content[l.pos:], relURLPrefix) { return } // check for schemaless URLs posAfter := l.pos + relURLPrefixLen if posAfter >= len(l.content) { return } r, _ := utf8.DecodeRune(l.content[posAfter:]) if r == '/' { // schemaless: skip return } if l.pos > l.start { l.emit() } l.pos += relURLPrefixLen l.w.Write(l.path) if len(l.root) > 0 && bytes.HasPrefix(l.content[l.pos:], l.root) { l.pos += len(l.root) } l.start = l.pos } func (l *absurllexer) posAfterURL(q []byte) int { if len(q) > 0 { // look for end quote return bytes.Index(l.content[l.pos:], q) } return bytes.IndexFunc(l.content[l.pos:], func(r rune) bool { return r == '>' || unicode.IsSpace(r) }) } // handle URLs in srcset. func checkCandidateSrcset(l *absurllexer) { q := l.consumeQuote() if q == nil { // srcset needs to be quoted. return } // special case, not frequent (me think) if !bytes.HasPrefix(l.content[l.pos:], relURLPrefix) { return } // check for schemaless URLs posAfter := l.pos + relURLPrefixLen if posAfter >= len(l.content) { return } r, _ := utf8.DecodeRune(l.content[posAfter:]) if r == '/' { // schemaless: skip return } posEnd := l.posAfterURL(q) // safe guard if posEnd < 0 || posEnd > 2000 { return } if l.pos > l.start { l.emit() } section := l.content[l.pos : l.pos+posEnd+1] fields := bytes.Fields(section) for i, f := range fields { if f[0] == '/' { l.w.Write(l.path) n := 1 if len(l.root) > 0 && bytes.HasPrefix(f[n:], l.root) { n += len(l.root) } l.w.Write(f[n:]) } else { l.w.Write(f) } if i < len(fields)-1 { l.w.Write([]byte(" ")) } } l.pos += len(section) l.start = l.pos } // main loop func (l *absurllexer) replace() { contentLength := len(l.content) prefixes := newPrefixState() for { if l.pos >= contentLength { break } var match *prefix for _, p := range prefixes { if !p.find(l.content, l.pos) { continue } if match == nil || p.nextPos < match.nextPos { match = p } } if match == nil { // Done! l.pos = contentLength break } else { l.pos = match.nextPos match.nextPos = -1 match.f(l) } } // Done! if l.pos > l.start { l.emit() } } func doReplace(path string, ct transform.FromTo, quotes [][]byte) { var root string if u, err := url.Parse(path); err == nil { root = paths.TrimLeading(u.Path) } lexer := &absurllexer{ content: ct.From().Bytes(), w: ct.To(), path: []byte(path), root: []byte(root), quotes: quotes, } lexer.replace() } type absURLReplacer struct { htmlQuotes [][]byte xmlQuotes [][]byte } func newAbsURLReplacer() *absURLReplacer { return &absURLReplacer{ htmlQuotes: [][]byte{[]byte("\""), []byte("'")}, xmlQuotes: [][]byte{[]byte("&#34;"), []byte("&#39;")}, } } func (au *absURLReplacer) replaceInHTML(path string, ct transform.FromTo) { doReplace(path, ct, au.htmlQuotes) } func (au *absURLReplacer) replaceInXML(path string, ct transform.FromTo) { doReplace(path, ct, au.xmlQuotes) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/transform/urlreplacers/absurl.go
transform/urlreplacers/absurl.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 urlreplacers import ( "github.com/gohugoio/hugo/transform" ) var ar = newAbsURLReplacer() // NewAbsURLTransformer replaces relative URLs with absolute ones // in HTML files, using the baseURL setting. func NewAbsURLTransformer(path string) transform.Transformer { return func(ft transform.FromTo) error { ar.replaceInHTML(path, ft) return nil } } // NewAbsURLInXMLTransformer replaces relative URLs with absolute ones // in XML files, using the baseURL setting. func NewAbsURLInXMLTransformer(path string) transform.Transformer { return func(ft transform.FromTo) error { ar.replaceInXML(path, ft) return nil } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/navigation/menu_cache.go
navigation/menu_cache.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package navigation import ( "slices" "sync" ) type menuCacheEntry struct { in []Menu out Menu } func (entry menuCacheEntry) matches(menuList []Menu) bool { if len(entry.in) != len(menuList) { return false } for i, m := range menuList { if !slices.Equal(m, entry.in[i]) { return false } } return true } // newMenuCache creates a new menuCache instance. func newMenuCache() *menuCache { return &menuCache{m: make(map[string][]menuCacheEntry)} } type menuCache struct { sync.RWMutex m map[string][]menuCacheEntry } // get retrieves a menu from the cache based on the provided key and menuLists. // If the menu is not found, it applies the provided function and caches the result. func (c *menuCache) get(key string, apply func(m Menu), menuLists ...Menu) (Menu, bool) { return c.getP(key, func(m *Menu) { if apply != nil { apply(*m) } }, menuLists...) } // getP is similar to get but also returns a boolean indicating whether the menu was found in the cache. func (c *menuCache) getP(key string, apply func(m *Menu), menuLists ...Menu) (Menu, bool) { c.Lock() defer c.Unlock() if cached, ok := c.m[key]; ok { for _, entry := range cached { if entry.matches(menuLists) { return entry.out, true } } } m := menuLists[0] menuCopy := slices.Clone(m) if apply != nil { apply(&menuCopy) } entry := menuCacheEntry{in: menuLists, out: menuCopy} if v, ok := c.m[key]; ok { c.m[key] = append(v, entry) } else { c.m[key] = []menuCacheEntry{entry} } return menuCopy, false }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/navigation/menu.go
navigation/menu.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 navigation provides the menu functionality. package navigation import ( "html/template" "slices" "sort" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/compare" "github.com/gohugoio/hugo/config" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" ) var smc = newMenuCache() // MenuEntry represents a menu item defined in either Page front matter // or in the site config. type MenuEntry struct { // The menu entry configuration. MenuConfig // The menu containing this menu entry. Menu string // The URL value from front matter / config. ConfiguredURL string // The Page connected to this menu entry. Page Page // Child entries. Children Menu } func (m *MenuEntry) URL() string { // Check page first. // In Hugo 0.86.0 we added `pageRef`, // a way to connect menu items in site config to pages. // This means that you now can have both a Page // and a configured URL. // Having the configured URL as a fallback if the Page isn't found // is obviously more useful, especially in multilingual sites. if !types.IsNil(m.Page) { return m.Page.RelPermalink() } return m.ConfiguredURL } // SetPageValues sets the Page and URL values for this menu entry. func SetPageValues(m *MenuEntry, p Page) { m.Page = p if m.MenuConfig.Name == "" { m.MenuConfig.Name = p.LinkTitle() } if m.MenuConfig.Title == "" { m.MenuConfig.Title = p.Title() } if m.MenuConfig.Weight == 0 { m.MenuConfig.Weight = p.Weight() } } // A narrow version of page.Page. type Page interface { LinkTitle() string Title() string RelPermalink() string Path() string Section() string Weight() int IsPage() bool IsSection() bool IsAncestor(other any) bool Params() maps.Params } // Menu is a collection of menu entries. type Menu []*MenuEntry // Menus is a dictionary of menus. type Menus map[string]Menu // PageMenus is a dictionary of menus defined in the Pages. type PageMenus map[string]*MenuEntry // HasChildren returns whether this menu item has any children. func (m *MenuEntry) HasChildren() bool { return m.Children != nil } // KeyName returns the key used to identify this menu entry. func (m *MenuEntry) KeyName() string { if m.Identifier != "" { return m.Identifier } return m.Name } func (m *MenuEntry) hopefullyUniqueID() string { if m.Identifier != "" { return m.Identifier } else if m.URL() != "" { return m.URL() } else { return m.Name } } // isEqual returns whether the two menu entries represents the same menu entry. func (m *MenuEntry) isEqual(inme *MenuEntry) bool { return m.hopefullyUniqueID() == inme.hopefullyUniqueID() && m.Parent == inme.Parent } // isSameResource returns whether the two menu entries points to the same // resource (URL). func (m *MenuEntry) isSameResource(inme *MenuEntry) bool { if m.isSamePage(inme.Page) { return m.Page == inme.Page } murl, inmeurl := m.URL(), inme.URL() return murl != "" && inmeurl != "" && murl == inmeurl } func (m *MenuEntry) isSamePage(p Page) bool { if !types.IsNil(m.Page) && !types.IsNil(p) { return m.Page == p } return false } // MenuConfig holds the configuration for a menu. type MenuConfig struct { Identifier string Parent string Name string Pre template.HTML Post template.HTML URL string PageRef string Weight int Title string // User defined params. Params maps.Params } // For internal use. // This is for internal use only. func (m Menu) Add(me *MenuEntry) Menu { m = append(m, me) // TODO(bep) m.Sort() return m } /* * Implementation of a custom sorter for Menu */ // A type to implement the sort interface for Menu type menuSorter struct { menu Menu by menuEntryBy } // Closure used in the Sort.Less method. type menuEntryBy func(m1, m2 *MenuEntry) bool func (by menuEntryBy) Sort(menu Menu) { ms := &menuSorter{ menu: menu, by: by, // The Sort method's receiver is the function (closure) that defines the sort order. } sort.Stable(ms) } var defaultMenuEntrySort = func(m1, m2 *MenuEntry) bool { if m1.Weight == m2.Weight { c := compare.Strings(m1.Name, m2.Name) if c == 0 { return m1.Identifier < m2.Identifier } return c < 0 } if m2.Weight == 0 { return true } if m1.Weight == 0 { return false } return m1.Weight < m2.Weight } func (ms *menuSorter) Len() int { return len(ms.menu) } func (ms *menuSorter) Swap(i, j int) { ms.menu[i], ms.menu[j] = ms.menu[j], ms.menu[i] } // Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter. func (ms *menuSorter) Less(i, j int) bool { return ms.by(ms.menu[i], ms.menu[j]) } // Sort sorts the menu by weight, name and then by identifier. func (m Menu) Sort() Menu { menuEntryBy(defaultMenuEntrySort).Sort(m) return m } // Limit limits the returned menu to n entries. func (m Menu) Limit(n int) Menu { if len(m) > n { return m[0:n] } return m } // ByWeight sorts the menu by the weight defined in the menu configuration. func (m Menu) ByWeight() Menu { const key = "menuSort.ByWeight" menus, _ := smc.get(key, menuEntryBy(defaultMenuEntrySort).Sort, m) return menus } // ByName sorts the menu by the name defined in the menu configuration. func (m Menu) ByName() Menu { const key = "menuSort.ByName" title := func(m1, m2 *MenuEntry) bool { return compare.LessStrings(m1.Name, m2.Name) } menus, _ := smc.get(key, menuEntryBy(title).Sort, m) return menus } // Reverse reverses the order of the menu entries. func (m Menu) Reverse() Menu { const key = "menuSort.Reverse" reverseFunc := func(menu Menu) { for i, j := 0, len(menu)-1; i < j; i, j = i+1, j-1 { menu[i], menu[j] = menu[j], menu[i] } } menus, _ := smc.get(key, reverseFunc, m) return menus } // Clone clones the menu entries. // This is for internal use only. func (m Menu) Clone() Menu { return slices.Clone(m) } func DecodeConfig(in any) (*config.ConfigNamespace[map[string]MenuConfig, Menus], error) { buildConfig := func(in any) (Menus, any, error) { ret := Menus{} if in == nil { return ret, map[string]any{}, nil } menus, err := maps.ToStringMapE(in) if err != nil { return ret, nil, err } menus = maps.CleanConfigStringMap(menus) for name, menu := range menus { m, err := cast.ToSliceE(menu) if err != nil { return ret, nil, err } else { for _, entry := range m { var menuConfig MenuConfig if err := mapstructure.WeakDecode(entry, &menuConfig); err != nil { return ret, nil, err } maps.PrepareParams(menuConfig.Params) menuEntry := MenuEntry{ Menu: name, MenuConfig: menuConfig, } menuEntry.ConfiguredURL = menuEntry.MenuConfig.URL if ret[name] == nil { ret[name] = Menu{} } ret[name] = ret[name].Add(&menuEntry) } } } return ret, menus, nil } return config.DecodeNamespace[map[string]MenuConfig](in, buildConfig) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/navigation/menu_cache_test.go
navigation/menu_cache_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package navigation import ( "slices" "sync" "sync/atomic" "testing" qt "github.com/frankban/quicktest" ) func createSortTestMenu(num int) Menu { menu := make(Menu, num) for i := range num { m := &MenuEntry{} menu[i] = m } return menu } func TestMenuCache(t *testing.T) { t.Parallel() c := qt.New(t) c1 := newMenuCache() changeFirst := func(m Menu) { m[0].MenuConfig.Title = "changed" } var o1 uint64 var o2 uint64 var wg sync.WaitGroup var l1 sync.Mutex var l2 sync.Mutex var testMenuSets []Menu for i := range 50 { testMenuSets = append(testMenuSets, createSortTestMenu(i+1)) } for range 100 { wg.Add(1) go func() { defer wg.Done() for k, menu := range testMenuSets { l1.Lock() m, ca := c1.get("k1", nil, menu) c.Assert(ca, qt.Equals, !atomic.CompareAndSwapUint64(&o1, uint64(k), uint64(k+1))) l1.Unlock() m2, c2 := c1.get("k1", nil, m) c.Assert(c2, qt.Equals, true) c.Assert(slices.Equal(m, m2), qt.Equals, true) c.Assert(slices.Equal(m, menu), qt.Equals, true) c.Assert(m, qt.Not(qt.IsNil)) l2.Lock() m3, c3 := c1.get("k2", changeFirst, menu) c.Assert(c3, qt.Equals, !atomic.CompareAndSwapUint64(&o2, uint64(k), uint64(k+1))) l2.Unlock() c.Assert(m3, qt.Not(qt.IsNil)) c.Assert("changed", qt.Equals, m3[0].Title) } }() } wg.Wait() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/navigation/pagemenus.go
navigation/pagemenus.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 navigation import ( "fmt" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" ) type PageMenusProvider interface { PageMenusGetter MenuQueryProvider } type PageMenusGetter interface { Menus() PageMenus } type MenusGetter interface { Menus() Menus } type MenuQueryProvider interface { HasMenuCurrent(menuID string, me *MenuEntry) bool IsMenuCurrent(menuID string, inme *MenuEntry) bool } func PageMenusFromPage(ms any, p Page) (PageMenus, error) { if ms == nil { return nil, nil } pm := PageMenus{} me := MenuEntry{} SetPageValues(&me, p) // Could be the name of the menu to attach it to mname, err := cast.ToStringE(ms) if err == nil { me.Menu = mname pm[mname] = &me return pm, nil } // Could be a slice of strings mnames, err := cast.ToStringSliceE(ms) if err == nil { for _, mname := range mnames { me.Menu = mname pm[mname] = &me } return pm, nil } wrapErr := func(err error) error { return fmt.Errorf("unable to process menus for page %q: %w", p.Path(), err) } // Could be a structured menu entry menus, err := maps.ToStringMapE(ms) if err != nil { return pm, wrapErr(err) } for name, menu := range menus { menuEntry := MenuEntry{Menu: name} if menu != nil { ime, err := maps.ToStringMapE(menu) if err != nil { return pm, wrapErr(err) } if err := mapstructure.WeakDecode(ime, &menuEntry.MenuConfig); err != nil { return pm, err } } SetPageValues(&menuEntry, p) pm[name] = &menuEntry } return pm, nil } func NewMenuQueryProvider( pagem PageMenusGetter, sitem MenusGetter, p Page, ) MenuQueryProvider { return &pageMenus{ p: p, pagem: pagem, sitem: sitem, } } type pageMenus struct { pagem PageMenusGetter sitem MenusGetter p Page } func (pm *pageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { if !types.IsNil(me.Page) && me.Page.IsSection() { if ok := me.Page.IsAncestor(pm.p); ok { return true } } if !me.HasChildren() { return false } menus := pm.pagem.Menus() if m, ok := menus[menuID]; ok { for _, child := range me.Children { if child.isEqual(m) { return true } if pm.HasMenuCurrent(menuID, child) { return true } } } if pm.p == nil { return false } for _, child := range me.Children { if child.isSamePage(pm.p) { return true } if pm.HasMenuCurrent(menuID, child) { return true } } return false } func (pm *pageMenus) IsMenuCurrent(menuID string, inme *MenuEntry) bool { menus := pm.pagem.Menus() if me, ok := menus[menuID]; ok { if me.isEqual(inme) { return true } } if pm.p == nil { return false } if !inme.isSamePage(pm.p) { return false } // This resource may be included in several menus. // Search for it to make sure that it is in the menu with the given menuId. if menu, ok := pm.sitem.Menus()[menuID]; ok { for _, menuEntry := range menu { if menuEntry.isSameResource(inme) { return true } descendantFound := pm.isSameAsDescendantMenu(inme, menuEntry) if descendantFound { return descendantFound } } } return false } func (pm *pageMenus) isSameAsDescendantMenu(inme *MenuEntry, parent *MenuEntry) bool { if parent.HasChildren() { for _, child := range parent.Children { if child.isSameResource(inme) { return true } descendantFound := pm.isSameAsDescendantMenu(inme, child) if descendantFound { return descendantFound } } } return false } var NopPageMenus = new(nopPageMenus) type nopPageMenus int func (m nopPageMenus) Menus() PageMenus { return PageMenus{} } func (m nopPageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { return false } func (m nopPageMenus) IsMenuCurrent(menuID string, inme *MenuEntry) bool { return false }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/docshelper/docs.go
docshelper/docs.go
// Copyright 2017-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 docshelper provides some helpers for the Hugo documentation, and // is of limited interest for the general Hugo user. package docshelper import "fmt" type ( DocProviderFunc = func() DocProvider DocProvider map[string]any ) var docProviderFuncs []DocProviderFunc func AddDocProviderFunc(fn DocProviderFunc) { docProviderFuncs = append(docProviderFuncs, fn) } func GetDocProvider() DocProvider { provider := make(DocProvider) for _, fn := range docProviderFuncs { p := fn() for k, v := range p { if _, found := provider[k]; found { // We use to merge config, but not anymore. // These constructs will eventually go away, so just make it simple. panic(fmt.Sprintf("Duplicate doc provider key: %q", k)) } provider[k] = v } } return provider }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/langs/language_test.go
langs/language_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 langs import ( "sync" "testing" qt "github.com/frankban/quicktest" "golang.org/x/text/collate" "golang.org/x/text/language" ) func TestCollator(t *testing.T) { c := qt.New(t) var wg sync.WaitGroup coll := &Collator{c: collate.New(language.English, collate.Loose)} for range 10 { wg.Add(1) go func() { coll.Lock() defer coll.Unlock() defer wg.Done() for range 10 { k := coll.CompareStrings("abc", "def") c.Assert(k, qt.Equals, -1) } }() } wg.Wait() } func BenchmarkCollator(b *testing.B) { s := []string{"foo", "bar", "éntre", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud"} doWork := func(coll *Collator) { for i := range s { for j := i + 1; j < len(s); j++ { _ = coll.CompareStrings(s[i], s[j]) } } } b.Run("Single", func(b *testing.B) { coll := &Collator{c: collate.New(language.English, collate.Loose)} for b.Loop() { doWork(coll) } }) b.Run("Para", func(b *testing.B) { b.RunParallel(func(pb *testing.PB) { coll := &Collator{c: collate.New(language.English, collate.Loose)} for pb.Next() { coll.Lock() doWork(coll) coll.Unlock() } }) }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/langs/languages_integration_test.go
langs/languages_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 langs_test import ( "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestLanguagesContentSimple(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org/" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 2 [languages.nn] weight = 1 -- content/_index.md -- --- title: "Home" --- Welcome to the home page. -- content/_index.nn.md -- --- title: "Heim" --- Welkomen heim! -- layouts/all.html -- title: {{ .Title }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/en/index.html", `title: Home|`) b.AssertFileContent("public/nn/index.html", `title: Heim|`) } func TestLanguagesContentSharedResource(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "sitemap", "404"] baseURL = "https://example.org/" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 2 [languages.nn] weight = 1 -- content/mytext.txt -- This is a shared text file. -- content/_index.md -- --- title: "Home" --- Welcome to the home page. -- content/_index.nn.md -- --- title: "Heim" --- Welkomen heim! -- layouts/home.html -- {{ $text := .Resources.Get "mytext.txt" }} title: {{ .Title }}|text: {{ with $text }}{{ .Content | safeHTML }}{{ end }}|{{ .Resources | len}} ` b := hugolib.Test(t, files) b.AssertFileContent("public/nn/index.html", `title: Heim|text: This is a shared text file.|1`) b.AssertFileContent("public/en/index.html", `title: Home|text: This is a shared text file.|1`) } // Issue 14031 func TestDraftTermIssue14031(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap'] capitalizeListTitles = false pluralizeListTitles = false defaultContentLanguage = 'en' defaultContentLanguageInSubdir = true [languages.en] weight = 1 [languages.fr] weight = 2 [taxonomies] tag = 'tags' -- content/p1.en.md -- --- title: P1 (en) tags: [a,b] --- -- content/p1.fr.md -- --- title: P1 (fr) tags: [a,b] --- -- content/tags/a/_index.en.md -- --- title: a (en) --- -- content/tags/a/_index.fr.md -- --- title: a (fr) --- -- content/tags/b/_index.en.md -- --- title: b (en) --- -- content/tags/b/_index.fr.md -- --- title: b (fr) draft: false --- -- layouts/list.html -- {{- .Title -}}| {{- range .Pages -}} TITLE: {{ .Title }} RELPERMALINK: {{ .RelPermalink }}| {{- end -}} -- layouts/page.html -- {{- .Title -}}| {{- range .GetTerms "tags" -}} TITLE: {{ .Title }} RELPERMALINK: {{ .RelPermalink }}| {{- end -}} ` b := hugolib.Test(t, files) b.AssertFileExists("public/en/tags/a/index.html", true) b.AssertFileExists("public/fr/tags/a/index.html", true) b.AssertFileExists("public/en/tags/b/index.html", true) b.AssertFileExists("public/fr/tags/b/index.html", true) b.AssertFileContentEquals("public/en/p1/index.html", "P1 (en)|TITLE: a (en) RELPERMALINK: /en/tags/a/|TITLE: b (en) RELPERMALINK: /en/tags/b/|", ) b.AssertFileContentEquals("public/fr/p1/index.html", "P1 (fr)|TITLE: a (fr) RELPERMALINK: /fr/tags/a/|TITLE: b (fr) RELPERMALINK: /fr/tags/b/|", ) b.AssertFileContentEquals("public/en/tags/index.html", "tags|TITLE: a (en) RELPERMALINK: /en/tags/a/|TITLE: b (en) RELPERMALINK: /en/tags/b/|", ) b.AssertFileContentEquals("public/fr/tags/index.html", "tags|TITLE: a (fr) RELPERMALINK: /fr/tags/a/|TITLE: b (fr) RELPERMALINK: /fr/tags/b/|", ) b.AssertFileContentEquals("public/en/tags/a/index.html", "a (en)|TITLE: P1 (en) RELPERMALINK: /en/p1/|", ) b.AssertFileContentEquals("public/fr/tags/a/index.html", "a (fr)|TITLE: P1 (fr) RELPERMALINK: /fr/p1/|", ) b.AssertFileContentEquals("public/en/tags/b/index.html", "b (en)|TITLE: P1 (en) RELPERMALINK: /en/p1/|", ) b.AssertFileContentEquals("public/fr/tags/b/index.html", "b (fr)|TITLE: P1 (fr) RELPERMALINK: /fr/p1/|", ) // Set draft to true on content/tags/b/_index.fr.md. files = strings.ReplaceAll(files, "draft: false", "draft: true") b = hugolib.Test(t, files) b.AssertFileExists("public/en/tags/a/index.html", true) b.AssertFileExists("public/fr/tags/a/index.html", true) b.AssertFileExists("public/en/tags/b/index.html", true) b.AssertFileExists("public/fr/tags/b/index.html", false) // The assertion below fails. // Got: P1 (en)|TITLE: a (en) RELPERMALINK: /en/tags/a/| b.AssertFileContentEquals("public/en/p1/index.html", "P1 (en)|TITLE: a (en) RELPERMALINK: /en/tags/a/|TITLE: b (en) RELPERMALINK: /en/tags/b/|", ) b.AssertFileContentEquals("public/fr/p1/index.html", "P1 (fr)|TITLE: a (fr) RELPERMALINK: /fr/tags/a/|", ) b.AssertFileContentEquals("public/en/tags/index.html", "tags|TITLE: a (en) RELPERMALINK: /en/tags/a/|TITLE: b (en) RELPERMALINK: /en/tags/b/|", ) b.AssertFileContentEquals("public/fr/tags/index.html", "tags|TITLE: a (fr) RELPERMALINK: /fr/tags/a/|", ) b.AssertFileContentEquals("public/en/tags/a/index.html", "a (en)|TITLE: P1 (en) RELPERMALINK: /en/p1/|", ) b.AssertFileContentEquals("public/fr/tags/a/index.html", "a (fr)|TITLE: P1 (fr) RELPERMALINK: /fr/p1/|", ) // The assertion below fails. // Got: b (en)| b.AssertFileContentEquals("public/en/tags/b/index.html", "b (en)|TITLE: P1 (en) RELPERMALINK: /en/p1/|", ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/langs/language.go
langs/language.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 langs contains the language related types and function. package langs import ( "fmt" "sync" "time" "golang.org/x/text/collate" "golang.org/x/text/language" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/locales" translators "github.com/gohugoio/localescompressed" ) var _ sitesmatrix.DimensionInfo = (*Language)(nil) type Language struct { // The language code, e.g. "en" or "no". // This is the key used in the languages map in the configuration, // and currently only settable as the key in the language map in the config. Lang string // Fields from the language config. LanguageConfig // Used for date formatting etc. We don't want these exported to the // templates. translator locales.Translator timeFormatter htime.TimeFormatter tag language.Tag // collator1 and collator2 are the same, we have 2 to prevent deadlocks. collator1 *Collator collator2 *Collator location *time.Location isDefault bool // This is just an alias of Site.Params. params maps.Params } // Name is an alias for Lang. func (l *Language) Name() string { return l.Lang } func (l *Language) IsDefault() bool { return l.isDefault } // NewLanguage creates a new language. func NewLanguage(lang, defaultContentLanguage, timeZone string, languageConfig LanguageConfig) (*Language, error) { translator := translators.GetTranslator(lang) if translator == nil { translator = translators.GetTranslator(defaultContentLanguage) if translator == nil { translator = translators.GetTranslator("en") } } var coll1, coll2 *Collator tag, err := language.Parse(lang) if err == nil { coll1 = &Collator{ c: collate.New(tag), } coll2 = &Collator{ c: collate.New(tag), } } else { coll1 = &Collator{ c: collate.New(language.English), } coll2 = &Collator{ c: collate.New(language.English), } } l := &Language{ Lang: lang, LanguageConfig: languageConfig, translator: translator, timeFormatter: htime.NewTimeFormatter(translator), tag: tag, collator1: coll1, collator2: coll2, isDefault: lang == defaultContentLanguage, } return l, l.loadLocation(timeZone) } // This is injected from hugolib to avoid circular dependencies. var DeprecationFunc = func(item, alternative string, err bool) {} // Params returns the language params. // Note that this is the same as the Site.Params, but we keep it here for legacy reasons. // Deprecated: Use the site.Params instead. func (l *Language) Params() maps.Params { // TODO(bep) Remove this for now as it created a little too much noise. Need to think about this. // See https://github.com/gohugoio/hugo/issues/11025 // DeprecationFunc(".Language.Params", paramsDeprecationWarning, false) return l.params } func (l *Language) LanguageCode() string { if l.LanguageConfig.LanguageCode != "" { return l.LanguageConfig.LanguageCode } return l.Lang } func (l *Language) loadLocation(tzStr string) error { location, err := time.LoadLocation(tzStr) if err != nil { return fmt.Errorf("invalid timeZone for language %q: %w", l.Lang, err) } l.location = location return nil } func (l *Language) String() string { return l.Lang } // Languages is a sortable list of languages. type Languages []*Language func (l Languages) AsSet() map[string]bool { m := make(map[string]bool) for _, lang := range l { m[lang.Lang] = true } return m } // AsIndexSet returns a map with the language code as key and index in l as value. func (l Languages) AsIndexSet() map[string]int { m := make(map[string]int) for i, lang := range l { m[lang.Lang] = i } return m } // Internal access to unexported Language fields. // This construct is to prevent them from leaking to the templates. func SetParams(l *Language, params maps.Params) { l.params = params } func GetTimeFormatter(l *Language) htime.TimeFormatter { return l.timeFormatter } func GetTranslator(l *Language) locales.Translator { return l.translator } func GetLocation(l *Language) *time.Location { return l.location } func GetCollator1(l *Language) *Collator { return l.collator1 } func GetCollator2(l *Language) *Collator { return l.collator2 } type Collator struct { sync.Mutex c *collate.Collator } // CompareStrings compares a and b. // It returns -1 if a < b, 1 if a > b and 0 if a == b. // Note that the Collator is not thread safe, so you may want // to acquire a lock on it before calling this method. func (c *Collator) CompareStrings(a, b string) int { return c.c.CompareString(a, b) } // IndexDefault returns the index of the default language. func IndexDefault(languages Languages) int { for i, l := range languages { if l.isDefault { return i } } panic("no default lang found") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/langs/config.go
langs/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 langs import ( "errors" "fmt" "iter" "slices" "sort" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/predicate" "github.com/gohugoio/hugo/config" "github.com/mitchellh/mapstructure" ) // LanguageConfig holds the configuration for a single language. // This is what is read from the config file. type LanguageConfig struct { // The language name, e.g. "English". LanguageName string // The language code, e.g. "en-US". LanguageCode string // The language title. When set, this will // override site.Title for this language. Title string // The language direction, e.g. "ltr" or "rtl". LanguageDirection string // The language weight. When set to a non-zero value, this will // be the main sort criteria for the language. Weight int // Set to true to disable this language. Disabled bool } type LanguageInternal struct { // Name is the name of the role, extracted from the key in the config. Name string // Whether this role is the default role. // This will be rendered in the root. // There is only be one default role. Default bool LanguageConfig } type LanguagesInternal struct { LanguageConfigs map[string]LanguageConfig Sorted []LanguageInternal } func (ls LanguagesInternal) IndexDefault() int { for i, role := range ls.Sorted { if role.Default { return i } } panic("no default role found") } func (ls LanguagesInternal) ResolveName(i int) string { if i < 0 || i >= len(ls.Sorted) { panic(fmt.Sprintf("index %d out of range for languages", i)) } return ls.Sorted[i].Name } func (ls LanguagesInternal) ResolveIndex(name string) int { for i, role := range ls.Sorted { if role.Name == name { return i } } panic(fmt.Sprintf("no language found for name %q", name)) } func (ls LanguagesInternal) Len() int { return len(ls.Sorted) } // IndexMatch returns an iterator for the roles that match the filter. func (ls LanguagesInternal) IndexMatch(match predicate.P[string]) (iter.Seq[int], error) { return func(yield func(i int) bool) { for i, l := range ls.Sorted { if match(l.Name) { if !yield(i) { return } } } }, nil } // ForEachIndex returns an iterator for the indices of the languages. func (ls LanguagesInternal) ForEachIndex() iter.Seq[int] { return func(yield func(i int) bool) { for i := range ls.Sorted { if !yield(i) { return } } } } func (ls *LanguagesInternal) init(defaultContentLanguage string, disabledLanguages []string) (string, error) { const en = "en" if len(ls.LanguageConfigs) == 0 { // Add a default language. if defaultContentLanguage == "" { defaultContentLanguage = en } ls.LanguageConfigs[defaultContentLanguage] = LanguageConfig{} } var ( defaultSeen bool enIdx int = -1 ) for k, v := range ls.LanguageConfigs { if !v.Disabled && slices.Contains(disabledLanguages, k) { // This language is disabled. v.Disabled = true ls.LanguageConfigs[k] = v } if k == "" { return "", errors.New("language name cannot be empty") } if err := paths.ValidateIdentifier(k); err != nil { return "", fmt.Errorf("language name %q is invalid: %s", k, err) } var isDefault bool if k == defaultContentLanguage { isDefault = true defaultSeen = true } if isDefault && v.Disabled { return "", fmt.Errorf("default language %q is disabled", k) } if !v.Disabled { ls.Sorted = append(ls.Sorted, LanguageInternal{Name: k, Default: isDefault, LanguageConfig: v}) } } // Sort by weight if set, then by name. sort.SliceStable(ls.Sorted, func(i, j int) bool { ri, rj := ls.Sorted[i], ls.Sorted[j] if ri.Weight == rj.Weight { return ri.Name < rj.Name } if rj.Weight == 0 { return true } if ri.Weight == 0 { return false } return ri.Weight < rj.Weight }) for i, l := range ls.Sorted { if l.Name == en { enIdx = i break } } if !defaultSeen { if defaultContentLanguage != "" { // Set by the user, but not found in the config. return "", fmt.Errorf("defaultContentLanguage %q not found in languages configuration", defaultContentLanguage) } // Not set by the user, so we use the first language in the config. defaultIdx := 0 if enIdx != -1 { defaultIdx = enIdx } d := ls.Sorted[defaultIdx] d.Default = true ls.LanguageConfigs[d.Name] = d.LanguageConfig ls.Sorted[defaultIdx] = d defaultContentLanguage = d.Name } return defaultContentLanguage, nil } func DecodeConfig(defaultContentLanguage string, disabledLanguages []string, m map[string]any) (*config.ConfigNamespace[map[string]LanguageConfig, LanguagesInternal], string, error) { v, err := config.DecodeNamespace[map[string]LanguageConfig](m, func(in any) (LanguagesInternal, any, error) { var languages LanguagesInternal var conf map[string]LanguageConfig if err := mapstructure.Decode(m, &conf); err != nil { return languages, nil, err } languages.LanguageConfigs = conf var err error if defaultContentLanguage, err = languages.init(defaultContentLanguage, disabledLanguages); err != nil { return languages, nil, err } return languages, languages.LanguageConfigs, nil }) return v, defaultContentLanguage, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/langs/i18n/i18n_integration_test.go
langs/i18n/i18n_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 i18n_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestI18nFromTheme(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [module] [[module.imports]] path = "mytheme" -- i18n/en.toml -- [l1] other = 'l1main' [l2] other = 'l2main' -- themes/mytheme/i18n/en.toml -- [l1] other = 'l1theme' [l2] other = 'l2theme' [l3] other = 'l3theme' -- layouts/home.html -- l1: {{ i18n "l1" }}|l2: {{ i18n "l2" }}|l3: {{ i18n "l3" }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` l1: l1main|l2: l2main|l3: l3theme `) } func TestPassPageToI18n(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/_index.md -- --- title: "Home" --- Duis quis irure id nisi sunt minim aliqua occaecat. Aliqua cillum labore consectetur quis culpa tempor quis non officia cupidatat in ad cillum. Velit irure pariatur nisi adipisicing officia reprehenderit commodo esse non. Ullamco cupidatat nostrud ut reprehenderit. Consequat nisi culpa magna amet tempor velit reprehenderit. Ad minim eiusmod tempor nostrud eu aliquip consectetur commodo ut in aliqua enim. Cupidatat voluptate laborum consequat qui nulla laborum laborum aute ea culpa nulla dolor cillum veniam. Commodo esse tempor qui labore aute aliqua sint nulla do. Ad deserunt esse nostrud labore. Amet reprehenderit fugiat nostrud eu reprehenderit sit reprehenderit minim deserunt esse id occaecat cillum. Ad qui Lorem cillum laboris ipsum anim in culpa ad dolor consectetur minim culpa. Lorem cupidatat officia aute in eu commodo anim nulla deserunt occaecat reprehenderit dolore. Eu cupidatat reprehenderit ipsum sit laboris proident. Duis quis nulla tempor adipisicing. Adipisicing amet ad reprehenderit non mollit. Cupidatat proident tempor laborum sit ipsum adipisicing sunt magna labore. Eu irure nostrud cillum exercitation tempor proident. Laborum magna nisi consequat do sint occaecat magna incididunt. Sit mollit amet esse dolore in labore aliquip eu duis officia incididunt. Esse veniam labore excepteur eiusmod occaecat ullamco magna sunt. Ipsum occaecat exercitation anim fugiat in amet excepteur excepteur aliquip laborum. Aliquip aliqua consequat officia sit sint amet aliqua ipsum eu veniam. Id enim quis ea in eu consequat exercitation occaecat veniam consequat anim nulla adipisicing minim. Ut duis cillum laboris duis non commodo eu aliquip tempor nisi aute do. Ipsum nulla esse excepteur ut aliqua esse incididunt deserunt veniam dolore est laborum nisi veniam. Magna eiusmod Lorem do tempor incididunt ut aute aliquip ipsum ea laboris culpa. Occaecat do officia velit fugiat culpa eu minim magna sint occaecat sunt. Duis magna proident incididunt est cupidatat proident esse proident ut ipsum non dolor Lorem eiusmod. Officia quis irure id eu aliquip. Duis anim elit in officia in in aliquip est. Aliquip nisi labore qui elit elit cupidatat ut labore incididunt eiusmod ipsum. Sit irure nulla non cupidatat exercitation sit culpa nisi ex dolore. Culpa nisi duis duis eiusmod commodo nulla. Et magna aliqua amet qui mollit. Eiusmod aute ut anim ea est fugiat non nisi in laborum ullamco. Proident mollit sunt nostrud irure esse sunt eiusmod deserunt dolor. Irure aute ad magna est consequat duis cupidatat consequat. Enim tempor aute cillum quis ea do enim proident incididunt aliquip cillum tempor minim. Nulla minim tempor proident in excepteur consectetur veniam. Exercitation tempor nulla incididunt deserunt laboris ad incididunt aliqua exercitation. Adipisicing laboris veniam aute eiusmod qui magna fugiat velit. Aute quis officia anim commodo id fugiat nostrud est. Quis ipsum amet velit adipisicing eu anim minim eu est in culpa aute. Esse in commodo irure enim proident reprehenderit ullamco in dolore aute cillum. Irure excepteur ex occaecat ipsum laboris fugiat exercitation. Exercitation adipisicing velit excepteur eu culpa consequat exercitation dolore. In laboris aute quis qui mollit minim culpa. Magna velit ea aliquip veniam fugiat mollit veniam. -- i18n/en.toml -- [a] other = 'Reading time: {{ .ReadingTime }}' -- layouts/home.html -- i18n: {{ i18n "a" . }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` i18n: Reading time: 3| `) } // Issue 9216 func TestI18nDefaultContentLanguage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['RSS','sitemap','taxonomy','term','page','section'] defaultContentLanguage = 'es' defaultContentLanguageInSubdir = true [languages.es] [languages.fr] -- i18n/es.toml -- cat = 'gato' -- i18n/fr.toml -- # this file intentionally empty -- layouts/home.html -- {{ .Title }}_{{ T "cat" }} -- content/_index.fr.md -- --- title: home_fr --- -- content/_index.md -- --- title: home_es --- ` b := hugolib.Test(t, files) b.AssertFileContent("public/es/index.html", `home_es_gato`) b.AssertFileContent("public/fr/index.html", `home_fr_gato`) } // See issue #14061 func TestI18nReservedKeyMap(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- i18n/en.toml -- [description] other = 'This is a description from i18n.' -- layouts/all.html -- description: {{ T "description" }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", `description: This is a description from i18n.|`) } // See issue #14061 func TestI18nReservedKeyScalar(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','page','rss','section','sitemap','taxonomy','term'] -- i18n/en.toml -- a = 'a translated' description = 'description translated' b = 'b translated' ` b, err := hugolib.TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "failed to load translations: reserved keys [description] mixed with unreserved keys [a b]: see the lang.Translate documentation for a list of reserved keys") } func TestI18nUseLanguageCodeWhenBothTranslationFilesArePresent(t *testing.T) { t.Parallel() filesTemplate := ` -- hugo.yaml -- languages: en: languageCode: en-us -- i18n/en.yml -- hello: Greetings from en! -- i18n/en-us.yml -- hello: Greetings from en-us! -- layouts/all.html -- {{ T "hello" }} ` runTest := func(s string) { b := hugolib.Test(t, s) b.AssertFileContent("public/index.html", `Greetings from en-us!`) } runTest(filesTemplate) runTest(strings.ReplaceAll(filesTemplate, "languageCode: en-us", "languageCode: En-US")) runTest(strings.ReplaceAll(filesTemplate, "-- i18n/en-us.yml --", "-- i18n/en-US.yml --")) } func TestI18nUseLangWhenLanguageCodeFileIsMissing(t *testing.T) { t.Parallel() filesTemplate := ` -- hugo.yaml -- languages: en: title: English pt: languageCode: pt-br -- i18n/en.yml -- hello: Greetings from en! -- i18n/pt.yml -- hello: Greetings from pt! -- layouts/all.html -- {{ T "hello" }} ` runTest := func(s string) { b := hugolib.Test(t, s) b.AssertFileContent("public/pt/index.html", `Greetings from pt!`) } runTest(filesTemplate) runTest(strings.ReplaceAll(filesTemplate, "pt:", "PT:")) runTest(strings.ReplaceAll(filesTemplate, "-- i18n/pt.yml --", "-- i18n/pT.yml --")) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/langs/i18n/i18n.go
langs/i18n/i18n.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 i18n import ( "context" "fmt" "reflect" "strings" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/go-i18n/v2/i18n" ) type translateFunc func(ctx context.Context, translationID string, templateData any) string // Translator handles i18n translations. type Translator struct { translateFuncs map[string]translateFunc cfg config.AllProvider logger loggers.Logger } // NewTranslator creates a new Translator for the given language bundle and configuration. func NewTranslator(b *i18n.Bundle, cfg config.AllProvider, logger loggers.Logger) Translator { t := Translator{cfg: cfg, logger: logger, translateFuncs: make(map[string]translateFunc)} t.initFuncs(b) return t } // Lookup looks up the translate func for the given language. func (t Translator) Lookup(lang string) (translateFunc, bool) { f, ok := t.translateFuncs[lang] return f, ok } // Func gets the translate func for the given language, or for the default // configured language if not found. func (t Translator) Func(lang string) translateFunc { if f, ok := t.translateFuncs[lang]; ok { return f } t.logger.Infof("Translation func for language %v not found, use default.", lang) if f, ok := t.translateFuncs[t.cfg.DefaultContentLanguage()]; ok { return f } t.logger.Infoln("i18n not initialized; if you need string translations, check that you have a bundle in /i18n that matches the site language or the default language.") return func(ctx context.Context, translationID string, args any) string { return "" } } func (t Translator) initFuncs(bndl *i18n.Bundle) { enableMissingTranslationPlaceholders := t.cfg.EnableMissingTranslationPlaceholders() for _, lang := range bndl.LanguageTags() { currentLang := lang currentLangStr := currentLang.String() // This may be pt-BR; make it case insensitive. currentLangKey := strings.ToLower(strings.TrimPrefix(currentLangStr, artificialLangTagPrefix)) localizer := i18n.NewLocalizer(bndl, currentLangStr) t.translateFuncs[currentLangKey] = func(ctx context.Context, translationID string, templateData any) string { pluralCount := getPluralCount(templateData) if templateData != nil { tp := reflect.TypeOf(templateData) if hreflect.IsInt(tp.Kind()) { // This was how go-i18n worked in v1, // and we keep it like this to avoid breaking // lots of sites in the wild. templateData = intCount(cast.ToInt(templateData)) } else { if p, ok := templateData.(page.Page); ok { // See issue 10782. // The i18n has its own template handling and does not know about // the context.Context. // A common pattern is to pass Page to i18n, and use .ReadingTime etc. // We need to improve this, but that requires some upstream changes. // For now, just create a wrapper. templateData = page.PageWithContext{Page: p, Ctx: ctx} } } } translated, translatedLang, err := localizer.LocalizeWithTag(&i18n.LocalizeConfig{ MessageID: translationID, TemplateData: templateData, PluralCount: pluralCount, }) sameLang := currentLang == translatedLang if err == nil && sameLang { return translated } if err != nil && sameLang && translated != "" { // See #8492 // TODO(bep) this needs to be improved/fixed upstream, // but currently we get an error even if the fallback to // "other" succeeds. if fmt.Sprintf("%T", err) == "i18n.pluralFormNotFoundError" { return translated } } if _, ok := err.(*i18n.MessageNotFoundErr); !ok { t.logger.Warnf("Failed to get translated string for language %q and ID %q: %s", currentLangStr, translationID, err) } if t.cfg.PrintI18nWarnings() { t.logger.Warnf("i18n|MISSING_TRANSLATION|%s|%s", currentLangStr, translationID) } if enableMissingTranslationPlaceholders { return "[i18n] " + translationID } return translated } } } // intCount wraps the Count method. type intCount int func (c intCount) Count() int { return int(c) } const countFieldName = "Count" // getPluralCount gets the plural count as a string (floats) or an integer. // If v is nil, nil is returned. func getPluralCount(v any) any { if v == nil { // i18n called without any argument, make sure it does not // get any plural count. return nil } switch v := v.(type) { case map[string]any: for k, vv := range v { if strings.EqualFold(k, countFieldName) { return toPluralCountValue(vv) } } default: vv, isNil := hreflect.IndirectElem(reflect.ValueOf(v)) if isNil { return nil } tp := vv.Type() if tp.Kind() == reflect.Struct { f := vv.FieldByName(countFieldName) if f.IsValid() { return toPluralCountValue(f.Interface()) } m := hreflect.GetMethodByName(vv, countFieldName) if m.IsValid() && m.Type().NumIn() == 0 && m.Type().NumOut() == 1 { c := m.Call(nil) return toPluralCountValue(c[0].Interface()) } } } return toPluralCountValue(v) } // go-i18n expects floats to be represented by string. func toPluralCountValue(in any) any { k := reflect.TypeOf(in).Kind() switch { case hreflect.IsFloat(k): f := cast.ToString(in) if !strings.Contains(f, ".") { f += ".0" } return f case k == reflect.String: if _, err := cast.ToFloat64E(in); err == nil { return in } // A non-numeric value. return nil default: if i, err := cast.ToIntE(in); err == nil { return i } return nil } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/langs/i18n/translationProvider.go
langs/i18n/translationProvider.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 i18n import ( "context" "encoding/json" "fmt" "strings" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/common/herrors" "golang.org/x/text/language" "github.com/gohugoio/go-i18n/v2/i18n" "github.com/gohugoio/hugo/helpers" toml "github.com/pelletier/go-toml/v2" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/source" ) // TranslationProvider provides translation handling, i.e. loading // of bundles etc. type TranslationProvider struct { t Translator } // NewTranslationProvider creates a new translation provider. func NewTranslationProvider() *TranslationProvider { return &TranslationProvider{} } // Update updates the i18n func in the provided Deps. func (tp *TranslationProvider) NewResource(dst *deps.Deps) error { defaultLangTag, err := language.Parse(dst.Conf.DefaultContentLanguage()) if err != nil { defaultLangTag = language.English } bundle := i18n.NewBundle(defaultLangTag) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) bundle.RegisterUnmarshalFunc("yaml", metadecoders.UnmarshalYaml) bundle.RegisterUnmarshalFunc("yml", metadecoders.UnmarshalYaml) bundle.RegisterUnmarshalFunc("json", json.Unmarshal) w := hugofs.NewWalkway( hugofs.WalkwayConfig{ Fs: dst.BaseFs.I18n.Fs, IgnoreFile: dst.SourceSpec.IgnoreFile, PathParser: dst.SourceSpec.Cfg.PathParser(), WalkFn: func(ctx context.Context, path string, info hugofs.FileMetaInfo) error { if info.IsDir() { return nil } return addTranslationFile(bundle, source.NewFileInfo(info)) }, }) if err := w.Walk(); err != nil { return err } tp.t = NewTranslator(bundle, dst.Conf, dst.Log) dst.Translate = tp.getTranslateFunc(dst) return nil } const artificialLangTagPrefix = "art-x-" func addTranslationFile(bundle *i18n.Bundle, r *source.File) error { f, err := r.FileInfo().Meta().Open() if err != nil { return fmt.Errorf("failed to open translations file %q:: %w", r.LogicalName(), err) } b := helpers.ReaderToBytes(f) f.Close() name := r.LogicalName() lang := paths.Filename(name) tag := language.Make(lang) if tag == language.Und { try := artificialLangTagPrefix + lang _, err = language.Parse(try) if err != nil { return fmt.Errorf("%q: %s", try, err) } name = artificialLangTagPrefix + name } _, err = bundle.ParseMessageFileBytes(b, name) if err != nil { if strings.Contains(err.Error(), "no plural rule") { // https://github.com/gohugoio/hugo/issues/7798 name = artificialLangTagPrefix + name _, err = bundle.ParseMessageFileBytes(b, name) if err == nil { return nil } } var guidance string if strings.Contains(err.Error(), "mixed with unreserved keys") { guidance = ": see the lang.Translate documentation for a list of reserved keys" } return errWithFileContext(fmt.Errorf("failed to load translations: %w%s", err, guidance), r) } return nil } // CloneResource sets the language func for the new language. func (tp *TranslationProvider) CloneResource(dst, src *deps.Deps) error { dst.Translate = tp.getTranslateFunc(dst) return nil } // getTranslateFunc returns the translation function for the language in Deps. // We first try the language code (e.g. "en-US"), then the language key (e.g. "en"). func (tp *TranslationProvider) getTranslateFunc(dst *deps.Deps) func(ctx context.Context, translationID string, templateData any) string { l := dst.Conf.Language().(*langs.Language) if lc := l.LanguageCode(); lc != "" { if fn, ok := tp.t.Lookup(strings.ToLower(lc)); ok { return fn } } // Func will fall back to the default language if not found. return tp.t.Func(l.Lang) } func errWithFileContext(inerr error, r *source.File) error { meta := r.FileInfo().Meta() realFilename := meta.Filename f, err := meta.Open() if err != nil { return inerr } defer f.Close() return herrors.NewFileErrorFromName(inerr, realFilename).UpdateContent(f, nil) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/langs/i18n/i18n_test.go
langs/i18n/i18n_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 i18n import ( "context" "fmt" "path/filepath" "testing" "github.com/bep/logg" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/resources/page" "github.com/spf13/afero" "github.com/gohugoio/hugo/deps" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" ) type i18nTest struct { name string data map[string][]byte args any lang, id, expected, expectedFlag string } var i18nTests = []i18nTest{ // All translations present { name: "all-present", data: map[string][]byte{ "en.toml": []byte("[hello]\nother = \"Hello, World!\""), "es.toml": []byte("[hello]\nother = \"¡Hola, Mundo!\""), }, args: nil, lang: "es", id: "hello", expected: "¡Hola, Mundo!", expectedFlag: "¡Hola, Mundo!", }, // Translation missing in current language but present in default { name: "present-in-default", data: map[string][]byte{ "en.toml": []byte("[hello]\nother = \"Hello, World!\""), "es.toml": []byte("[goodbye]\nother = \"¡Adiós, Mundo!\""), }, args: nil, lang: "es", id: "hello", expected: "Hello, World!", expectedFlag: "[i18n] hello", }, // Translation missing in default language but present in current { name: "present-in-current", data: map[string][]byte{ "en.toml": []byte("[goodbye]\nother = \"Goodbye, World!\""), "es.toml": []byte("[hello]\nother = \"¡Hola, Mundo!\""), }, args: nil, lang: "es", id: "hello", expected: "¡Hola, Mundo!", expectedFlag: "¡Hola, Mundo!", }, // Translation missing in both default and current language { name: "missing", data: map[string][]byte{ "en.toml": []byte("[goodbye]\nother = \"Goodbye, World!\""), "es.toml": []byte("[goodbye]\nother = \"¡Adiós, Mundo!\""), }, args: nil, lang: "es", id: "hello", expected: "", expectedFlag: "[i18n] hello", }, // Default translation file missing or empty { name: "file-missing", data: map[string][]byte{ "en.toml": []byte(""), }, args: nil, lang: "es", id: "hello", expected: "", expectedFlag: "[i18n] hello", }, // Context provided { name: "context-provided", data: map[string][]byte{ "en.toml": []byte("[wordCount]\nother = \"Hello, {{.WordCount}} people!\""), "es.toml": []byte("[wordCount]\nother = \"¡Hola, {{.WordCount}} gente!\""), }, args: struct { WordCount int }{ 50, }, lang: "es", id: "wordCount", expected: "¡Hola, 50 gente!", expectedFlag: "¡Hola, 50 gente!", }, // https://github.com/gohugoio/hugo/issues/7787 { name: "readingTime-one", data: map[string][]byte{ "en.toml": []byte(`[readingTime] one = "One minute to read" other = "{{ .Count }} minutes to read" `), }, args: 1, lang: "en", id: "readingTime", expected: "One minute to read", expectedFlag: "One minute to read", }, { name: "readingTime-many-dot", data: map[string][]byte{ "en.toml": []byte(`[readingTime] one = "One minute to read" other = "{{ . }} minutes to read" `), }, args: 21, lang: "en", id: "readingTime", expected: "21 minutes to read", expectedFlag: "21 minutes to read", }, { name: "readingTime-many", data: map[string][]byte{ "en.toml": []byte(`[readingTime] one = "One minute to read" other = "{{ .Count }} minutes to read" `), }, args: 21, lang: "en", id: "readingTime", expected: "21 minutes to read", expectedFlag: "21 minutes to read", }, // Issue #8454 { name: "readingTime-map-one", data: map[string][]byte{ "en.toml": []byte(`[readingTime] one = "One minute to read" other = "{{ .Count }} minutes to read" `), }, args: map[string]any{"Count": 1}, lang: "en", id: "readingTime", expected: "One minute to read", expectedFlag: "One minute to read", }, { name: "readingTime-string-one", data: map[string][]byte{ "en.toml": []byte(`[readingTime] one = "One minute to read" other = "{{ . }} minutes to read" `), }, args: "1", lang: "en", id: "readingTime", expected: "One minute to read", expectedFlag: "One minute to read", }, { name: "readingTime-map-many", data: map[string][]byte{ "en.toml": []byte(`[readingTime] one = "One minute to read" other = "{{ .Count }} minutes to read" `), }, args: map[string]any{"Count": 21}, lang: "en", id: "readingTime", expected: "21 minutes to read", expectedFlag: "21 minutes to read", }, { name: "argument-float", data: map[string][]byte{ "en.toml": []byte(`[float] other = "Number is {{ . }}" `), }, args: 22.5, lang: "en", id: "float", expected: "Number is 22.5", expectedFlag: "Number is 22.5", }, // Same id and translation in current language // https://github.com/gohugoio/hugo/issues/2607 { name: "same-id-and-translation", data: map[string][]byte{ "es.toml": []byte("[hello]\nother = \"hello\""), "en.toml": []byte("[hello]\nother = \"hi\""), }, args: nil, lang: "es", id: "hello", expected: "hello", expectedFlag: "hello", }, // Translation missing in current language, but same id and translation in default { name: "same-id-and-translation-default", data: map[string][]byte{ "es.toml": []byte("[bye]\nother = \"bye\""), "en.toml": []byte("[hello]\nother = \"hello\""), }, args: nil, lang: "es", id: "hello", expected: "hello", expectedFlag: "[i18n] hello", }, // Unknown language code should get its plural spec from en { name: "unknown-language-code", data: map[string][]byte{ "en.toml": []byte(`[readingTime] one ="one minute read" other = "{{.Count}} minutes read"`), "klingon.toml": []byte(`[readingTime] one = "eitt minutt med lesing" other = "{{ .Count }} minuttar lesing"`), }, args: 3, lang: "klingon", id: "readingTime", expected: "3 minuttar lesing", expectedFlag: "3 minuttar lesing", }, // Issue #7838 { name: "unknown-language-codes", data: map[string][]byte{ "en.toml": []byte(`[readingTime] one ="en one" other = "en count {{.Count}}"`), "a1.toml": []byte(`[readingTime] one = "a1 one" other = "a1 count {{ .Count }}"`), "a2.toml": []byte(`[readingTime] one = "a2 one" other = "a2 count {{ .Count }}"`), }, args: 3, lang: "a2", id: "readingTime", expected: "a2 count 3", expectedFlag: "a2 count 3", }, // https://github.com/gohugoio/hugo/issues/7798 { name: "known-language-missing-plural", data: map[string][]byte{ "oc.toml": []byte(`[oc] one = "abc"`), }, args: 1, lang: "oc", id: "oc", expected: "abc", expectedFlag: "abc", }, // https://github.com/gohugoio/hugo/issues/7794 { name: "dotted-bare-key", data: map[string][]byte{ "en.toml": []byte(`"shop_nextPage.one" = "Show Me The Money" `), }, args: nil, lang: "en", id: "shop_nextPage.one", expected: "Show Me The Money", expectedFlag: "Show Me The Money", }, // https: //github.com/gohugoio/hugo/issues/7804 { name: "lang-with-hyphen", data: map[string][]byte{ "pt-br.toml": []byte(`foo.one = "abc"`), }, args: 1, lang: "pt-br", id: "foo", expected: "abc", expectedFlag: "abc", }, } func TestPlural(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string lang string id string templ string variants []types.KeyValue }{ { name: "English", lang: "en", id: "hour", templ: ` [hour] one = "{{ . }} hour" other = "{{ . }} hours"`, variants: []types.KeyValue{ {Key: 1, Value: "1 hour"}, {Key: "1", Value: "1 hour"}, {Key: 1.5, Value: "1.5 hours"}, {Key: "1.5", Value: "1.5 hours"}, {Key: 2, Value: "2 hours"}, {Key: "2", Value: "2 hours"}, }, }, { name: "Other only", lang: "en", id: "hour", templ: ` [hour] other = "{{ with . }}{{ . }}{{ end }} hours"`, variants: []types.KeyValue{ {Key: 1, Value: "1 hours"}, {Key: "1", Value: "1 hours"}, {Key: 2, Value: "2 hours"}, {Key: nil, Value: " hours"}, }, }, { name: "Polish", lang: "pl", id: "day", templ: ` [day] one = "{{ . }} miesiąc" few = "{{ . }} miesiące" many = "{{ . }} miesięcy" other = "{{ . }} miesiąca" `, variants: []types.KeyValue{ {Key: 1, Value: "1 miesiąc"}, {Key: 2, Value: "2 miesiące"}, {Key: 100, Value: "100 miesięcy"}, {Key: "100.0", Value: "100.0 miesiąca"}, {Key: 100.0, Value: "100 miesiąca"}, }, }, } { c.Run(test.name, func(c *qt.C) { cfg := config.New() cfg.Set("enableMissingTranslationPlaceholders", true) cfg.Set("publishDir", "public") afs := afero.NewMemMapFs() err := afero.WriteFile(afs, filepath.Join("i18n", test.lang+".toml"), []byte(test.templ), 0o755) c.Assert(err, qt.IsNil) d, tp := prepareDeps(afs, cfg) f := tp.t.Func(test.lang) ctx := context.Background() for _, variant := range test.variants { c.Assert(f(ctx, test.id, variant.Key), qt.Equals, variant.Value, qt.Commentf("input: %v", variant.Key)) c.Assert(d.Log.LoggCount(logg.LevelWarn), qt.Equals, 0) } }) } } func doTestI18nTranslate(t testing.TB, test i18nTest, cfg config.Provider) string { tp := prepareTranslationProvider(t, test, cfg) f := tp.t.Func(test.lang) return f(context.Background(), test.id, test.args) } type countField struct { Count any } type noCountField struct { Counts int } type countMethod struct{} func (c countMethod) Count() any { return 32.5 } func TestGetPluralCount(t *testing.T) { c := qt.New(t) c.Assert(getPluralCount(map[string]any{"Count": 32}), qt.Equals, 32) c.Assert(getPluralCount(map[string]any{"Count": 1}), qt.Equals, 1) c.Assert(getPluralCount(map[string]any{"Count": 1.5}), qt.Equals, "1.5") c.Assert(getPluralCount(map[string]any{"Count": "32"}), qt.Equals, "32") c.Assert(getPluralCount(map[string]any{"Count": "32.5"}), qt.Equals, "32.5") c.Assert(getPluralCount(map[string]any{"count": 32}), qt.Equals, 32) c.Assert(getPluralCount(map[string]any{"Count": "32"}), qt.Equals, "32") c.Assert(getPluralCount(map[string]any{"Counts": 32}), qt.Equals, nil) c.Assert(getPluralCount("foo"), qt.Equals, nil) c.Assert(getPluralCount(countField{Count: 22}), qt.Equals, 22) c.Assert(getPluralCount(countField{Count: 1.5}), qt.Equals, "1.5") c.Assert(getPluralCount(&countField{Count: 22}), qt.Equals, 22) c.Assert(getPluralCount(noCountField{Counts: 23}), qt.Equals, nil) c.Assert(getPluralCount(countMethod{}), qt.Equals, "32.5") c.Assert(getPluralCount(&countMethod{}), qt.Equals, "32.5") c.Assert(getPluralCount(1234), qt.Equals, 1234) c.Assert(getPluralCount(1234.4), qt.Equals, "1234.4") c.Assert(getPluralCount(1234.0), qt.Equals, "1234.0") c.Assert(getPluralCount("1234"), qt.Equals, "1234") c.Assert(getPluralCount("0.5"), qt.Equals, "0.5") c.Assert(getPluralCount(nil), qt.Equals, nil) } func prepareTranslationProvider(t testing.TB, test i18nTest, cfg config.Provider) *TranslationProvider { c := qt.New(t) afs := afero.NewMemMapFs() for file, content := range test.data { err := afero.WriteFile(afs, filepath.Join("i18n", file), []byte(content), 0o755) c.Assert(err, qt.IsNil) } _, tp := prepareDeps(afs, cfg) return tp } func prepareDeps(afs afero.Fs, cfg config.Provider) (*deps.Deps, *TranslationProvider) { d := testconfig.GetTestDeps(afs, cfg) translationProvider := NewTranslationProvider() d.TranslationProvider = translationProvider d.Site = page.NewDummyHugoSite(d.Conf) if err := d.Compile(nil); err != nil { panic(err) } return d, translationProvider } func TestI18nTranslate(t *testing.T) { c := qt.New(t) var actual, expected string v := config.New() // Test without and with placeholders for _, enablePlaceholders := range []bool{false, true} { v.Set("enableMissingTranslationPlaceholders", enablePlaceholders) for _, test := range i18nTests { c.Run(fmt.Sprintf("%s-%t", test.name, enablePlaceholders), func(c *qt.C) { if enablePlaceholders { expected = test.expectedFlag } else { expected = test.expected } actual = doTestI18nTranslate(c, test, v) c.Assert(actual, qt.Equals, expected) }) } } } func BenchmarkI18nTranslate(b *testing.B) { v := config.New() for _, test := range i18nTests { b.Run(test.name, func(b *testing.B) { tp := prepareTranslationProvider(b, test, v) b.ResetTimer() for b.Loop() { f := tp.t.Func(test.lang) actual := f(context.Background(), test.id, test.args) if actual != test.expected { b.Fatalf("expected %v got %v", test.expected, actual) } } }) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/api.go
internal/js/api.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 import ( "context" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" ) // BatcherClient is used to do JS batch operations. type BatcherClient interface { New(id string) (Batcher, error) Store() *maps.Cache[string, Batcher] } // BatchPackage holds a group of JavaScript resources. type BatchPackage interface { Groups() map[string]resource.Resources } // Batcher is used to build JavaScript packages. type Batcher interface { Build(context.Context) (BatchPackage, error) Config(ctx context.Context) OptionsSetter Group(ctx context.Context, id string) BatcherGroup } // BatcherGroup is a group of scripts and instances. type BatcherGroup interface { Instance(sid, iid string) OptionsSetter Runner(id string) OptionsSetter Script(id string) OptionsSetter } // OptionsSetter is used to set options for a batch, script or instance. type OptionsSetter interface { SetOptions(map[string]any) string }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/esbuild/batch_integration_test.go
internal/js/esbuild/batch_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 js provides functions for building JavaScript resources package esbuild_test import ( "os" "path/filepath" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/bep/logg" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/internal/js/esbuild" ) // Used to test misc. error situations etc. const jsBatchFilesTemplate = ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "section"] disableLiveReload = true -- assets/js/styles.css -- body { background-color: red; } -- assets/js/main.js -- import './styles.css'; import * as params from '@params'; import * as foo from 'mylib'; console.log("Hello, Main!"); console.log("params.p1", params.p1); export default function Main() {}; -- assets/js/runner.js -- console.log("Hello, Runner!"); -- node_modules/mylib/index.js -- console.log("Hello, My Lib!"); -- layouts/_shortcodes/hdx.html -- {{ $path := .Get "r" }} {{ $r := or (.Page.Resources.Get $path) (resources.Get $path) }} {{ $batch := (js.Batch "mybatch") }} {{ $scriptID := $path | anchorize }} {{ $instanceID := .Ordinal | string }} {{ $group := .Page.RelPermalink | anchorize }} {{ $params := .Params | default dict }} {{ $export := .Get "export" | default "default" }} {{ with $batch.Group $group }} {{ with .Runner "create-elements" }} {{ .SetOptions (dict "resource" (resources.Get "js/runner.js")) }} {{ end }} {{ with .Script $scriptID }} {{ .SetOptions (dict "resource" $r "export" $export "importContext" (slice $.Page) ) }} {{ end }} {{ with .Instance $scriptID $instanceID }} {{ .SetOptions (dict "params" $params) }} {{ end }} {{ end }} hdx-instance: {{ $scriptID }}: {{ $instanceID }}| -- layouts/baseof.html -- Base. {{ $batch := (js.Batch "mybatch") }} {{ with $batch.Config }} {{ .SetOptions (dict "params" (dict "id" "config") "sourceMap" "" ) }} {{ end }} {{ with (templates.Defer (dict "key" "global")) }} Defer: {{ $batch := (js.Batch "mybatch") }} {{ range $k, $v := $batch.Build.Groups }} {{ range $kk, $vv := . -}} {{ $k }}: {{ .RelPermalink }} {{ end }} {{ end -}} {{ end }} {{ block "main" . }}Main{{ end }} End. -- layouts/single.html -- {{ define "main" }} ==> Single Template Content: {{ .Content }}$ {{ $batch := (js.Batch "mybatch") }} {{ with $batch.Group "mygroup" }} {{ with .Runner "run" }} {{ .SetOptions (dict "resource" (resources.Get "js/runner.js")) }} {{ end }} {{ with .Script "main" }} {{ .SetOptions (dict "resource" (resources.Get "js/main.js") "params" (dict "p1" "param-p1-main" )) }} {{ end }} {{ with .Instance "main" "i1" }} {{ .SetOptions (dict "params" (dict "title" "Instance 1")) }} {{ end }} {{ end }} {{ end }} -- layouts/home.html -- {{ define "main" }} Home. {{ end }} -- content/p1/index.md -- --- title: "P1" --- Some content. {{< hdx r="p1script.js" myparam="p1-param-1" >}} {{< hdx r="p1script.js" myparam="p1-param-2" >}} -- content/p1/p1script.js -- console.log("P1 Script"); ` // Just to verify that the above file setup works. func TestBatchTemplateOKBuild(t *testing.T) { b := hugolib.Test(t, jsBatchFilesTemplate, hugolib.TestOptWithOSFs()) b.AssertPublishDir("mybatch/mygroup.js", "mybatch/mygroup.css") } func TestBatchRemoveAllInGroup(t *testing.T) { files := jsBatchFilesTemplate b := hugolib.TestRunning(t, files, hugolib.TestOptWithOSFs()) b.AssertFileContent("public/p1/index.html", "p1: /mybatch/p1.js") b.EditFiles("content/p1/index.md", ` --- title: "P1" --- Empty. `) b.Build() b.AssertFileContent("public/p1/index.html", "! p1: /mybatch/p1.js") // Add one script back. b.EditFiles("content/p1/index.md", ` --- title: "P1" --- {{< hdx r="p1script.js" myparam="p1-param-1-new" >}} `) b.Build() b.AssertFileContent("public/mybatch/p1.js", "p1-param-1-new", "p1script.js") } func TestBatchEditInstance(t *testing.T) { files := jsBatchFilesTemplate b := hugolib.TestRunning(t, files, hugolib.TestOptWithOSFs()) b.AssertFileContent("public/mybatch/mygroup.js", "Instance 1") b.EditFileReplaceAll("layouts/single.html", "Instance 1", "Instance 1 Edit").Build() b.AssertFileContent("public/mybatch/mygroup.js", "Instance 1 Edit") } func TestBatchEditScriptParam(t *testing.T) { files := jsBatchFilesTemplate b := hugolib.TestRunning(t, files, hugolib.TestOptWithOSFs()) b.AssertFileContent("public/mybatch/mygroup.js", "param-p1-main") b.EditFileReplaceAll("layouts/single.html", "param-p1-main", "param-p1-main-edited").Build() b.AssertFileContent("public/mybatch/mygroup.js", "param-p1-main-edited") } func TestBatchMultiHost(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "section"] [languages] [languages.en] weight = 1 baseURL = "https://example.com/en" [languages.fr] weight = 2 baseURL = "https://example.com/fr" disableLiveReload = true -- assets/js/styles.css -- body { background-color: red; } -- assets/js/main.js -- import * as foo from 'mylib'; console.log("Hello, Main!"); -- assets/js/runner.js -- console.log("Hello, Runner!"); -- node_modules/mylib/index.js -- console.log("Hello, My Lib!"); -- layouts/home.html -- Home. {{ $batch := (js.Batch "mybatch") }} {{ with $batch.Config }} {{ .SetOptions (dict "params" (dict "id" "config") "sourceMap" "" ) }} {{ end }} {{ with (templates.Defer (dict "key" "global")) }} Defer: {{ $batch := (js.Batch "mybatch") }} {{ range $k, $v := $batch.Build.Groups }} {{ range $kk, $vv := . -}} {{ $k }}: {{ .RelPermalink }} {{ end }} {{ end -}} {{ end }} {{ $batch := (js.Batch "mybatch") }} {{ with $batch.Group "mygroup" }} {{ with .Runner "run" }} {{ .SetOptions (dict "resource" (resources.Get "js/runner.js")) }} {{ end }} {{ with .Script "main" }} {{ .SetOptions (dict "resource" (resources.Get "js/main.js") "params" (dict "p1" "param-p1-main" )) }} {{ end }} {{ with .Instance "main" "i1" }} {{ .SetOptions (dict "params" (dict "title" "Instance 1")) }} {{ end }} {{ end }} ` b := hugolib.Test(t, files, hugolib.TestOptWithOSFs()) b.AssertPublishDir( "en/mybatch/chunk-TOZKWCDE.js", "en/mybatch/mygroup.js ", "fr/mybatch/mygroup.js", "fr/mybatch/chunk-TOZKWCDE.js") } func TestBatchRenameBundledScript(t *testing.T) { files := jsBatchFilesTemplate b := hugolib.TestRunning(t, files, hugolib.TestOptWithOSFs()) b.AssertFileContent("public/mybatch/p1.js", "P1 Script") b.RenameFile("content/p1/p1script.js", "content/p1/p1script2.js") _, err := b.BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "resource not set") // Rename it back. b.RenameFile("content/p1/p1script2.js", "content/p1/p1script.js") b.Build() } func TestBatchErrorScriptResourceNotSet(t *testing.T) { files := strings.Replace(jsBatchFilesTemplate, `(resources.Get "js/main.js")`, `(resources.Get "js/doesnotexist.js")`, 1) b, err := hugolib.TestE(t, files, hugolib.TestOptWithOSFs()) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `error calling SetOptions: resource not set`) } func TestBatchSlashInBatchID(t *testing.T) { files := strings.ReplaceAll(jsBatchFilesTemplate, `"mybatch"`, `"my/batch"`) b, err := hugolib.TestE(t, files, hugolib.TestOptWithOSFs()) b.Assert(err, qt.IsNil) b.AssertPublishDir("my/batch/mygroup.js") } func TestBatchSourceMaps(t *testing.T) { filesTemplate := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "section"] disableLiveReload = true -- assets/js/styles.css -- body { background-color: red; } -- assets/js/main.js -- import * as foo from 'mylib'; console.log("Hello, Main!"); -- assets/js/runner.js -- console.log("Hello, Runner!"); -- node_modules/mylib/index.js -- console.log("Hello, My Lib!"); -- layouts/_shortcodes/hdx.html -- {{ $path := .Get "r" }} {{ $r := or (.Page.Resources.Get $path) (resources.Get $path) }} {{ $batch := (js.Batch "mybatch") }} {{ $scriptID := $path | anchorize }} {{ $instanceID := .Ordinal | string }} {{ $group := .Page.RelPermalink | anchorize }} {{ $params := .Params | default dict }} {{ $export := .Get "export" | default "default" }} {{ with $batch.Group $group }} {{ with .Runner "create-elements" }} {{ .SetOptions (dict "resource" (resources.Get "js/runner.js")) }} {{ end }} {{ with .Script $scriptID }} {{ .SetOptions (dict "resource" $r "export" $export "importContext" (slice $.Page) ) }} {{ end }} {{ with .Instance $scriptID $instanceID }} {{ .SetOptions (dict "params" $params) }} {{ end }} {{ end }} hdx-instance: {{ $scriptID }}: {{ $instanceID }}| -- layouts/baseof.html -- Base. {{ $batch := (js.Batch "mybatch") }} {{ with $batch.Config }} {{ .SetOptions (dict "params" (dict "id" "config") "sourceMap" "" ) }} {{ end }} {{ with (templates.Defer (dict "key" "global")) }} Defer: {{ $batch := (js.Batch "mybatch") }} {{ range $k, $v := $batch.Build.Groups }} {{ range $kk, $vv := . -}} {{ $k }}: {{ .RelPermalink }} {{ end }} {{ end -}} {{ end }} {{ block "main" . }}Main{{ end }} End. -- layouts/single.html -- {{ define "main" }} ==> Single Template Content: {{ .Content }}$ {{ $batch := (js.Batch "mybatch") }} {{ with $batch.Group "mygroup" }} {{ with .Runner "run" }} {{ .SetOptions (dict "resource" (resources.Get "js/runner.js")) }} {{ end }} {{ with .Script "main" }} {{ .SetOptions (dict "resource" (resources.Get "js/main.js") "params" (dict "p1" "param-p1-main" )) }} {{ end }} {{ with .Instance "main" "i1" }} {{ .SetOptions (dict "params" (dict "title" "Instance 1")) }} {{ end }} {{ end }} {{ end }} -- layouts/home.html -- {{ define "main" }} Home. {{ end }} -- content/p1/index.md -- --- title: "P1" --- Some content. {{< hdx r="p1script.js" myparam="p1-param-1" >}} {{< hdx r="p1script.js" myparam="p1-param-2" >}} -- content/p1/p1script.js -- import * as foo from 'mylib'; console.lg("Foo", foo); console.log("P1 Script"); export default function P1Script() {}; ` files := strings.Replace(filesTemplate, `"sourceMap" ""`, `"sourceMap" "linked"`, 1) b := hugolib.TestRunning(t, files, hugolib.TestOptWithOSFs()) b.AssertFileContent("public/mybatch/mygroup.js.map", "main.js", "! ns-hugo") b.AssertFileContent("public/mybatch/mygroup.js", "sourceMappingURL=mygroup.js.map") b.AssertFileContent("public/mybatch/p1.js", "sourceMappingURL=p1.js.map") b.AssertFileContent("public/mybatch/mygroup_run_runner.js", "sourceMappingURL=mygroup_run_runner.js.map") b.AssertFileContent("public/mybatch/chunk-UQKPPNA6.js", "sourceMappingURL=chunk-UQKPPNA6.js.map") checkMap := func(p string, expectLen int) { s := b.FileContent(p) sources := esbuild.SourcesFromSourceMap(s) b.Assert(sources, qt.HasLen, expectLen) // Check that all source files exist. for _, src := range sources { filename, ok := paths.UrlStringToFilename(src) b.Assert(ok, qt.IsTrue) _, err := os.Stat(filename) b.Assert(err, qt.IsNil) } } checkMap("public/mybatch/mygroup.js.map", 1) checkMap("public/mybatch/p1.js.map", 1) checkMap("public/mybatch/mygroup_run_runner.js.map", 0) checkMap("public/mybatch/chunk-UQKPPNA6.js.map", 1) } func TestBatchErrorRunnerResourceNotSet(t *testing.T) { files := strings.Replace(jsBatchFilesTemplate, `(resources.Get "js/runner.js")`, `(resources.Get "js/doesnotexist.js")`, 1) b, err := hugolib.TestE(t, files, hugolib.TestOptWithOSFs()) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `resource not set`) } func TestBatchErrorScriptResourceInAssetsSyntaxError(t *testing.T) { // Introduce JS syntax error in assets/js/main.js files := strings.Replace(jsBatchFilesTemplate, `console.log("Hello, Main!");`, `console.log("Hello, Main!"`, 1) b, err := hugolib.TestE(t, files, hugolib.TestOptWithOSFs()) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`assets/js/main.js:5:0": Expected ")" but found "console"`)) } func TestBatchErrorScriptResourceInBundleSyntaxError(t *testing.T) { // Introduce JS syntax error in content/p1/p1script.js files := strings.Replace(jsBatchFilesTemplate, `console.log("P1 Script");`, `console.log("P1 Script"`, 1) b, err := hugolib.TestE(t, files, hugolib.TestOptWithOSFs()) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`/content/p1/p1script.js:3:0": Expected ")" but found end of file`)) } func TestBatch(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] disableLiveReload = true baseURL = "https://example.com" -- package.json -- { "devDependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } } -- assets/js/shims/react.js -- -- assets/js/shims/react-dom.js -- module.exports = window.ReactDOM; module.exports = window.React; -- content/mybundle/index.md -- --- title: "My Bundle" --- -- content/mybundle/mybundlestyles.css -- @import './foo.css'; @import './bar.css'; @import './otherbundlestyles.css'; .mybundlestyles { background-color: blue; } -- content/mybundle/bundlereact.jsx -- import * as React from "react"; import './foo.css'; import './mybundlestyles.css'; window.React1 = React; let text = 'Click me, too!' export default function MyBundleButton() { return ( <button>${text}</button> ) } -- assets/js/reactrunner.js -- import * as ReactDOM from 'react-dom/client'; import * as React from 'react'; export default function Run(group) { for (const module of group.scripts) { for (const instance of module.instances) { /* This is a convention in this project. */ let elId = §§${module.id}-${instance.id}§§; let el = document.getElementById(elId); if (!el) { console.warn(§§Element with id ${elId} not found§§); continue; } const root = ReactDOM.createRoot(el); const reactEl = React.createElement(module.mod, instance.params); root.render(reactEl); } } } -- assets/other/otherbundlestyles.css -- .otherbundlestyles { background-color: red; } -- assets/other/foo.css -- @import './bar.css'; .foo { background-color: blue; } -- assets/other/bar.css -- .bar { background-color: red; } -- assets/js/button.css -- button { background-color: red; } -- assets/js/bar.css -- .bar-assets { background-color: red; } -- assets/js/helper.js -- import './bar.css' export function helper() { console.log('helper'); } -- assets/js/react1styles_nested.css -- .react1styles_nested { background-color: red; } -- assets/js/react1styles.css -- @import './react1styles_nested.css'; .react1styles { background-color: red; } -- assets/js/react1.jsx -- import * as React from "react"; import './button.css' import './foo.css' import './react1styles.css' window.React1 = React; let text = 'Click me' export default function MyButton() { return ( <button>${text}</button> ) } -- assets/js/react2.jsx -- import * as React from "react"; import { helper } from './helper.js' import './foo.css' window.React2 = React; let text = 'Click me, too!' export function MyOtherButton() { return ( <button>${text}</button> ) } -- assets/js/main1.js -- import * as React from "react"; import * as params from '@params'; console.log('main1.React', React) console.log('main1.params.id', params.id) -- assets/js/main2.js -- import * as React from "react"; import * as params from '@params'; console.log('main2.React', React) console.log('main2.params.id', params.id) export default function Main2() {}; -- assets/js/main3.js -- import * as React from "react"; import * as params from '@params'; import * as config from '@params/config'; console.log('main3.params.id', params.id) console.log('config.params.id', config.id) export default function Main3() {}; -- layouts/single.html -- Single. {{ $r := .Resources.GetMatch "*.jsx" }} {{ $batch := (js.Batch "mybundle") }} {{ $otherCSS := (resources.Match "/other/*.css").Mount "/other" "." }} {{ with $batch.Config }} {{ $shims := dict "react" "js/shims/react.js" "react-dom/client" "js/shims/react-dom.js" }} {{ .SetOptions (dict "target" "es2018" "params" (dict "id" "config") "shims" $shims ) }} {{ end }} {{ with $batch.Group "reactbatch" }} {{ with .Script "r3" }} {{ .SetOptions (dict "resource" $r "importContext" (slice $ $otherCSS) "params" (dict "id" "r3") ) }} {{ end }} {{ with .Instance "r3" "r2i1" }} {{ .SetOptions (dict "title" "r2 instance 1")}} {{ end }} {{ end }} -- layouts/home.html -- Home. {{ with (templates.Defer (dict "key" "global")) }} {{ $batch := (js.Batch "mybundle") }} {{ range $k, $v := $batch.Build.Groups }} {{ range $kk, $vv := . }} {{ $k }}: {{ $kk }}: {{ .RelPermalink }} {{ end }} {{ end }} {{ end }} {{ $myContentBundle := site.GetPage "mybundle" }} {{ $batch := (js.Batch "mybundle") }} {{ $otherCSS := (resources.Match "/other/*.css").Mount "/other" "." }} {{ with $batch.Group "mains" }} {{ with .Script "main1" }} {{ .SetOptions (dict "resource" (resources.Get "js/main1.js") "params" (dict "id" "main1") ) }} {{ end }} {{ with .Script "main2" }} {{ .SetOptions (dict "resource" (resources.Get "js/main2.js") "params" (dict "id" "main2") ) }} {{ end }} {{ with .Script "main3" }} {{ .SetOptions (dict "resource" (resources.Get "js/main3.js") ) }} {{ end }} {{ with .Instance "main1" "m1i1" }}{{ .SetOptions (dict "params" (dict "title" "Main1 Instance 1"))}}{{ end }} {{ with .Instance "main1" "m1i2" }}{{ .SetOptions (dict "params" (dict "title" "Main1 Instance 2"))}}{{ end }} {{ end }} {{ with $batch.Group "reactbatch" }} {{ with .Runner "reactrunner" }} {{ .SetOptions ( dict "resource" (resources.Get "js/reactrunner.js") )}} {{ end }} {{ with .Script "r1" }} {{ .SetOptions (dict "resource" (resources.Get "js/react1.jsx") "importContext" (slice $myContentBundle $otherCSS) "params" (dict "id" "r1") ) }} {{ end }} {{ with .Instance "r1" "i1" }}{{ .SetOptions (dict "params" (dict "title" "Instance 1"))}}{{ end }} {{ with .Instance "r1" "i2" }}{{ .SetOptions (dict "params" (dict "title" "Instance 2"))}}{{ end }} {{ with .Script "r2" }} {{ .SetOptions (dict "resource" (resources.Get "js/react2.jsx") "export" "MyOtherButton" "importContext" $otherCSS "params" (dict "id" "r2") ) }} {{ end }} {{ with .Instance "r2" "i1" }}{{ .SetOptions (dict "params" (dict "title" "Instance 2-1"))}}{{ end }} {{ end }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, NeedsOsFS: true, NeedsNpmInstall: true, TxtarString: files, Running: true, LogLevel: logg.LevelWarn, // PrintAndKeepTempDir: true, }).Build() b.AssertFileContent("public/index.html", "mains: 0: /mybundle/mains.js", "reactbatch: 2: /mybundle/reactbatch.css", ) b.AssertFileContent("public/mybundle/reactbatch.css", ".bar {", ) // Verify params resolution. b.AssertFileContent("public/mybundle/mains.js", ` var id = "main1"; console.log("main1.params.id", id); var id2 = "main2"; console.log("main2.params.id", id2); # Params from top level config. var id3 = "config"; console.log("main3.params.id", void 0); console.log("config.params.id", id3); `) b.EditFileReplaceAll("content/mybundle/mybundlestyles.css", ".mybundlestyles", ".mybundlestyles-edit").Build() b.AssertFileContent("public/mybundle/reactbatch.css", ".mybundlestyles-edit {") b.EditFileReplaceAll("assets/other/bar.css", ".bar {", ".bar-edit {").Build() b.AssertFileContent("public/mybundle/reactbatch.css", ".bar-edit {") b.EditFileReplaceAll("assets/other/bar.css", ".bar-edit {", ".bar-edit2 {").Build() b.AssertFileContent("public/mybundle/reactbatch.css", ".bar-edit2 {") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/esbuild/build.go
internal/js/esbuild/build.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 esbuild provides functions for building JavaScript resources. package esbuild import ( "errors" "fmt" "os" "path/filepath" "strings" "github.com/evanw/esbuild/pkg/api" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources" ) // NewBuildClient creates a new BuildClient. func NewBuildClient(fs *filesystems.SourceFilesystem, rs *resources.Spec) *BuildClient { return &BuildClient{ rs: rs, sfs: fs, } } // BuildClient is a client for building JavaScript resources using esbuild. type BuildClient struct { rs *resources.Spec sfs *filesystems.SourceFilesystem } // Build builds the given JavaScript resources using esbuild with the given options. func (c *BuildClient) Build(opts Options) (api.BuildResult, error) { dependencyManager := opts.DependencyManager if dependencyManager == nil { dependencyManager = identity.NopManager } opts.OutDir = c.rs.AbsPublishDir opts.ResolveDir = c.rs.Cfg.BaseConfig().WorkingDir // where node_modules gets resolved opts.AbsWorkingDir = opts.ResolveDir opts.TsConfig = c.rs.ResolveJSConfigFile("tsconfig.json") assetsResolver := newFSResolver(c.rs.Assets.Fs) if err := opts.validate(); err != nil { return api.BuildResult{}, err } if err := opts.compile(); err != nil { return api.BuildResult{}, err } var err error opts.compiled.Plugins, err = createBuildPlugins(c.rs, assetsResolver, dependencyManager, opts) if err != nil { return api.BuildResult{}, err } if opts.Inject != nil { // Resolve the absolute filenames. for i, ext := range opts.Inject { impPath := filepath.FromSlash(ext) if filepath.IsAbs(impPath) { return api.BuildResult{}, fmt.Errorf("inject: absolute paths not supported, must be relative to /assets") } m := assetsResolver.resolveComponent(impPath) if m == nil { return api.BuildResult{}, fmt.Errorf("inject: file %q not found", ext) } opts.Inject[i] = m.Filename } opts.compiled.Inject = opts.Inject } result := api.Build(opts.compiled) if len(result.Errors) > 0 { createErr := func(msg api.Message) error { if msg.Location == nil { return errors.New(msg.Text) } var ( contentr hugio.ReadSeekCloser errorMessage string loc = msg.Location errorPath = loc.File err error ) var resolvedError *ErrorMessageResolved if opts.ErrorMessageResolveFunc != nil { resolvedError = opts.ErrorMessageResolveFunc(msg) } if resolvedError == nil { if errorPath == stdinImporter { errorPath = opts.StdinSourcePath } errorMessage = msg.Text var namespace string for _, ns := range hugoNamespaces { if strings.HasPrefix(errorPath, ns) { namespace = ns break } } if namespace != "" { namespace += ":" errorMessage = strings.ReplaceAll(errorMessage, namespace, "") errorPath = strings.TrimPrefix(errorPath, namespace) contentr, err = hugofs.Os.Open(errorPath) } else { var fi os.FileInfo fi, err = c.sfs.Fs.Stat(errorPath) if err == nil { m := fi.(hugofs.FileMetaInfo).Meta() errorPath = m.Filename contentr, err = m.Open() } } } else { contentr = resolvedError.Content errorPath = resolvedError.Path errorMessage = resolvedError.Message } if contentr != nil { defer contentr.Close() } if err == nil { fe := herrors. NewFileErrorFromName(errors.New(errorMessage), errorPath). UpdatePosition(text.Position{Offset: -1, LineNumber: loc.Line, ColumnNumber: loc.Column}). UpdateContent(contentr, nil) return fe } return fmt.Errorf("%s", errorMessage) } var errors []error for _, msg := range result.Errors { errors = append(errors, createErr(msg)) } // Return 1, log the rest. for i, err := range errors { if i > 0 { c.rs.Logger.Errorf("js.Build failed: %s", err) } } return result, errors[0] } inOutputPathToAbsFilename := opts.ResolveSourceMapSource opts.ResolveSourceMapSource = func(s string) string { if inOutputPathToAbsFilename != nil { if filename := inOutputPathToAbsFilename(s); filename != "" { return filename } } if m := assetsResolver.resolveComponent(s); m != nil { return m.Filename } return "" } for i, o := range result.OutputFiles { if err := fixOutputFile(&o, func(s string) string { if s == "<stdin>" { return opts.ResolveSourceMapSource(opts.StdinSourcePath) } var isNsHugo bool if strings.HasPrefix(s, "ns-hugo") { isNsHugo = true idxColon := strings.Index(s, ":") s = s[idxColon+1:] } if !strings.HasPrefix(s, PrefixHugoVirtual) { if !filepath.IsAbs(s) { s = filepath.Join(opts.OutDir, s) } } if isNsHugo { if ss := opts.ResolveSourceMapSource(s); ss != "" { if strings.HasPrefix(ss, PrefixHugoMemory) { // File not on disk, mark it for removal from the sources slice. return "" } return ss } return "" } return s }); err != nil { return result, err } result.OutputFiles[i] = o } return result, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/esbuild/resolve.go
internal/js/esbuild/resolve.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 esbuild import ( "encoding/json" "fmt" "os" "path/filepath" "strings" "github.com/evanw/esbuild/pkg/api" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/spf13/afero" "slices" ) const ( NsHugoImport = "ns-hugo-imp" NsHugoImportResolveFunc = "ns-hugo-imp-func" nsHugoParams = "ns-hugo-params" pathHugoConfigParams = "@params/config" stdinImporter = "<stdin>" ) var hugoNamespaces = []string{NsHugoImport, NsHugoImportResolveFunc, nsHugoParams} const ( PrefixHugoVirtual = "__hu_v" PrefixHugoMemory = "__hu_m" ) var extensionToLoaderMap = map[string]api.Loader{ ".js": api.LoaderJS, ".mjs": api.LoaderJS, ".cjs": api.LoaderJS, ".jsx": api.LoaderJSX, ".ts": api.LoaderTS, ".tsx": api.LoaderTSX, ".css": api.LoaderCSS, ".json": api.LoaderJSON, ".txt": api.LoaderText, } // This is a common sub-set of ESBuild's default extensions. // We assume that imports of JSON, CSS etc. will be using their full // name with extension. var commonExtensions = []string{".js", ".ts", ".tsx", ".jsx"} // ResolveComponent resolves a component using the given resolver. func ResolveComponent[T any](impPath string, resolve func(string) (v T, found, isDir bool)) (v T, found bool) { findFirst := func(base string) (v T, found, isDir bool) { for _, ext := range commonExtensions { if strings.HasSuffix(impPath, ext) { // Import of foo.js.js need the full name. continue } if v, found, isDir = resolve(base + ext); found { return } } // Not found. return } // We need to check if this is a regular file imported without an extension. // There may be ambiguous situations where both foo.js and foo/index.js exists. // This import order is in line with both how Node and ESBuild's native // import resolver works. // It may be a regular file imported without an extension, e.g. // foo or foo/index. v, found, _ = findFirst(impPath) if found { return v, found } base := filepath.Base(impPath) if base == "index" { // try index.esm.js etc. v, found, _ = findFirst(impPath + ".esm") if found { return v, found } } // Check the path as is. var isDir bool v, found, isDir = resolve(impPath) if found && isDir { v, found, _ = findFirst(filepath.Join(impPath, "index")) if !found { v, found, _ = findFirst(filepath.Join(impPath, "index.esm")) } } if !found && strings.HasSuffix(base, ".js") { v, found, _ = findFirst(strings.TrimSuffix(impPath, ".js")) } return } // ResolveResource resolves a resource using the given resourceGetter. func ResolveResource(impPath string, resourceGetter resource.ResourceGetter) (r resource.Resource) { resolve := func(name string) (v resource.Resource, found, isDir bool) { r := resourceGetter.Get(name) return r, r != nil, false } r, found := ResolveComponent(impPath, resolve) if !found { return nil } return r } func newFSResolver(fs afero.Fs) *fsResolver { return &fsResolver{fs: fs, resolved: maps.NewCache[string, *hugofs.FileMeta]()} } type fsResolver struct { fs afero.Fs resolved *maps.Cache[string, *hugofs.FileMeta] } func (r *fsResolver) resolveComponent(impPath string) *hugofs.FileMeta { v, _ := r.resolved.GetOrCreate(impPath, func() (*hugofs.FileMeta, error) { resolve := func(name string) (*hugofs.FileMeta, bool, bool) { if fi, err := r.fs.Stat(name); err == nil { return fi.(hugofs.FileMetaInfo).Meta(), true, fi.IsDir() } return nil, false, false } v, _ := ResolveComponent(impPath, resolve) return v, nil }) return v } func createBuildPlugins(rs *resources.Spec, assetsResolver *fsResolver, depsManager identity.Manager, opts Options) ([]api.Plugin, error) { fs := rs.Assets resolveImport := func(args api.OnResolveArgs) (api.OnResolveResult, error) { impPath := args.Path shimmed := false if opts.Shims != nil { override, found := opts.Shims[impPath] if found { impPath = override shimmed = true } } if slices.Contains(opts.Externals, impPath) { return api.OnResolveResult{ Path: impPath, External: true, }, nil } if opts.ImportOnResolveFunc != nil { if s := opts.ImportOnResolveFunc(impPath, args); s != "" { return api.OnResolveResult{Path: s, Namespace: NsHugoImportResolveFunc}, nil } } importer := args.Importer isStdin := importer == stdinImporter var relDir string if !isStdin { if after, ok := strings.CutPrefix(importer, PrefixHugoVirtual); ok { relDir = filepath.Dir(after) } else { rel, found := fs.MakePathRelative(importer, true) if !found { if shimmed { relDir = opts.SourceDir } else { // Not in any of the /assets folders. // This is an import from a node_modules, let // ESBuild resolve this. return api.OnResolveResult{}, nil } } else { relDir = filepath.Dir(rel) } } } else { relDir = opts.SourceDir } // Imports not starting with a "." is assumed to live relative to /assets. // Hugo makes no assumptions about the directory structure below /assets. if relDir != "" && strings.HasPrefix(impPath, ".") { impPath = filepath.Join(relDir, impPath) } m := assetsResolver.resolveComponent(impPath) if m != nil { depsManager.AddIdentity(m.PathInfo) // Store the source root so we can create a jsconfig.json // to help IntelliSense when the build is done. // This should be a small number of elements, and when // in server mode, we may get stale entries on renames etc., // but that shouldn't matter too much. rs.JSConfigBuilder.AddSourceRoot(m.SourceRoot) return api.OnResolveResult{Path: m.Filename, Namespace: NsHugoImport}, nil } // Fall back to ESBuild's resolve. return api.OnResolveResult{}, nil } importResolver := api.Plugin{ Name: "hugo-import-resolver", Setup: func(build api.PluginBuild) { build.OnResolve(api.OnResolveOptions{Filter: `.*`}, func(args api.OnResolveArgs) (api.OnResolveResult, error) { return resolveImport(args) }) build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: NsHugoImport}, func(args api.OnLoadArgs) (api.OnLoadResult, error) { b, err := os.ReadFile(args.Path) if err != nil { return api.OnLoadResult{}, fmt.Errorf("failed to read %q: %w", args.Path, err) } c := string(b) return api.OnLoadResult{ // See https://github.com/evanw/esbuild/issues/502 // This allows all modules to resolve dependencies // in the main project's node_modules. ResolveDir: opts.ResolveDir, Contents: &c, Loader: opts.loaderFromFilename(args.Path), }, nil }) build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: NsHugoImportResolveFunc}, func(args api.OnLoadArgs) (api.OnLoadResult, error) { c := opts.ImportOnLoadFunc(args) if c == "" { return api.OnLoadResult{}, fmt.Errorf("ImportOnLoadFunc failed to resolve %q", args.Path) } return api.OnLoadResult{ ResolveDir: opts.ResolveDir, Contents: &c, Loader: opts.loaderFromFilename(args.Path), }, nil }) }, } params := opts.Params if params == nil { // This way @params will always resolve to something. params = make(map[string]any) } b, err := json.Marshal(params) if err != nil { return nil, fmt.Errorf("failed to marshal params: %w", err) } paramsPlugin := api.Plugin{ Name: "hugo-params-plugin", Setup: func(build api.PluginBuild) { build.OnResolve(api.OnResolveOptions{Filter: `^@params(/config)?$`}, func(args api.OnResolveArgs) (api.OnResolveResult, error) { resolvedPath := args.Importer if args.Path == pathHugoConfigParams { resolvedPath = pathHugoConfigParams } return api.OnResolveResult{ Path: resolvedPath, Namespace: nsHugoParams, }, nil }) build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: nsHugoParams}, func(args api.OnLoadArgs) (api.OnLoadResult, error) { bb := b if args.Path != pathHugoConfigParams && opts.ImportParamsOnLoadFunc != nil { bb = opts.ImportParamsOnLoadFunc(args) } s := string(bb) if s == "" { s = "{}" } return api.OnLoadResult{ Contents: &s, Loader: api.LoaderJSON, }, nil }) }, } return []api.Plugin{importResolver, paramsPlugin}, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/esbuild/resolve_test.go
internal/js/esbuild/resolve_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 esbuild import ( "path" "path/filepath" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/hugolib/paths" "github.com/spf13/afero" ) func TestResolveComponentInAssets(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string files []string impPath string expect string }{ {"Basic, extension", []string{"foo.js", "bar.js"}, "foo.js", "foo.js"}, {"Basic, no extension", []string{"foo.js", "bar.js"}, "foo", "foo.js"}, {"Basic, no extension, typescript", []string{"foo.ts", "bar.js"}, "foo", "foo.ts"}, {"Not found", []string{"foo.js", "bar.js"}, "moo.js", ""}, {"Not found, double js extension", []string{"foo.js.js", "bar.js"}, "foo.js", ""}, {"Index file, folder only", []string{"foo/index.js", "bar.js"}, "foo", "foo/index.js"}, {"Index file, folder and index", []string{"foo/index.js", "bar.js"}, "foo/index", "foo/index.js"}, {"Index file, folder and index and suffix", []string{"foo/index.js", "bar.js"}, "foo/index.js", "foo/index.js"}, {"Index ESM file, folder only", []string{"foo/index.esm.js", "bar.js"}, "foo", "foo/index.esm.js"}, {"Index ESM file, folder and index", []string{"foo/index.esm.js", "bar.js"}, "foo/index", "foo/index.esm.js"}, {"Index ESM file, folder and index and suffix", []string{"foo/index.esm.js", "bar.js"}, "foo/index.esm.js", "foo/index.esm.js"}, // We added these index.esm.js cases in v0.101.0. The case below is unlikely to happen in the wild, but add a test // to document Hugo's behavior. We pick the file with the name index.js; anything else would be breaking. {"Index and Index ESM file, folder only", []string{"foo/index.esm.js", "foo/index.js", "bar.js"}, "foo", "foo/index.js"}, // Issue #8949 {"Check file before directory", []string{"foo.js", "foo/index.js"}, "foo", "foo.js"}, } { c.Run(test.name, func(c *qt.C) { baseDir := "assets" mfs := afero.NewMemMapFs() for _, filename := range test.files { c.Assert(afero.WriteFile(mfs, filepath.Join(baseDir, filename), []byte("let foo='bar';"), 0o777), qt.IsNil) } conf := testconfig.GetTestConfig(mfs, config.New()) fs := hugofs.NewFrom(mfs, conf.BaseConfig()) p, err := paths.New(fs, conf) c.Assert(err, qt.IsNil) bfs, err := filesystems.NewBase(p, nil) c.Assert(err, qt.IsNil) resolver := newFSResolver(bfs.Assets.Fs) got := resolver.resolveComponent(test.impPath) gotPath := "" expect := test.expect if got != nil { gotPath = filepath.ToSlash(got.Filename) expect = path.Join(baseDir, test.expect) } c.Assert(gotPath, qt.Equals, expect) }) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/esbuild/options_test.go
internal/js/esbuild/options_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 esbuild import ( "testing" "github.com/gohugoio/hugo/media" "github.com/evanw/esbuild/pkg/api" qt "github.com/frankban/quicktest" ) func TestToBuildOptions(t *testing.T) { c := qt.New(t) opts := Options{ InternalOptions: InternalOptions{ MediaType: media.Builtin.JavascriptType, Stdin: true, }, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled, qt.DeepEquals, api.BuildOptions{ Bundle: true, Target: api.ESNext, Format: api.FormatIIFE, Platform: api.PlatformBrowser, SourcesContent: 1, Stdin: &api.StdinOptions{ Loader: api.LoaderJS, }, }) opts = Options{ ExternalOptions: ExternalOptions{ Target: "es2018", Format: "cjs", Minify: true, AvoidTDZ: true, }, InternalOptions: InternalOptions{ MediaType: media.Builtin.JavascriptType, Stdin: true, }, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled, qt.DeepEquals, api.BuildOptions{ Bundle: true, Target: api.ES2018, Format: api.FormatCommonJS, Platform: api.PlatformBrowser, SourcesContent: 1, MinifyIdentifiers: true, MinifySyntax: true, MinifyWhitespace: true, Stdin: &api.StdinOptions{ Loader: api.LoaderJS, }, }) opts = Options{ ExternalOptions: ExternalOptions{ Target: "es2018", Format: "cjs", Minify: true, SourceMap: "inline", }, InternalOptions: InternalOptions{ MediaType: media.Builtin.JavascriptType, Stdin: true, }, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled, qt.DeepEquals, api.BuildOptions{ Bundle: true, Target: api.ES2018, Format: api.FormatCommonJS, Platform: api.PlatformBrowser, MinifyIdentifiers: true, MinifySyntax: true, MinifyWhitespace: true, SourcesContent: 1, Sourcemap: api.SourceMapInline, Stdin: &api.StdinOptions{ Loader: api.LoaderJS, }, }) opts = Options{ ExternalOptions: ExternalOptions{ Target: "es2018", Format: "cjs", Minify: true, SourceMap: "inline", }, InternalOptions: InternalOptions{ MediaType: media.Builtin.JavascriptType, Stdin: true, }, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled, qt.DeepEquals, api.BuildOptions{ Bundle: true, Target: api.ES2018, Format: api.FormatCommonJS, Platform: api.PlatformBrowser, MinifyIdentifiers: true, MinifySyntax: true, MinifyWhitespace: true, Sourcemap: api.SourceMapInline, SourcesContent: 1, Stdin: &api.StdinOptions{ Loader: api.LoaderJS, }, }) opts = Options{ ExternalOptions: ExternalOptions{ Target: "es2018", Format: "cjs", Minify: true, SourceMap: "external", }, InternalOptions: InternalOptions{ MediaType: media.Builtin.JavascriptType, Stdin: true, }, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled, qt.DeepEquals, api.BuildOptions{ Bundle: true, Target: api.ES2018, Format: api.FormatCommonJS, Platform: api.PlatformBrowser, MinifyIdentifiers: true, MinifySyntax: true, MinifyWhitespace: true, Sourcemap: api.SourceMapExternal, SourcesContent: 1, Stdin: &api.StdinOptions{ Loader: api.LoaderJS, }, }) opts = Options{ ExternalOptions: ExternalOptions{ JSX: "automatic", JSXImportSource: "preact", }, InternalOptions: InternalOptions{ MediaType: media.Builtin.JavascriptType, Stdin: true, }, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled, qt.DeepEquals, api.BuildOptions{ Bundle: true, Target: api.ESNext, Format: api.FormatIIFE, Platform: api.PlatformBrowser, SourcesContent: 1, Stdin: &api.StdinOptions{ Loader: api.LoaderJS, }, JSX: api.JSXAutomatic, JSXImportSource: "preact", }) opts = Options{ ExternalOptions: ExternalOptions{ Drop: "console", }, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled.Drop, qt.Equals, api.DropConsole) opts = Options{ ExternalOptions: ExternalOptions{ Drop: "debugger", }, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled.Drop, qt.Equals, api.DropDebugger) opts = Options{ ExternalOptions: ExternalOptions{ Drop: "adsfadsf", }, } c.Assert(opts.compile(), qt.ErrorMatches, `unsupported drop type: "adsfadsf"`) } func TestToBuildOptionsTarget(t *testing.T) { c := qt.New(t) for _, test := range []struct { target string expect api.Target }{ {"es2015", api.ES2015}, {"es2016", api.ES2016}, {"es2017", api.ES2017}, {"es2018", api.ES2018}, {"es2019", api.ES2019}, {"es2020", api.ES2020}, {"es2021", api.ES2021}, {"es2022", api.ES2022}, {"es2023", api.ES2023}, {"", api.ESNext}, {"esnext", api.ESNext}, } { c.Run(test.target, func(c *qt.C) { opts := Options{ ExternalOptions: ExternalOptions{ Target: test.target, }, InternalOptions: InternalOptions{ MediaType: media.Builtin.JavascriptType, }, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled.Target, qt.Equals, test.expect) }) } } func TestDecodeExternalOptions(t *testing.T) { c := qt.New(t) m := map[string]any{ "platform": "node", } ext, err := DecodeExternalOptions(m) c.Assert(err, qt.IsNil) c.Assert(ext, qt.DeepEquals, ExternalOptions{ SourcesContent: true, Platform: "node", }) opts := Options{ ExternalOptions: ext, } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled, qt.DeepEquals, api.BuildOptions{ Bundle: true, Target: api.ESNext, Format: api.FormatIIFE, Platform: api.PlatformNode, SourcesContent: api.SourcesContentInclude, }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/esbuild/options.go
internal/js/esbuild/options.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 esbuild import ( "encoding/json" "fmt" "path/filepath" "strings" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/identity" "github.com/evanw/esbuild/pkg/api" "github.com/gohugoio/hugo/media" "github.com/mitchellh/mapstructure" ) var ( nameTarget = map[string]api.Target{ "": api.ESNext, "esnext": api.ESNext, "es5": api.ES5, "es6": api.ES2015, "es2015": api.ES2015, "es2016": api.ES2016, "es2017": api.ES2017, "es2018": api.ES2018, "es2019": api.ES2019, "es2020": api.ES2020, "es2021": api.ES2021, "es2022": api.ES2022, "es2023": api.ES2023, "es2024": api.ES2024, } // source names: https://github.com/evanw/esbuild/blob/9eca46464ed5615cb36a3beb3f7a7b9a8ffbe7cf/internal/config/config.go#L208 nameLoader = map[string]api.Loader{ "none": api.LoaderNone, "base64": api.LoaderBase64, "binary": api.LoaderBinary, "copy": api.LoaderFile, "css": api.LoaderCSS, "dataurl": api.LoaderDataURL, "default": api.LoaderDefault, "empty": api.LoaderEmpty, "file": api.LoaderFile, "global-css": api.LoaderGlobalCSS, "js": api.LoaderJS, "json": api.LoaderJSON, "jsx": api.LoaderJSX, "local-css": api.LoaderLocalCSS, "text": api.LoaderText, "ts": api.LoaderTS, "tsx": api.LoaderTSX, } ) // DecodeExternalOptions decodes the given map into ExternalOptions. func DecodeExternalOptions(m map[string]any) (ExternalOptions, error) { opts := ExternalOptions{ SourcesContent: true, } if err := mapstructure.WeakDecode(m, &opts); err != nil { return opts, err } if opts.TargetPath != "" { opts.TargetPath = paths.ToSlashTrimLeading(opts.TargetPath) } opts.Target = strings.ToLower(opts.Target) opts.Format = strings.ToLower(opts.Format) return opts, nil } // ErrorMessageResolved holds a resolved error message. type ErrorMessageResolved struct { Path string Message string Content hugio.ReadSeekCloser } // ExternalOptions holds user facing options for the js.Build template function. type ExternalOptions struct { // If not set, the source path will be used as the base target path. // Note that the target path's extension may change if the target MIME type // is different, e.g. when the source is TypeScript. TargetPath string // Whether to minify to output. Minify bool // One of "inline", "external", "linked" or "none". SourceMap string SourcesContent bool // The language target. // One of: es2015, es2016, es2017, es2018, es2019, es2020 or esnext. // Default is esnext. Target string // The output format. // One of: iife, cjs, esm // Default is to esm. Format string // One of browser, node, neutral. // Default is browser. // See https://esbuild.github.io/api/#platform Platform string // External dependencies, e.g. "react". Externals []string // This option allows you to automatically replace a global variable with an import from another file. // The filenames must be relative to /assets. // See https://esbuild.github.io/api/#inject Inject []string // User defined symbols. Defines map[string]any // This tells esbuild to edit your source code before building to drop certain constructs. // See https://esbuild.github.io/api/#drop Drop string // Maps a component import to another. Shims map[string]string // Configuring a loader for a given file type lets you load that file type with an // import statement or a require call. For example, configuring the .png file extension // to use the data URL loader means importing a .png file gives you a data URL // containing the contents of that image // // See https://esbuild.github.io/api/#loader Loaders map[string]string // User defined params. Will be marshaled to JSON and available as "@params", e.g. // import * as params from '@params'; Params any // What to use instead of React.createElement. JSXFactory string // What to use instead of React.Fragment. JSXFragment string // What to do about JSX syntax. // See https://esbuild.github.io/api/#jsx JSX string // Which library to use to automatically import JSX helper functions from. Only works if JSX is set to automatic. // See https://esbuild.github.io/api/#jsx-import-source JSXImportSource string // There is/was a bug in WebKit with severe performance issue with the tracking // of TDZ checks in JavaScriptCore. // // Enabling this flag removes the TDZ and `const` assignment checks and // may improve performance of larger JS codebases until the WebKit fix // is in widespread use. // // See https://bugs.webkit.org/show_bug.cgi?id=199866 // Deprecated: This no longer have any effect and will be removed. // TODO(bep) remove. See https://github.com/evanw/esbuild/commit/869e8117b499ca1dbfc5b3021938a53ffe934dba AvoidTDZ bool } // InternalOptions holds internal options for the js.Build template function. type InternalOptions struct { MediaType media.Type OutDir string Contents string SourceDir string ResolveDir string AbsWorkingDir string Metafile bool StdinSourcePath string DependencyManager identity.Manager Stdin bool // Set to true to pass in the entry point as a byte slice. Splitting bool TsConfig string EntryPoints []string ImportOnResolveFunc func(string, api.OnResolveArgs) string ImportOnLoadFunc func(api.OnLoadArgs) string ImportParamsOnLoadFunc func(args api.OnLoadArgs) json.RawMessage ErrorMessageResolveFunc func(api.Message) *ErrorMessageResolved ResolveSourceMapSource func(string) string // Used to resolve paths in error source maps. } // Options holds the options passed to Build. type Options struct { ExternalOptions InternalOptions compiled api.BuildOptions } func (opts *Options) compile() (err error) { target, found := nameTarget[opts.Target] if !found { err = fmt.Errorf("invalid target: %q", opts.Target) return } var loaders map[string]api.Loader if opts.Loaders != nil { loaders = make(map[string]api.Loader) for k, v := range opts.Loaders { loader, found := nameLoader[v] if !found { err = fmt.Errorf("invalid loader: %q", v) return } loaders[k] = loader } } mediaType := opts.MediaType if mediaType.IsZero() { mediaType = media.Builtin.JavascriptType } var loader api.Loader switch mediaType.SubType { case media.Builtin.JavascriptType.SubType: loader = api.LoaderJS case media.Builtin.TypeScriptType.SubType: loader = api.LoaderTS case media.Builtin.TSXType.SubType: loader = api.LoaderTSX case media.Builtin.JSXType.SubType: loader = api.LoaderJSX default: err = fmt.Errorf("unsupported Media Type: %q", opts.MediaType) return } var format api.Format // One of: iife, cjs, esm switch opts.Format { case "", "iife": format = api.FormatIIFE case "esm": format = api.FormatESModule case "cjs": format = api.FormatCommonJS default: err = fmt.Errorf("unsupported script output format: %q", opts.Format) return } var jsx api.JSX switch opts.JSX { case "", "transform": jsx = api.JSXTransform case "preserve": jsx = api.JSXPreserve case "automatic": jsx = api.JSXAutomatic default: err = fmt.Errorf("unsupported jsx type: %q", opts.JSX) return } var platform api.Platform switch opts.Platform { case "", "browser": platform = api.PlatformBrowser case "node": platform = api.PlatformNode case "neutral": platform = api.PlatformNeutral default: err = fmt.Errorf("unsupported platform type: %q", opts.Platform) return } var defines map[string]string if opts.Defines != nil { defines = maps.ToStringMapString(opts.Defines) } var drop api.Drop switch opts.Drop { case "": case "console": drop = api.DropConsole case "debugger": drop = api.DropDebugger default: err = fmt.Errorf("unsupported drop type: %q", opts.Drop) } // By default we only need to specify outDir and no outFile outDir := opts.OutDir outFile := "" var sourceMap api.SourceMap switch opts.SourceMap { case "inline": sourceMap = api.SourceMapInline case "external": sourceMap = api.SourceMapExternal case "linked": sourceMap = api.SourceMapLinked case "", "none": sourceMap = api.SourceMapNone default: err = fmt.Errorf("unsupported sourcemap type: %q", opts.SourceMap) return } sourcesContent := api.SourcesContentInclude if !opts.SourcesContent { sourcesContent = api.SourcesContentExclude } opts.compiled = api.BuildOptions{ Outfile: outFile, Bundle: true, Metafile: opts.Metafile, AbsWorkingDir: opts.AbsWorkingDir, Target: target, Format: format, Platform: platform, Sourcemap: sourceMap, SourcesContent: sourcesContent, Loader: loaders, MinifyWhitespace: opts.Minify, MinifyIdentifiers: opts.Minify, MinifySyntax: opts.Minify, Outdir: outDir, Splitting: opts.Splitting, Define: defines, External: opts.Externals, Drop: drop, JSXFactory: opts.JSXFactory, JSXFragment: opts.JSXFragment, JSX: jsx, JSXImportSource: opts.JSXImportSource, Tsconfig: opts.TsConfig, EntryPoints: opts.EntryPoints, } if opts.Stdin { // This makes ESBuild pass `stdin` as the Importer to the import. opts.compiled.Stdin = &api.StdinOptions{ Contents: opts.Contents, ResolveDir: opts.ResolveDir, Loader: loader, } } return } func (o Options) loaderFromFilename(filename string) api.Loader { ext := filepath.Ext(filename) if optsLoaders := o.compiled.Loader; optsLoaders != nil { if l, found := optsLoaders[ext]; found { return l } } l, found := extensionToLoaderMap[ext] if found { return l } return api.LoaderJS } func (opts *Options) validate() error { if opts.ImportOnResolveFunc != nil && opts.ImportOnLoadFunc == nil { return fmt.Errorf("ImportOnLoadFunc must be set if ImportOnResolveFunc is set") } if opts.ImportOnResolveFunc == nil && opts.ImportOnLoadFunc != nil { return fmt.Errorf("ImportOnResolveFunc must be set if ImportOnLoadFunc is set") } if opts.AbsWorkingDir == "" { return fmt.Errorf("AbsWorkingDir must be set") } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/esbuild/sourcemap.go
internal/js/esbuild/sourcemap.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 esbuild import ( "encoding/json" "strings" "github.com/evanw/esbuild/pkg/api" "github.com/gohugoio/hugo/common/paths" ) type sourceMap struct { Version int `json:"version"` Sources []string `json:"sources"` SourcesContent []string `json:"sourcesContent"` Mappings string `json:"mappings"` Names []string `json:"names"` } func fixOutputFile(o *api.OutputFile, resolve func(string) string) error { if strings.HasSuffix(o.Path, ".map") { b, err := fixSourceMap(o.Contents, resolve) if err != nil { return err } o.Contents = b } return nil } func fixSourceMap(s []byte, resolve func(string) string) ([]byte, error) { var sm sourceMap if err := json.Unmarshal([]byte(s), &sm); err != nil { return nil, err } sm.Sources = fixSourceMapSources(sm.Sources, resolve) b, err := json.Marshal(sm) if err != nil { return nil, err } return b, nil } func fixSourceMapSources(s []string, resolve func(string) string) []string { var result []string for _, src := range s { if s := resolve(src); s != "" { // Absolute filenames works fine on U*ix (tested in Chrome on MacOs), but works very poorly on Windows (again Chrome). // So, convert it to a URL. if u, err := paths.UrlFromFilename(s); err == nil { result = append(result, u.String()) } } } return result } // Used in tests. func SourcesFromSourceMap(s string) []string { var sm sourceMap if err := json.Unmarshal([]byte(s), &sm); err != nil { return nil } return sm.Sources }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/esbuild/helpers.go
internal/js/esbuild/helpers.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 esbuild provides functions for building JavaScript resources. package esbuild
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/js/esbuild/batch.go
internal/js/esbuild/batch.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 esbuild provides functions for building JavaScript resources. package esbuild import ( "bytes" "context" _ "embed" "encoding/json" "fmt" "io" "path" "path/filepath" "reflect" "sort" "strings" "sync" "sync/atomic" "github.com/evanw/esbuild/pkg/api" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/common/hsync" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/internal/js" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/tpl/tplimpl" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" ) var _ js.Batcher = (*batcher)(nil) const ( NsBatch = "_hugo-js-batch" propsKeyImportContext = "importContext" propsResoure = "resource" ) //go:embed batch-esm-runner.gotmpl var runnerTemplateStr string var _ js.BatchPackage = (*Package)(nil) var _ buildToucher = (*optsHolder[scriptOptions])(nil) var ( _ buildToucher = (*scriptGroup)(nil) _ isBuiltOrTouchedProvider = (*scriptGroup)(nil) ) func NewBatcherClient(deps *deps.Deps) (js.BatcherClient, error) { c := &BatcherClient{ d: deps, buildClient: NewBuildClient(deps.BaseFs.Assets, deps.ResourceSpec), createClient: create.New(deps.ResourceSpec), batcherStore: maps.NewCache[string, js.Batcher](), bundlesStore: maps.NewCache[string, js.BatchPackage](), } deps.BuildEndListeners.Add(func(...any) bool { c.bundlesStore.Reset() return false }) return c, nil } func (o optionsMap[K, C]) ByKey() optionsGetSetters[K, C] { var values []optionsGetSetter[K, C] for _, v := range o { values = append(values, v) } sort.Slice(values, func(i, j int) bool { return values[i].Key().String() < values[j].Key().String() }) return values } func (o *opts[K, C]) Compiled() C { o.h.checkCompileErr() return o.h.compiled } func (os optionsGetSetters[K, C]) Filter(predicate func(K) bool) optionsGetSetters[K, C] { var a optionsGetSetters[K, C] for _, v := range os { if predicate(v.Key()) { a = append(a, v) } } return a } func (o *optsHolder[C]) IdentifierBase() string { return o.optionsID } func (o *opts[K, C]) Key() K { return o.key } func (o *opts[K, C]) Reset() { o.once.Reset() o.h.resetCounter++ } func (o *opts[K, C]) Get(id uint32) js.OptionsSetter { var b *optsHolder[C] o.once.Do(func() { b = o.h b.setBuilt(id) }) return b } func (o *opts[K, C]) GetIdentity() identity.Identity { return o.h } func (o *optsHolder[C]) SetOptions(m map[string]any) string { o.optsSetCounter++ o.optsPrev = o.optsCurr o.optsCurr = m o.compiledPrev = o.compiled o.compiled, o.compileErr = o.compiled.compileOptions(m, o.defaults) o.checkCompileErr() return "" } // ValidateBatchID validates the given ID according to some very func ValidateBatchID(id string, isTopLevel bool) error { if id == "" { return fmt.Errorf("id must be set") } // No Windows slashes. if strings.Contains(id, "\\") { return fmt.Errorf("id must not contain backslashes") } // Allow forward slashes in top level IDs only. if !isTopLevel && strings.Contains(id, "/") { return fmt.Errorf("id must not contain forward slashes") } return nil } func newIsBuiltOrTouched() isBuiltOrTouched { return isBuiltOrTouched{ built: make(buildIDs), touched: make(buildIDs), } } func newOpts[K any, C optionsCompiler[C]](key K, optionsID string, defaults defaultOptionValues) *opts[K, C] { return &opts[K, C]{ key: key, h: &optsHolder[C]{ optionsID: optionsID, defaults: defaults, isBuiltOrTouched: newIsBuiltOrTouched(), }, } } // BatcherClient is a client for building JavaScript packages. type BatcherClient struct { d *deps.Deps once sync.Once runnerTemplate *tplimpl.TemplInfo createClient *create.Client buildClient *BuildClient batcherStore *maps.Cache[string, js.Batcher] bundlesStore *maps.Cache[string, js.BatchPackage] } // New creates a new Batcher with the given ID. // This will be typically created once and reused across rebuilds. func (c *BatcherClient) New(id string) (js.Batcher, error) { var initErr error c.once.Do(func() { // We should fix the initialization order here (or use the Go template package directly), but we need to wait // for the Hugo templates to be ready. tmpl, err := c.d.TemplateStore.TextParse("batch-esm-runner", runnerTemplateStr) if err != nil { initErr = err return } c.runnerTemplate = tmpl }) if initErr != nil { return nil, initErr } dependencyManager := c.d.Conf.NewIdentityManager() configID := "config_" + id b := &batcher{ id: id, scriptGroups: make(map[string]*scriptGroup), dependencyManager: dependencyManager, client: c, configOptions: newOpts[scriptID, configOptions]( scriptID(configID), configID, defaultOptionValues{}, ), } c.d.BuildEndListeners.Add(func(...any) bool { b.reset() return false }) idFinder := identity.NewFinder(identity.FinderConfig{}) c.d.OnChangeListeners.Add(func(ids ...identity.Identity) bool { for _, id := range ids { if r := idFinder.Contains(id, b.dependencyManager, 50); r > 0 { b.staleVersion.Add(1) return false } sp, ok := id.(identity.DependencyManagerScopedProvider) if !ok { continue } idms := sp.GetDependencyManagerForScopesAll() for _, g := range b.scriptGroups { g.forEachIdentity(func(id2 identity.Identity) bool { bt, ok := id2.(buildToucher) if !ok { return false } for _, id3 := range idms { // This handles the removal of the only source for a script group (e.g. all shortcodes in a contnt page). // Note the very shallow search. if r := idFinder.Contains(id2, id3, 0); r > 0 { bt.setTouched(b.buildCount) return false } } return false }) } } return false }) return b, nil } func (c *BatcherClient) Store() *maps.Cache[string, js.Batcher] { return c.batcherStore } func (c *BatcherClient) buildBatchGroup(ctx context.Context, t *batchGroupTemplateContext) (resource.Resource, string, error) { var buf bytes.Buffer if err := c.d.GetTemplateStore().ExecuteWithContext(ctx, c.runnerTemplate, &buf, t); err != nil { return nil, "", err } s := paths.AddLeadingSlash(t.keyPath + ".js") r, err := c.createClient.FromString(s, buf.String()) if err != nil { return nil, "", err } return r, s, nil } // Package holds a group of JavaScript resources. type Package struct { id string b *batcher groups map[string]resource.Resources } func (p *Package) Groups() map[string]resource.Resources { return p.groups } type batchGroupTemplateContext struct { keyPath string ID string Runners []scriptRunnerTemplateContext Scripts []scriptBatchTemplateContext } type batcher struct { mu sync.Mutex id string buildCount uint32 staleVersion atomic.Uint32 scriptGroups scriptGroups client *BatcherClient dependencyManager identity.Manager configOptions optionsGetSetter[scriptID, configOptions] // The last successfully built package. // If this is non-nil and not stale, we can reuse it (e.g. on server rebuilds) prevBuild *Package } // Build builds the batch if not already built or if it's stale. func (b *batcher) Build(ctx context.Context) (js.BatchPackage, error) { key := dynacache.CleanKey(b.id + ".js") p, err := b.client.bundlesStore.GetOrCreate(key, func() (js.BatchPackage, error) { return b.build(ctx) }) if err != nil { return nil, fmt.Errorf("failed to build JS batch %q: %w", b.id, err) } return p, nil } func (b *batcher) Config(ctx context.Context) js.OptionsSetter { return b.configOptions.Get(b.buildCount) } func (b *batcher) Group(ctx context.Context, id string) js.BatcherGroup { if err := ValidateBatchID(id, false); err != nil { panic(err) } b.mu.Lock() defer b.mu.Unlock() group, found := b.scriptGroups[id] if !found { idm := b.client.d.Conf.NewIdentityManager() b.dependencyManager.AddIdentity(idm) group = &scriptGroup{ id: id, b: b, isBuiltOrTouched: newIsBuiltOrTouched(), dependencyManager: idm, scriptsOptions: make(optionsMap[scriptID, scriptOptions]), instancesOptions: make(optionsMap[instanceID, paramsOptions]), runnersOptions: make(optionsMap[scriptID, scriptOptions]), } b.scriptGroups[id] = group } group.setBuilt(b.buildCount) return group } func (b *batcher) isStale() bool { if b.staleVersion.Load() > 0 { return true } if b.removeNotSet() { return true } if b.configOptions.isStale() { return true } for _, v := range b.scriptGroups { if v.isStale() { return true } } return false } func (b *batcher) build(ctx context.Context) (js.BatchPackage, error) { b.mu.Lock() defer b.mu.Unlock() defer func() { b.staleVersion.Store(0) b.buildCount++ }() if b.prevBuild != nil { if !b.isStale() { return b.prevBuild, nil } } p, err := b.doBuild(ctx) if err != nil { return nil, err } b.prevBuild = p return p, nil } func (b *batcher) doBuild(ctx context.Context) (*Package, error) { type importContext struct { name string resourceGetter resource.ResourceGetter scriptOptions scriptOptions dm identity.Manager } state := struct { importResource *maps.Cache[string, resource.Resource] resultResource *maps.Cache[string, resource.Resource] importerImportContext *maps.Cache[string, importContext] pathGroup *maps.Cache[string, string] }{ importResource: maps.NewCache[string, resource.Resource](), resultResource: maps.NewCache[string, resource.Resource](), importerImportContext: maps.NewCache[string, importContext](), pathGroup: maps.NewCache[string, string](), } multihostBasePaths := b.client.d.ResourceSpec.MultihostTargetBasePaths // Entry points passed to ESBuid. var entryPoints []string addResource := func(group, pth string, r resource.Resource, isResult bool) { state.pathGroup.Set(paths.TrimExt(pth), group) state.importResource.Set(pth, r) if isResult { state.resultResource.Set(pth, r) } entryPoints = append(entryPoints, pth) } for _, g := range b.scriptGroups.Sorted() { keyPath := g.id t := &batchGroupTemplateContext{ keyPath: keyPath, ID: g.id, } instances := g.instancesOptions.ByKey() for _, vv := range g.scriptsOptions.ByKey() { keyPath := keyPath + "_" + vv.Key().String() opts := vv.Compiled() impPath := path.Join(PrefixHugoVirtual, opts.Dir(), keyPath+opts.Resource.MediaType().FirstSuffix.FullSuffix) impCtx := opts.ImportContext state.importerImportContext.Set(impPath, importContext{ name: keyPath, resourceGetter: impCtx, scriptOptions: opts, dm: g.dependencyManager, }) bt := scriptBatchTemplateContext{ opts: vv, Import: impPath, Instances: []scriptInstanceBatchTemplateContext{}, } state.importResource.Set(bt.Import, vv.Compiled().Resource) predicate := func(k instanceID) bool { return k.scriptID == vv.Key() } for _, vvv := range instances.Filter(predicate) { bt.Instances = append(bt.Instances, scriptInstanceBatchTemplateContext{opts: vvv}) } t.Scripts = append(t.Scripts, bt) } for _, vv := range g.runnersOptions.ByKey() { runnerKeyPath := keyPath + "_" + vv.Key().String() runnerImpPath := paths.AddLeadingSlash(runnerKeyPath + "_runner" + vv.Compiled().Resource.MediaType().FirstSuffix.FullSuffix) t.Runners = append(t.Runners, scriptRunnerTemplateContext{opts: vv, Import: runnerImpPath}) addResource(g.id, runnerImpPath, vv.Compiled().Resource, false) } r, s, err := b.client.buildBatchGroup(ctx, t) if err != nil { return nil, fmt.Errorf("failed to build JS batch: %w", err) } state.importerImportContext.Set(s, importContext{ name: s, resourceGetter: nil, dm: g.dependencyManager, }) addResource(g.id, s, r, true) } mediaTypes := b.client.d.ResourceSpec.MediaTypes() externalOptions := b.configOptions.Compiled().Options if externalOptions.Format == "" { externalOptions.Format = "esm" } if externalOptions.Format != "esm" { return nil, fmt.Errorf("only esm format is currently supported") } jsOpts := Options{ ExternalOptions: externalOptions, InternalOptions: InternalOptions{ DependencyManager: b.dependencyManager, Splitting: true, ImportOnResolveFunc: func(imp string, args api.OnResolveArgs) string { var importContextPath string if args.Kind == api.ResolveEntryPoint { importContextPath = args.Path } else { importContextPath = args.Importer } importContext, importContextFound := state.importerImportContext.Get(importContextPath) // We want to track the dependencies closest to where they're used. dm := b.dependencyManager if importContextFound { dm = importContext.dm } if r, found := state.importResource.Get(imp); found { dm.AddIdentity(identity.FirstIdentity(r)) return imp } if importContext.resourceGetter != nil { resolved := ResolveResource(imp, importContext.resourceGetter) if resolved != nil { resolvePath := resources.InternalResourceTargetPath(resolved) dm.AddIdentity(identity.FirstIdentity(resolved)) imp := PrefixHugoVirtual + resolvePath state.importResource.Set(imp, resolved) state.importerImportContext.Set(imp, importContext) return imp } } return "" }, ImportOnLoadFunc: func(args api.OnLoadArgs) string { imp := args.Path if r, found := state.importResource.Get(imp); found { content, err := r.(resource.ContentProvider).Content(ctx) if err != nil { panic(err) } return cast.ToString(content) } return "" }, ImportParamsOnLoadFunc: func(args api.OnLoadArgs) json.RawMessage { if importContext, found := state.importerImportContext.Get(args.Path); found { if !importContext.scriptOptions.IsZero() { return importContext.scriptOptions.Params } } return nil }, ErrorMessageResolveFunc: func(args api.Message) *ErrorMessageResolved { if loc := args.Location; loc != nil { path := strings.TrimPrefix(loc.File, NsHugoImportResolveFunc+":") if r, found := state.importResource.Get(path); found { sourcePath := resources.InternalResourceSourcePathBestEffort(r) var contentr hugio.ReadSeekCloser if cp, ok := r.(hugio.ReadSeekCloserProvider); ok { contentr, _ = cp.ReadSeekCloser() } return &ErrorMessageResolved{ Content: contentr, Path: sourcePath, Message: args.Text, } } } return nil }, ResolveSourceMapSource: func(s string) string { if r, found := state.importResource.Get(s); found { if ss := resources.InternalResourceSourcePath(r); ss != "" { return ss } return PrefixHugoMemory + s } return "" }, EntryPoints: entryPoints, }, } result, err := b.client.buildClient.Build(jsOpts) if err != nil { return nil, fmt.Errorf("failed to build JS bundle: %w", err) } groups := make(map[string]resource.Resources) createAndAddResource := func(targetPath, group string, o api.OutputFile, mt media.Type) error { var sourceFilename string if r, found := state.importResource.Get(targetPath); found { sourceFilename = resources.InternalResourceSourcePathBestEffort(r) } targetPath = path.Join(b.id, targetPath) rd := resources.ResourceSourceDescriptor{ LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromBytes(o.Contents), nil }, MediaType: mt, TargetPath: targetPath, SourceFilenameOrPath: sourceFilename, } r, err := b.client.d.ResourceSpec.NewResource(rd) if err != nil { return err } groups[group] = append(groups[group], r) return nil } outDir := b.client.d.AbsPublishDir createAndAddResources := func(o api.OutputFile) (bool, error) { p := paths.ToSlashPreserveLeading(strings.TrimPrefix(o.Path, outDir)) ext := path.Ext(p) mt, _, found := mediaTypes.GetBySuffix(ext) if !found { return false, nil } group, found := state.pathGroup.Get(paths.TrimExt(p)) if !found { return false, nil } if err := createAndAddResource(p, group, o, mt); err != nil { return false, err } return true, nil } for _, o := range result.OutputFiles { handled, err := createAndAddResources(o) if err != nil { return nil, err } if !handled { // Copy to destination. // In a multihost setup, we will have multiple targets. var targetFilenames []string if len(multihostBasePaths) > 0 { for _, base := range multihostBasePaths { p := strings.TrimPrefix(o.Path, outDir) targetFilename := filepath.Join(base, b.id, p) targetFilenames = append(targetFilenames, targetFilename) } } else { p := strings.TrimPrefix(o.Path, outDir) targetFilename := filepath.Join(b.id, p) targetFilenames = append(targetFilenames, targetFilename) } fs := b.client.d.BaseFs.PublishFs if err := func() error { fw, err := helpers.OpenFilesForWriting(fs, targetFilenames...) if err != nil { return err } defer fw.Close() fr := bytes.NewReader(o.Contents) _, err = io.Copy(fw, fr) return err }(); err != nil { return nil, fmt.Errorf("failed to copy to %q: %w", targetFilenames, err) } } } p := &Package{ id: path.Join(NsBatch, b.id), b: b, groups: groups, } return p, nil } func (b *batcher) removeNotSet() bool { // We already have the lock. var removed bool currentBuildID := b.buildCount for k, v := range b.scriptGroups { if !v.isBuilt(currentBuildID) && v.isTouched(currentBuildID) { // Remove entire group. removed = true delete(b.scriptGroups, k) continue } if v.removeTouchedButNotSet() { removed = true } if v.removeNotSet() { removed = true } } return removed } func (b *batcher) reset() { b.mu.Lock() defer b.mu.Unlock() b.configOptions.Reset() for _, v := range b.scriptGroups { v.Reset() } } type buildIDs map[uint32]bool func (b buildIDs) Has(buildID uint32) bool { return b[buildID] } func (b buildIDs) Set(buildID uint32) { b[buildID] = true } type buildToucher interface { setTouched(buildID uint32) } type configOptions struct { Options ExternalOptions } func (s configOptions) isStaleCompiled(prev configOptions) bool { return false } func (s configOptions) compileOptions(m map[string]any, defaults defaultOptionValues) (configOptions, error) { config, err := DecodeExternalOptions(m) if err != nil { return configOptions{}, err } return configOptions{ Options: config, }, nil } type defaultOptionValues struct { defaultExport string } type instanceID struct { scriptID scriptID instanceID string } func (i instanceID) String() string { return i.scriptID.String() + "_" + i.instanceID } type isBuiltOrTouched struct { built buildIDs touched buildIDs } func (i isBuiltOrTouched) setBuilt(id uint32) { i.built.Set(id) } func (i isBuiltOrTouched) isBuilt(id uint32) bool { return i.built.Has(id) } func (i isBuiltOrTouched) setTouched(id uint32) { i.touched.Set(id) } func (i isBuiltOrTouched) isTouched(id uint32) bool { return i.touched.Has(id) } type isBuiltOrTouchedProvider interface { isBuilt(uint32) bool isTouched(uint32) bool } type key interface { comparable fmt.Stringer } type optionsCompiler[C any] interface { isStaleCompiled(C) bool compileOptions(map[string]any, defaultOptionValues) (C, error) } type optionsGetSetter[K, C any] interface { isBuiltOrTouchedProvider identity.IdentityProvider // resource.StaleInfo Compiled() C Key() K Reset() Get(uint32) js.OptionsSetter isStale() bool currPrev() (map[string]any, map[string]any) } type optionsGetSetters[K key, C any] []optionsGetSetter[K, C] type optionsMap[K key, C any] map[K]optionsGetSetter[K, C] type opts[K any, C optionsCompiler[C]] struct { key K h *optsHolder[C] once hsync.OnceMore } type optsHolder[C optionsCompiler[C]] struct { optionsID string defaults defaultOptionValues // Keep track of one generation so we can detect changes. // Note that most of this tracking is performed on the options/map level. compiled C compiledPrev C compileErr error resetCounter uint32 optsSetCounter uint32 optsCurr map[string]any optsPrev map[string]any isBuiltOrTouched } type paramsOptions struct { Params json.RawMessage } func (s paramsOptions) isStaleCompiled(prev paramsOptions) bool { return false } func (s paramsOptions) compileOptions(m map[string]any, defaults defaultOptionValues) (paramsOptions, error) { v := struct { Params map[string]any }{} if err := mapstructure.WeakDecode(m, &v); err != nil { return paramsOptions{}, err } paramsJSON, err := json.Marshal(v.Params) if err != nil { return paramsOptions{}, err } return paramsOptions{ Params: paramsJSON, }, nil } type scriptBatchTemplateContext struct { opts optionsGetSetter[scriptID, scriptOptions] Import string Instances []scriptInstanceBatchTemplateContext } func (s *scriptBatchTemplateContext) Export() string { return s.opts.Compiled().Export } func (c scriptBatchTemplateContext) MarshalJSON() (b []byte, err error) { return json.Marshal(&struct { ID string `json:"id"` Instances []scriptInstanceBatchTemplateContext `json:"instances"` }{ ID: c.opts.Key().String(), Instances: c.Instances, }) } func (b scriptBatchTemplateContext) RunnerJSON(i int) string { script := fmt.Sprintf("Script%d", i) v := struct { ID string `json:"id"` // Read-only live JavaScript binding. Binding string `json:"binding"` Instances []scriptInstanceBatchTemplateContext `json:"instances"` }{ b.opts.Key().String(), script, b.Instances, } bb, err := json.Marshal(v) if err != nil { panic(err) } s := string(bb) // Remove the quotes to make it a valid JS object. s = strings.ReplaceAll(s, fmt.Sprintf("%q", script), script) return s } type scriptGroup struct { mu sync.Mutex id string b *batcher isBuiltOrTouched dependencyManager identity.Manager scriptsOptions optionsMap[scriptID, scriptOptions] instancesOptions optionsMap[instanceID, paramsOptions] runnersOptions optionsMap[scriptID, scriptOptions] } // For internal use only. func (b *scriptGroup) GetDependencyManager() identity.Manager { return b.dependencyManager } // For internal use only. func (b *scriptGroup) IdentifierBase() string { return b.id } func (s *scriptGroup) Instance(sid, id string) js.OptionsSetter { if err := ValidateBatchID(sid, false); err != nil { panic(err) } if err := ValidateBatchID(id, false); err != nil { panic(err) } s.mu.Lock() defer s.mu.Unlock() iid := instanceID{scriptID: scriptID(sid), instanceID: id} if v, found := s.instancesOptions[iid]; found { return v.Get(s.b.buildCount) } fullID := "instance_" + s.key() + "_" + iid.String() s.instancesOptions[iid] = newOpts[instanceID, paramsOptions]( iid, fullID, defaultOptionValues{}, ) return s.instancesOptions[iid].Get(s.b.buildCount) } func (g *scriptGroup) Reset() { for _, v := range g.scriptsOptions { v.Reset() } for _, v := range g.instancesOptions { v.Reset() } for _, v := range g.runnersOptions { v.Reset() } } func (s *scriptGroup) Runner(id string) js.OptionsSetter { if err := ValidateBatchID(id, false); err != nil { panic(err) } s.mu.Lock() defer s.mu.Unlock() sid := scriptID(id) if v, found := s.runnersOptions[sid]; found { return v.Get(s.b.buildCount) } runnerIdentity := "runner_" + s.key() + "_" + id // A typical signature for a runner would be: // export default function Run(scripts) {} // The user can override the default export in the templates. s.runnersOptions[sid] = newOpts[scriptID, scriptOptions]( sid, runnerIdentity, defaultOptionValues{ defaultExport: "default", }, ) return s.runnersOptions[sid].Get(s.b.buildCount) } func (s *scriptGroup) Script(id string) js.OptionsSetter { if err := ValidateBatchID(id, false); err != nil { panic(err) } s.mu.Lock() defer s.mu.Unlock() sid := scriptID(id) if v, found := s.scriptsOptions[sid]; found { return v.Get(s.b.buildCount) } scriptIdentity := "script_" + s.key() + "_" + id s.scriptsOptions[sid] = newOpts[scriptID, scriptOptions]( sid, scriptIdentity, defaultOptionValues{ defaultExport: "*", }, ) return s.scriptsOptions[sid].Get(s.b.buildCount) } func (s *scriptGroup) isStale() bool { for _, v := range s.scriptsOptions { if v.isStale() { return true } } for _, v := range s.instancesOptions { if v.isStale() { return true } } for _, v := range s.runnersOptions { if v.isStale() { return true } } return false } func (v *scriptGroup) forEachIdentity( f func(id identity.Identity) bool, ) bool { if f(v) { return true } for _, vv := range v.instancesOptions { if f(vv.GetIdentity()) { return true } } for _, vv := range v.scriptsOptions { if f(vv.GetIdentity()) { return true } } for _, vv := range v.runnersOptions { if f(vv.GetIdentity()) { return true } } return false } func (s *scriptGroup) key() string { return s.b.id + "_" + s.id } func (g *scriptGroup) removeNotSet() bool { currentBuildID := g.b.buildCount if !g.isBuilt(currentBuildID) { // This group was never accessed in this build. return false } var removed bool if g.instancesOptions.isBuilt(currentBuildID) { // A new instance has been set in this group for this build. // Remove any instance that has not been set in this build. for k, v := range g.instancesOptions { if v.isBuilt(currentBuildID) { continue } delete(g.instancesOptions, k) removed = true } } if g.runnersOptions.isBuilt(currentBuildID) { // A new runner has been set in this group for this build. // Remove any runner that has not been set in this build. for k, v := range g.runnersOptions { if v.isBuilt(currentBuildID) { continue } delete(g.runnersOptions, k) removed = true } } if g.scriptsOptions.isBuilt(currentBuildID) { // A new script has been set in this group for this build. // Remove any script that has not been set in this build. for k, v := range g.scriptsOptions { if v.isBuilt(currentBuildID) { continue } delete(g.scriptsOptions, k) // Also remove any instance with this ID. for kk := range g.instancesOptions { if kk.scriptID == k { delete(g.instancesOptions, kk) } } removed = true } } return removed } func (g *scriptGroup) removeTouchedButNotSet() bool { currentBuildID := g.b.buildCount var removed bool for k, v := range g.instancesOptions { if v.isBuilt(currentBuildID) { continue } if v.isTouched(currentBuildID) { delete(g.instancesOptions, k) removed = true } } for k, v := range g.runnersOptions { if v.isBuilt(currentBuildID) { continue } if v.isTouched(currentBuildID) { delete(g.runnersOptions, k) removed = true } } for k, v := range g.scriptsOptions { if v.isBuilt(currentBuildID) { continue } if v.isTouched(currentBuildID) { delete(g.scriptsOptions, k) removed = true // Also remove any instance with this ID. for kk := range g.instancesOptions { if kk.scriptID == k { delete(g.instancesOptions, kk) } } } } return removed } type scriptGroups map[string]*scriptGroup func (s scriptGroups) Sorted() []*scriptGroup { var a []*scriptGroup for _, v := range s { a = append(a, v) } sort.Slice(a, func(i, j int) bool { return a[i].id < a[j].id }) return a } type scriptID string func (s scriptID) String() string { return string(s) } type scriptInstanceBatchTemplateContext struct { opts optionsGetSetter[instanceID, paramsOptions] } func (c scriptInstanceBatchTemplateContext) ID() string { return c.opts.Key().instanceID } func (c scriptInstanceBatchTemplateContext) MarshalJSON() (b []byte, err error) { return json.Marshal(&struct { ID string `json:"id"` Params json.RawMessage `json:"params"` }{ ID: c.opts.Key().instanceID, Params: c.opts.Compiled().Params, }) } type scriptOptions struct { // The script to build. Resource resource.Resource // The import context to use. // Note that we will always fall back to the resource's own import context. ImportContext resource.ResourceGetter // The export name to use for this script's group's runners (if any). // If not set, the default export will be used. Export string // Params marshaled to JSON. Params json.RawMessage } func (o *scriptOptions) Dir() string { return path.Dir(resources.InternalResourceTargetPath(o.Resource)) } func (s scriptOptions) IsZero() bool { return s.Resource == nil } func (s scriptOptions) isStaleCompiled(prev scriptOptions) bool { if prev.IsZero() { return false } // All but the ImportContext are checked at the options/map level. i1nil, i2nil := prev.ImportContext == nil, s.ImportContext == nil if i1nil && i2nil { return false } if i1nil || i2nil { return true } // On its own this check would have too many false positives, but combined with the other checks it should be fine. // We cannot do equality checking here. if !prev.ImportContext.(resource.IsProbablySameResourceGetter).IsProbablySameResourceGetter(s.ImportContext) { return true } return false } func (s scriptOptions) compileOptions(m map[string]any, defaults defaultOptionValues) (scriptOptions, error) { v := struct { Resource resource.Resource ImportContext any Export string Params map[string]any }{} if err := mapstructure.WeakDecode(m, &v); err != nil { panic(err) } var paramsJSON []byte if v.Params != nil { var err error paramsJSON, err = json.Marshal(v.Params) if err != nil { panic(err) } } if v.Export == "" { v.Export = defaults.defaultExport } compiled := scriptOptions{ Resource: v.Resource, Export: v.Export, ImportContext: resource.NewCachedResourceGetter(v.ImportContext), Params: paramsJSON, } if compiled.Resource == nil { return scriptOptions{}, fmt.Errorf("resource not set") } return compiled, nil } type scriptRunnerTemplateContext struct { opts optionsGetSetter[scriptID, scriptOptions] Import string } func (s *scriptRunnerTemplateContext) Export() string { return s.opts.Compiled().Export } func (c scriptRunnerTemplateContext) MarshalJSON() (b []byte, err error) { return json.Marshal(&struct { ID string `json:"id"` }{ ID: c.opts.Key().String(), }) } func (o optionsMap[K, C]) isBuilt(id uint32) bool { for _, v := range o { if v.isBuilt(id) { return true } } return false } func (o *opts[K, C]) isBuilt(id uint32) bool { return o.h.isBuilt(id) } func (o *opts[K, C]) isStale() bool { if o.h.isStaleOpts() { return true } if o.h.compiled.isStaleCompiled(o.h.compiledPrev) { return true } return false } func (o *optsHolder[C]) isStaleOpts() bool { if o.optsSetCounter == 1 && o.resetCounter > 0 { return false } isStale := func() bool { if len(o.optsCurr) != len(o.optsPrev) { return true } for k, v := range o.optsPrev { vv, found := o.optsCurr[k] if !found { return true } if strings.EqualFold(k, propsKeyImportContext) { // This is checked later. } else if si, ok := vv.(resource.StaleInfo); ok { if si.StaleVersion() > 0 { return true } } else { if !reflect.DeepEqual(v, vv) { return true }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/warpc/katex.go
internal/warpc/katex.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 warpc import ( _ "embed" ) //go:embed wasm/renderkatex.wasm var katexWasm []byte // See https://katex.org/docs/options.html type KatexInput struct { Expression string `json:"expression"` Options KatexOptions `json:"options"` } // KatexOptions defines the options for the KaTeX rendering. // See https://katex.org/docs/options.html type KatexOptions struct { // html, mathml (default), htmlAndMathml Output string `json:"output"` // If true, display math in display mode, false in inline mode. DisplayMode bool `json:"displayMode"` // Render \tags on the left side instead of the right. Leqno bool `json:"leqno"` // If true, render flush left with a 2em left margin. Fleqn bool `json:"fleqn"` // The color used for typesetting errors. // A color string given in the format "#XXX" or "#XXXXXX" ErrorColor string `json:"errorColor"` // A collection of custom macros. Macros map[string]string `json:"macros,omitempty"` // Specifies a minimum thickness, in ems, for fraction lines. MinRuleThickness float64 `json:"minRuleThickness"` // If true, KaTeX will throw a ParseError when it encounters an unsupported command. ThrowOnError bool `json:"throwOnError"` // Controls how KaTeX handles LaTeX features that offer convenience but // aren't officially supported, one of error (default), ignore, or warn. // // - error: Throws an error when convenient, unsupported LaTeX features // are encountered. // - ignore: Allows convenient, unsupported LaTeX features without any // feedback. // - warn: Emits a warning when convenient, unsupported LaTeX features are // encountered. // // The "newLineInDisplayMode" error code, which flags the use of \\ // or \newline in display mode outside an array or tabular environment, is // intentionally designed not to throw an error, despite this behavior // being questionable. Strict string `json:"strict"` } type KatexOutput struct { Output string `json:"output"` }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/warpc/webp.go
internal/warpc/webp.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 warpc import ( "bytes" "context" "errors" "fmt" "image" "image/color" "image/draw" "io" "maps" "github.com/gohugoio/hugo/common/himage" "github.com/gohugoio/hugo/common/hugio" ) var ( _ SourceProvider = WebpInput{} _ DestinationProvider = WebpInput{} ) type CommonImageProcessingParams struct { Width int `json:"width,omitempty"` Height int `json:"height,omitempty"` Stride int `json:"stride,omitempty"` // For animated images. FrameDurations []int `json:"frameDurations,omitempty"` LoopCount int `json:"loopCount,omitempty"` } /* If you're reading this and questioning the protocol on top of WASM using JSON and streams instead of WAS Call's with pointers written to linear memory: - The goal of this is to eventually make it into one or more RPC plugin APIs. - Passing pointers around has a number of challenges in that context. - One would be that it's not possible to pass pointers to child processes (e.g. non-WASM plugins). Also, you would think that this JSON/streams approach would be significantly slower than using pointers directly, but in practice, at least for WebP, the difference is negligible, see below output from a test run: [pointers] DecodeWebp took 18.168375ms [pointers] EncodeWebp took 13.959458ms [pointers] DecodeWebpConfig took 93.083µs [streams] DecodeWebp took 17.192917ms [streams] EncodeWebp took 14.084792ms [streams] DecodeWebpConfig took 54.334µs Also note that the placement of this code in this internal package is also temporary. We 1. Need to get the WASM RPC plugin infrastructure in place, and 2. Need to decide on the final API shape for image processing plugins. */ type WebpInput struct { Source hugio.SizeReader `json:"-"` // Will be sent in a separate stream. Destination io.Writer `json:"-"` // Will be used to write the result to. Options map[string]any `json:"options"` // Config options. Params map[string]any `json:"params"` // Command params (width, height, etc.). } func (w WebpInput) GetSource() hugio.SizeReader { return w.Source } func (w WebpInput) GetDestination() io.Writer { return w.Destination } type WebpOutput struct { Params CommonImageProcessingParams `json:"params"` } type WebpCodec struct { d func() (Dispatcher[WebpInput, WebpOutput], error) } // Decode reads a WEBP image from r and returns it as an image.Image. // Note that animated WebP images are returnes as an himage.AnimatedImage. func (d *WebpCodec) Decode(r io.Reader) (image.Image, error) { dd, err := d.d() if err != nil { return nil, err } source, err := hugio.ToSizeReader(r) if err != nil { return nil, err } var destination bytes.Buffer // Commands: // encodeNRGBA // encodeGray // decode // config message := Message[WebpInput]{ Header: Header{ Version: 1, Command: "decode", RequestKinds: []string{MessageKindJSON, MessageKindBlob}, ResponseKinds: []string{MessageKindJSON, MessageKindBlob}, }, Data: WebpInput{ Source: source, Destination: &destination, Options: map[string]any{}, }, } out, err := dd.Execute(context.Background(), message) if err != nil { return nil, err } w, h, stride := out.Data.Params.Width, out.Data.Params.Height, out.Data.Params.Stride if w == 0 || h == 0 || stride == 0 { return nil, fmt.Errorf("received invalid image dimensions: %dx%d stride %d", w, h, stride) } if len(out.Data.Params.FrameDurations) > 0 { // Animated WebP. img := &WEBP{ frameDurations: out.Data.Params.FrameDurations, loopCount: out.Data.Params.LoopCount, } frameSize := stride * h frames := make([]image.Image, len(destination.Bytes())/frameSize) for i := 0; i < len(frames); i++ { frameBytes := destination.Bytes()[i*frameSize : (i+1)*frameSize] frameImg := &image.NRGBA{ Pix: frameBytes, Stride: stride, Rect: image.Rect(0, 0, w, h), } frames[i] = frameImg } img.SetFrames(frames) return img, nil } img := &image.NRGBA{ Pix: destination.Bytes(), Stride: stride, Rect: image.Rect(0, 0, w, h), } return img, nil } func (d *WebpCodec) DecodeConfig(r io.Reader) (image.Config, error) { dd, err := d.d() if err != nil { return image.Config{}, err } // Avoid reading the entire image for config only. const webpMaxHeaderSize = 32 b := make([]byte, webpMaxHeaderSize) _, err = r.Read(b) if err != nil { return image.Config{}, err } message := Message[WebpInput]{ Header: Header{ Version: 1, Command: "config", RequestKinds: []string{MessageKindJSON, MessageKindBlob}, ResponseKinds: []string{MessageKindJSON}, }, Data: WebpInput{ Source: bytes.NewReader(b), }, } out, err := dd.Execute(context.Background(), message) if err != nil { return image.Config{}, err } return image.Config{ Width: out.Data.Params.Width, Height: out.Data.Params.Height, ColorModel: color.RGBAModel, }, nil } func (d *WebpCodec) Encode(w io.Writer, img image.Image, opts map[string]any) error { b := img.Bounds() if b.Dx() >= 1<<16 || b.Dy() >= 1<<16 { return errors.New("webp: image is too large to encode") } dd, err := d.d() if err != nil { return err } const ( commandEncodeNRGBA = "encodeNRGBA" commandEncodeGray = "encodeGray" ) var ( bounds = img.Bounds() imageBytes []byte stride int frameDurations []int loopCount int command string ) switch v := img.(type) { case *image.RGBA: imageBytes = v.Pix stride = v.Stride command = commandEncodeNRGBA case *WEBP: // Animated WebP. frames := v.GetFrames() if len(frames) == 0 { return errors.New("webp: animated image has no frames") } firstFrame := frames[0] bounds = firstFrame.Bounds() nrgba := convertToNRGBA(firstFrame) frameSize := nrgba.Stride * bounds.Dy() imageBytes = make([]byte, frameSize*len(frames)) stride = nrgba.Stride for i, frame := range frames { var nrgbaFrame *image.NRGBA if i == 0 { nrgbaFrame = nrgba } else { nrgbaFrame = convertToNRGBA(frame) } copy(imageBytes[i*frameSize:(i+1)*frameSize], nrgbaFrame.Pix) } frameDurations = v.GetFrameDurations() loopCount = v.loopCount command = commandEncodeNRGBA case *image.Gray: imageBytes = v.Pix stride = v.Stride command = commandEncodeGray case himage.AnimatedImage: frames := v.GetFrames() if len(frames) == 0 { return errors.New("webp: animated image has no frames") } firstFrame := frames[0] bounds = firstFrame.Bounds() nrgba := convertToNRGBA(firstFrame) frameSize := nrgba.Stride * bounds.Dy() imageBytes = make([]byte, frameSize*len(frames)) stride = nrgba.Stride for i, frame := range frames { var nrgbaFrame *image.NRGBA if i == 0 { nrgbaFrame = nrgba } else { nrgbaFrame = convertToNRGBA(frame) } copy(imageBytes[i*frameSize:(i+1)*frameSize], nrgbaFrame.Pix) } frameDurations = v.GetFrameDurations() loopCount = v.GetLoopCount() command = commandEncodeNRGBA default: nrgba := convertToNRGBA(img) imageBytes = nrgba.Pix stride = nrgba.Stride command = commandEncodeNRGBA } if len(imageBytes) == 0 { return fmt.Errorf("no image bytes extracted from %T", img) } opts = maps.Clone(opts) opts["useSharpYuv"] = true // Use sharp (and slow) RGB->YUV conversion. message := Message[WebpInput]{ Header: Header{ Version: 1, Command: command, RequestKinds: []string{MessageKindJSON, MessageKindBlob}, ResponseKinds: []string{MessageKindJSON, MessageKindBlob}, }, Data: WebpInput{ Source: bytes.NewReader(imageBytes), Destination: w, Options: opts, Params: map[string]any{ "width": bounds.Max.X, "height": bounds.Max.Y, "stride": stride, "frameDurations": frameDurations, "loopCount": loopCount, }, }, } _, err = dd.Execute(context.Background(), message) if err != nil { return err } return nil } func convertToNRGBA(src image.Image) *image.NRGBA { dst := image.NewNRGBA(src.Bounds()) draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Src) return dst } var _ himage.AnimatedImage = (*WEBP)(nil) // WEBP represents an animated WebP image. // The naming deliberately matches the fields in the standard library image/gif package. type WEBP struct { image.Image // The first frame. frames []image.Image frameDurations []int loopCount int } func (w *WEBP) GetLoopCount() int { return w.loopCount } func (w *WEBP) GetFrames() []image.Image { return w.frames } func (w *WEBP) GetFrameDurations() []int { return w.frameDurations } func (w *WEBP) GetRaw() any { return w } func (w *WEBP) SetFrames(frames []image.Image) { if len(frames) == 0 { panic("frames cannot be empty") } w.frames = frames w.Image = frames[0] } func (w *WEBP) SetWidthHeight(width, height int) { // No-op for WEBP. }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/warpc/webp_integration_test.go
internal/warpc/webp_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 warpc_test import ( "path/filepath" "runtime" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestWebPMisc(t *testing.T) { files := ` -- assets/sunrise.webp -- sourcefilename: ../../resources/testdata/sunrise.webp -- layouts/home.html -- {{ $image := resources.Get "sunrise.webp" }} {{ $resized := $image.Resize "123x456" }} Original Width/Height: {{ $image.Width }}/{{ $image.Height }}| Resized Width:/Height {{ $resized.Width }}/{{ $resized.Height }}| Resized RelPermalink: {{ $resized.RelPermalink }}| {{ $ic := images.Config "/assets/sunrise.webp" }} ImageConfig: {{ printf "%d/%d" $ic.Width $ic.Height }}| ` b := hugolib.Test(t, files) b.ImageHelper("public/sunrise_hu_8dd1706a77fb35ce.webp").AssertFormat("webp").AssertIsAnimated(false) b.AssertFileContent("public/index.html", "Original Width/Height: 1024/640|", "Resized Width:/Height 123/456|", "Resized RelPermalink: /sunrise_hu_8dd1706a77fb35ce.webp|", "ImageConfig: 1024/640|", ) } func TestWebPEncodeGrayscale(t *testing.T) { files := ` -- assets/gopher.png -- sourcefilename: ../../resources/testdata/bw-gopher.png -- layouts/home.html -- {{ $image := resources.Get "gopher.png" }} {{ $resized := $image.Resize "123x456 webp" }} Resized RelPermalink: {{ $resized.RelPermalink }}| ` b := hugolib.Test(t, files) b.ImageHelper("public/gopher_hu_cc98ebaf742cba8e.webp").AssertFormat("webp") } func TestWebPInvalid(t *testing.T) { files := ` -- assets/invalid.webp -- sourcefilename: ../../resources/testdata/webp/invalid.webp -- layouts/home.html -- {{ $image := resources.Get "invalid.webp" }} {{ $resized := $image.Resize "123x456 webp" }} Resized RelPermalink: {{ $resized.RelPermalink }}| ` tempDir := t.TempDir() b, err := hugolib.TestE(t, files, hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) { cfg.NeedsOsFS = true cfg.WorkingDir = tempDir })) b.Assert(err, qt.IsNotNil) if runtime.GOOS != "windows" { // Make sure the full image filename is in the error message. filename := filepath.Join(tempDir, "assets/invalid.webp") b.Assert(err.Error(), qt.Contains, filename) } } // This test isn't great, but we have golden tests to verify the output itself. func TestWebPAnimation(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["page", "section", "taxonomy", "term", "sitemap", "robotsTXT", "404"] -- assets/anim.webp -- sourcefilename: ../../resources/testdata/webp/anim.webp -- assets/giphy.gif -- sourcefilename: ../../resources/testdata/giphy.gif -- layouts/home.html -- {{ $webpAnim := resources.Get "anim.webp" }} {{ $gifAnim := resources.Get "giphy.gif" }} {{ ($webpAnim.Resize "100x100 webp").Publish }} {{ ($webpAnim.Resize "100x100 gif").Publish }} {{ ($gifAnim.Resize "100x100 gif").Publish }} {{ ($gifAnim.Resize "100x100 webp").Publish }} ` b := hugolib.Test(t, files) // Source animated gif: // Frame durations in ms. giphyFrameDurations := []int{200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200} b.ImageHelper("public/giphy_hu_bb052284cc220165.webp").AssertFormat("webp").AssertIsAnimated(true).AssertLoopCount(0).AssertFrameDurations(giphyFrameDurations) b.ImageHelper("public/giphy_hu_c6b8060edf0363b1.gif").AssertFormat("gif").AssertIsAnimated(true).AssertLoopCount(0).AssertFrameDurations(giphyFrameDurations) // Source animated webp: animFrameDurations := []int{80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80} b.ImageHelper("public/anim_hu_edc2f24aaad2cee6.webp").AssertFormat("webp").AssertIsAnimated(true).AssertLoopCount(0).AssertFrameDurations(animFrameDurations) b.ImageHelper("public/anim_hu_58eb49733894e7ce.gif").AssertFormat("gif").AssertIsAnimated(true).AssertLoopCount(0).AssertFrameDurations(animFrameDurations) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/warpc/warpc.go
internal/warpc/warpc.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 warpc import ( "bytes" "context" _ "embed" "encoding/json" "errors" "fmt" "io" "os" "runtime" "strings" "sync" "sync/atomic" "time" "github.com/bep/textandbinarywriter" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "golang.org/x/sync/errgroup" "github.com/tetratelabs/wazero" "github.com/tetratelabs/wazero/api" "github.com/tetratelabs/wazero/experimental" "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1" ) const ( MessageKindJSON string = "json" MessageKindBlob string = "blob" ) const currentVersion = 1 //go:embed wasm/quickjs.wasm var quickjsWasm []byte //go:embed wasm/webp.wasm var webpWasm []byte // Header is in both the request and response. type Header struct { // Major version of the protocol. Version uint16 `json:"version"` // Unique ID for the request. // Note that this only needs to be unique within the current request set time window. ID uint32 `json:"id"` // Command is the command to execute. Command string `json:"command"` // RequestKinds is a list of kinds in this RPC request, // e.g. {"json", "blob"}, or {"json"}. RequestKinds []string `json:"requestKinds"` // ResponseKinds is a list of kinds expected in the response, // e.g. {"json", "blob"}, or {"json"}. ResponseKinds []string `json:"responseKinds"` // Set in the response if there was an error. Err string `json:"err"` // Warnings is a list of warnings that may be returned in the response. Warnings []string `json:"warnings,omitempty"` } func (m *Header) init() error { if m.ID == 0 { return errors.New("ID must not be 0 (note that this must be unique within the current request set time window)") } if m.Version == 0 { m.Version = currentVersion } if len(m.RequestKinds) == 0 { m.RequestKinds = []string{string(MessageKindJSON)} } if len(m.ResponseKinds) == 0 { m.ResponseKinds = []string{string(MessageKindJSON)} } if m.Version != currentVersion { return fmt.Errorf("unsupported version: %d", m.Version) } for range 2 { if len(m.RequestKinds) > 2 { return fmt.Errorf("invalid number of request kinds: %d", len(m.RequestKinds)) } if len(m.ResponseKinds) > 2 { return fmt.Errorf("invalid number of response kinds: %d", len(m.ResponseKinds)) } m.RequestKinds = hstrings.UniqueStringsReuse(m.RequestKinds) m.ResponseKinds = hstrings.UniqueStringsReuse(m.ResponseKinds) } return nil } type Message[T any] struct { Header Header `json:"header"` Data T `json:"data"` } func (m Message[T]) GetID() uint32 { return m.Header.ID } func (m *Message[T]) init() error { return m.Header.init() } type SourceProvider interface { GetSource() hugio.SizeReader } type DestinationProvider interface { GetDestination() io.Writer } type Dispatcher[Q, R any] interface { Execute(ctx context.Context, q Message[Q]) (Message[R], error) Close() error } func (p *dispatcherPool[Q, R]) getDispatcher() *dispatcher[Q, R] { i := int(p.counter.Add(1)) % len(p.dispatchers) return p.dispatchers[i] } func (p *dispatcherPool[Q, R]) Close() error { return p.close() } type dispatcher[Q, R any] struct { zeroR Message[R] id atomic.Uint32 mu sync.Mutex encodeMu sync.Mutex pending map[uint32]*call[Q, R] inOut *inOut inGroup *errgroup.Group shutdown bool closing bool } type inOut struct { sync.Mutex stdin hugio.ReadWriteCloser stdout io.WriteCloser stdoutBinary hugio.ReadWriteCloser dec *json.Decoder enc *json.Encoder } func (p *inOut) Close() error { if err := p.stdin.Close(); err != nil { return err } // This will also close the underlying writers. if err := p.stdout.Close(); err != nil { return err } return nil } var ErrShutdown = fmt.Errorf("dispatcher is shutting down") var timerPool = sync.Pool{} func getTimer(d time.Duration) *time.Timer { if v := timerPool.Get(); v != nil { timer := v.(*time.Timer) timer.Reset(d) return timer } return time.NewTimer(d) } func putTimer(t *time.Timer) { if !t.Stop() { select { case <-t.C: default: } } timerPool.Put(t) } // Execute sends a request to the dispatcher and waits for the response. func (p *dispatcherPool[Q, R]) Execute(ctx context.Context, q Message[Q]) (Message[R], error) { d := p.getDispatcher() call, err := d.newCall(q) if err != nil { return d.zeroR, err } if err := d.send(call); err != nil { return d.zeroR, err } timer := getTimer(30 * time.Second) defer putTimer(timer) select { case call = <-call.donec: case <-p.donec: return d.zeroR, p.Err() case <-ctx.Done(): return d.zeroR, ctx.Err() case <-timer.C: return d.zeroR, errors.New("timeout") } if call.err != nil { return d.zeroR, call.err } resp, err := call.response, p.Err() if err == nil && resp.Header.Err != "" { err = errors.New(resp.Header.Err) } return resp, err } func (d *dispatcher[Q, R]) newCall(q Message[Q]) (*call[Q, R], error) { if q.Header.ID == 0 { q.Header.ID = d.id.Add(1) } if err := q.init(); err != nil { return nil, err } responseKinds := maps.NewMap[string, bool]() for _, rk := range q.Header.ResponseKinds { responseKinds.Set(rk, true) } call := &call[Q, R]{ donec: make(chan *call[Q, R], 1), request: q, responseKinds: responseKinds, } if d.shutdown || d.closing { call.err = ErrShutdown call.done() return call, nil } d.mu.Lock() d.pending[q.GetID()] = call d.mu.Unlock() return call, nil } func (d *dispatcher[Q, R]) send(call *call[Q, R]) error { d.mu.Lock() if d.closing || d.shutdown { d.mu.Unlock() return ErrShutdown } d.mu.Unlock() d.encodeMu.Lock() defer d.encodeMu.Unlock() err := d.inOut.enc.Encode(call.request) if err != nil { return err } if sp, ok := any(call.request.Data).(SourceProvider); ok { source := sp.GetSource() if source.Size() == 0 { return errors.New("source size must be greater than 0") } if err := textandbinarywriter.WriteBlobHeader(d.inOut.stdin, call.request.GetID(), uint32(source.Size())); err != nil { return err } _, err := io.Copy(d.inOut.stdin, source) if err != nil { return err } } return nil } func (d *dispatcher[Q, R]) inputBlobs() error { var inputErr error for { id, length, err := textandbinarywriter.ReadBlobHeader(d.inOut.stdoutBinary) if err != nil { inputErr = err break } lr := &io.LimitedReader{ R: d.inOut.stdoutBinary, N: int64(length), } call := d.pendingCall(id) if err := call.handleBlob(lr); err != nil { inputErr = err break } if lr.N != 0 { inputErr = fmt.Errorf("blob %d: expected to read %d more bytes", id, lr.N) break } if err := call.responseKinds.WithWriteLock( func(m map[string]bool) error { if _, ok := m[MessageKindBlob]; !ok { return fmt.Errorf("unexpected blob response for %q call ID %d", call.request.Header.Command, id) } delete(m, MessageKindBlob) if len(m) == 0 { // Message exchange is complete. d.mu.Lock() delete(d.pending, id) d.mu.Unlock() call.done() } return nil }); err != nil { inputErr = err break } } return inputErr } func (d *dispatcher[Q, R]) inputJSON() error { var inputErr error for d.inOut.dec.More() { var r Message[R] if err := d.inOut.dec.Decode(&r); err != nil { inputErr = err break } call := d.pendingCall(r.GetID()) if err := call.responseKinds.WithWriteLock( func(m map[string]bool) error { call.response = r if _, ok := m[MessageKindJSON]; !ok { return fmt.Errorf("unexpected JSON response for call ID %d", r.GetID()) } delete(m, MessageKindJSON) if len(m) == 0 || r.Header.Err != "" { // Message exchange is complete. d.mu.Lock() delete(d.pending, r.GetID()) d.mu.Unlock() call.done() } return nil }); err != nil { inputErr = err break } } // Terminate pending calls. d.shutdown = true if inputErr != nil { isEOF := inputErr == io.EOF || inputErr == io.ErrClosedPipe || strings.Contains(inputErr.Error(), "already closed") if isEOF { if d.closing { inputErr = ErrShutdown } else { inputErr = io.ErrUnexpectedEOF } } } d.mu.Lock() defer d.mu.Unlock() for _, call := range d.pending { call.err = inputErr call.done() } return inputErr } func (d *dispatcher[Q, R]) pendingCall(id uint32) *call[Q, R] { d.mu.Lock() defer d.mu.Unlock() c, ok := d.pending[id] if !ok { panic(fmt.Errorf("call with ID %d not found", id)) } return c } type call[Q, R any] struct { request Message[Q] response Message[R] responseKinds *maps.Map[string, bool] err error donec chan *call[Q, R] } func (c *call[Q, R]) handleBlob(r io.Reader) error { dest := any(c.request.Data).(DestinationProvider).GetDestination() if dest == nil { panic("blob destination is not set") } _, err := io.Copy(dest, r) return err } func (call *call[Q, R]) done() { select { case call.donec <- call: default: } } // Binary represents a WebAssembly binary. type Binary struct { // The name of the binary. // For quickjs, this must match the instance import name, "javy_quickjs_provider_v2". // For the main module, we only use this for caching. Name string // THe wasm binary. Data []byte } type ProtocolType int const ( ProtocolJSON ProtocolType = iota + 1 ProtocolJSONAndBinary = iota ) type Options struct { Ctx context.Context Infof func(format string, v ...any) Warnf func(format string, v ...any) // E.g. quickjs wasm. May be omitted if not needed. Runtime Binary // The main module to instantiate. Main Binary CompilationCacheDir string PoolSize int // Memory limit in MiB. Memory int } func (o *Options) init() error { if o.Infof == nil { o.Infof = func(format string, v ...any) { } } if o.Warnf == nil { o.Warnf = func(format string, v ...any) { } } return nil } type CompileModuleContext struct { Opts Options Runtime wazero.Runtime } type CompiledModule struct { // Runtime (e.g. QuickJS) may be nil if not needed (e.g. embedded in Module). Runtime wazero.CompiledModule // If Runtime is not nil, this should be the name of the instance. RuntimeName string // The main module to instantiate. // This will be insantiated multiple times in a pool, // so it does not need a name. Module wazero.CompiledModule } // Start creates a new dispatcher pool. func Start[Q, R any](opts Options) (Dispatcher[Q, R], error) { if opts.Main.Data == nil { return nil, errors.New("Main.Data must be set") } if opts.Main.Name == "" { return nil, errors.New("Main.Name must be set") } if opts.Runtime.Data != nil && opts.Runtime.Name == "" { return nil, errors.New("Runtime.Name must be set") } if opts.PoolSize == 0 { opts.PoolSize = 1 } return newDispatcher[Q, R](opts) } type dispatcherPool[Q, R any] struct { counter atomic.Uint32 dispatchers []*dispatcher[Q, R] close func() error opts Options errc chan error donec chan struct{} } func (p *dispatcherPool[Q, R]) SendIfErr(err error) { if err != nil { p.errc <- err } } func (p *dispatcherPool[Q, R]) Err() error { select { case err := <-p.errc: return err default: return nil } } func newDispatcher[Q, R any](opts Options) (*dispatcherPool[Q, R], error) { if opts.Ctx == nil { opts.Ctx = context.Background() } if opts.Infof == nil { opts.Infof = func(format string, v ...any) { // noop } } if opts.Warnf == nil { opts.Warnf = func(format string, v ...any) { // noop } } if opts.Memory <= 0 { opts.Memory = 32 // 32 MiB } ctx := opts.Ctx // Page size is 64KB. numPages := opts.Memory * 1024 / 64 runtimeConfig := wazero.NewRuntimeConfig().WithMemoryLimitPages(uint32(numPages)) if opts.CompilationCacheDir != "" { compilationCache, err := wazero.NewCompilationCacheWithDir(opts.CompilationCacheDir) if err != nil { return nil, err } runtimeConfig = runtimeConfig.WithCompilationCache(compilationCache) } // Create a new WebAssembly Runtime. r := wazero.NewRuntimeWithConfig(opts.Ctx, runtimeConfig) // Instantiate WASI, which implements system I/O such as console output. if _, err := wasi_snapshot_preview1.Instantiate(ctx, r); err != nil { return nil, err } dispatchers := make([]*dispatcher[Q, R], opts.PoolSize) inOuts := make([]*inOut, opts.PoolSize) for i := range opts.PoolSize { var stdinPipe, stdoutBinary hugio.ReadWriteCloser var stdout io.WriteCloser var jsonr io.Reader stdinPipe = hugio.NewPipeReadWriteCloser() stdoutPipe := hugio.NewPipeReadWriteCloser() stdout = stdoutPipe var zero Q if _, ok := any(zero).(DestinationProvider); ok { stdoutBinary = hugio.NewPipeReadWriteCloser() jsonr = stdoutPipe stdout = textandbinarywriter.NewWriter(stdout, stdoutBinary) } else { jsonr = stdoutPipe } inOuts[i] = &inOut{ stdin: stdinPipe, stdout: stdout, stdoutBinary: stdoutBinary, dec: json.NewDecoder(jsonr), enc: json.NewEncoder(stdinPipe), } } var ( runtimeModule wazero.CompiledModule mainModule wazero.CompiledModule err error ) if opts.Runtime.Data != nil { runtimeModule, err = r.CompileModule(experimental.WithCompilationWorkers(ctx, runtime.GOMAXPROCS(0)/4), opts.Runtime.Data) if err != nil { return nil, err } } mainModule, err = r.CompileModule(experimental.WithCompilationWorkers(ctx, runtime.GOMAXPROCS(0)/4), opts.Main.Data) if err != nil { return nil, err } toErr := func(what string, errBuff bytes.Buffer, err error) error { return fmt.Errorf("%s: %s: %w", what, errBuff.String(), err) } run := func() error { g, ctx := errgroup.WithContext(ctx) for _, c := range inOuts { g.Go(func() error { var errBuff bytes.Buffer stderr := io.MultiWriter(&errBuff, os.Stderr) ctx := context.WithoutCancel(ctx) // WithStartFunctions allows us to call the _start function manually. configBase := wazero.NewModuleConfig().WithStderr(stderr).WithStdout(c.stdout).WithStdin(c.stdin).WithStartFunctions() if opts.Runtime.Data != nil { // This needs to be anonymous, it will be resolved in the import resolver below. runtimeInstance, err := r.InstantiateModule(ctx, runtimeModule, configBase.WithName("")) if err != nil { return toErr("quickjs", errBuff, err) } ctx = experimental.WithImportResolver(ctx, func(name string) api.Module { if name == opts.Runtime.Name { return runtimeInstance } return nil }, ) } mainInstance, err := r.InstantiateModule(ctx, mainModule, configBase.WithName("")) if err != nil { return toErr(opts.Main.Name, errBuff, err) } if _, err := mainInstance.ExportedFunction("_start").Call(ctx); err != nil { return toErr(opts.Main.Name, errBuff, err) } // The console.log in the Javy/quickjs WebAssembly module will write to stderr. // In non-error situations, write that to the provided infof logger. if errBuff.Len() > 0 { opts.Infof("%s", errBuff.String()) } return nil }) } return g.Wait() } dp := &dispatcherPool[Q, R]{ dispatchers: dispatchers, opts: opts, errc: make(chan error, 10), donec: make(chan struct{}), } go func() { // This will block until stdin is closed or it encounters an error. err := run() dp.SendIfErr(err) close(dp.donec) }() for i := range inOuts { ing, _ := errgroup.WithContext(ctx) d := &dispatcher[Q, R]{ pending: make(map[uint32]*call[Q, R]), inOut: inOuts[i], inGroup: ing, } d.inGroup.Go(func() error { return d.inputJSON() }) if d.inOut.stdoutBinary != nil { d.inGroup.Go(func() error { return d.inputBlobs() }) } dp.dispatchers[i] = d } dp.close = func() error { for _, d := range dp.dispatchers { d.closing = true if err := d.inOut.Close(); err != nil { return err } } for _, d := range dp.dispatchers { if err := d.inGroup.Wait(); err != nil { return err } } // We need to wait for the WebAssembly instances to finish executing before we can close the runtime. <-dp.donec if err := r.Close(ctx); err != nil { return err } // Return potential late compilation errors. return dp.Err() } return dp, dp.Err() } type lazyDispatcher[Q, R any] struct { opts Options dispatcher Dispatcher[Q, R] startOnce sync.Once started bool startErr error } func (d *lazyDispatcher[Q, R]) start() (Dispatcher[Q, R], error) { d.startOnce.Do(func() { start := time.Now() d.dispatcher, d.startErr = Start[Q, R](d.opts) d.started = true d.opts.Infof("started dispatcher in %s", time.Since(start)) }) return d.dispatcher, d.startErr } // Dispatchers holds all the dispatchers for the warpc package. type Dispatchers struct { katex *lazyDispatcher[KatexInput, KatexOutput] webp *lazyDispatcher[WebpInput, WebpOutput] } func (d *Dispatchers) Katex() (Dispatcher[KatexInput, KatexOutput], error) { return d.katex.start() } func (d *Dispatchers) Webp() (Dispatcher[WebpInput, WebpOutput], error) { return d.webp.start() } func (d *Dispatchers) NewWepCodec() (*WebpCodec, error) { return &WebpCodec{ d: d.Webp, }, nil } func (d *Dispatchers) Close() error { var errs []error if d.katex.started { if err := d.katex.dispatcher.Close(); err != nil { errs = append(errs, err) } } if d.webp.started { if err := d.webp.dispatcher.Close(); err != nil { errs = append(errs, err) } } if len(errs) == 0 { return nil } return fmt.Errorf("%v", errs) } // AllDispatchers creates all the dispatchers for the warpc package. // Note that the individual dispatchers are started lazily. // Remember to call Close on the returned Dispatchers when done. func AllDispatchers(katexOpts, webpOpts Options) *Dispatchers { if err := katexOpts.init(); err != nil { panic(err) } if err := webpOpts.init(); err != nil { panic(err) } if katexOpts.Runtime.Data == nil { katexOpts.Runtime = Binary{Name: "javy_quickjs_provider_v2", Data: quickjsWasm} } if katexOpts.Main.Data == nil { katexOpts.Main = Binary{Name: "renderkatex", Data: katexWasm} } webpOpts.Main = Binary{Name: "webp", Data: webpWasm} dispatchers := &Dispatchers{ katex: &lazyDispatcher[KatexInput, KatexOutput]{opts: katexOpts}, webp: &lazyDispatcher[WebpInput, WebpOutput]{opts: webpOpts}, } return dispatchers }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/warpc/warpc_test.go
internal/warpc/warpc_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 warpc import ( "context" _ "embed" "fmt" "sync" "sync/atomic" "testing" qt "github.com/frankban/quicktest" ) //go:embed wasm/greet.wasm var greetWasm []byte type person struct { Name string `json:"name"` } func TestKatex(t *testing.T) { c := qt.New(t) opts := Options{ PoolSize: 8, Runtime: quickjsBinary, Main: katexBinary, } d, err := Start[KatexInput, KatexOutput](opts) c.Assert(err, qt.IsNil) defer d.Close() runExpression := func(c *qt.C, id uint32, expression string) (Message[KatexOutput], error) { c.Helper() ctx := context.Background() input := KatexInput{ Expression: expression, Options: KatexOptions{ Output: "html", DisplayMode: true, ThrowOnError: true, }, } message := Message[KatexInput]{ Header: Header{ Version: currentVersion, ID: uint32(id), }, Data: input, } return d.Execute(ctx, message) } c.Run("Simple", func(c *qt.C) { id := uint32(32) result, err := runExpression(c, id, "c = \\pm\\sqrt{a^2 + b^2}") c.Assert(err, qt.IsNil) c.Assert(result.GetID(), qt.Equals, id) }) c.Run("Chemistry", func(c *qt.C) { id := uint32(32) result, err := runExpression(c, id, "C_p[\\ce{H2O(l)}] = \\pu{75.3 J // mol K}") c.Assert(err, qt.IsNil) c.Assert(result.GetID(), qt.Equals, id) }) c.Run("Invalid expression", func(c *qt.C) { id := uint32(32) result, err := runExpression(c, id, "c & \\foo\\") c.Assert(err, qt.IsNotNil) c.Assert(result.GetID(), qt.Equals, id) }) } func TestGreet(t *testing.T) { c := qt.New(t) opts := Options{ PoolSize: 1, Runtime: quickjsBinary, Main: greetBinary, Infof: t.Logf, } for range 2 { func() { d, err := Start[person, greeting](opts) if err != nil { t.Fatal(err) } defer func() { c.Assert(d.Close(), qt.IsNil) }() ctx := context.Background() inputMessage := Message[person]{ Header: Header{ Version: currentVersion, }, Data: person{ Name: "Person", }, } for j := range 20 { inputMessage.Header.ID = uint32(j + 1) g, err := d.Execute(ctx, inputMessage) if err != nil { t.Fatal(err) } if g.Data.Greeting != "Hello Person!" { t.Fatalf("got: %v", g) } if g.GetID() != inputMessage.GetID() { t.Fatalf("%d vs %d", g.GetID(), inputMessage.GetID()) } } }() } } func TestGreetParallel(t *testing.T) { c := qt.New(t) opts := Options{ Runtime: quickjsBinary, Main: greetBinary, PoolSize: 4, } d, err := Start[person, greeting](opts) c.Assert(err, qt.IsNil) defer func() { c.Assert(d.Close(), qt.IsNil) }() var wg sync.WaitGroup for i := 1; i <= 10; i++ { wg.Add(1) go func(i int) { defer wg.Done() ctx := context.Background() for j := range 5 { base := i * 100 id := uint32(base + j) inputPerson := person{ Name: fmt.Sprintf("Person %d", id), } inputMessage := Message[person]{ Header: Header{ Version: currentVersion, ID: id, }, Data: inputPerson, } g, err := d.Execute(ctx, inputMessage) if err != nil { t.Error(err) return } c.Assert(g.Data.Greeting, qt.Equals, fmt.Sprintf("Hello Person %d!", id)) c.Assert(g.GetID(), qt.Equals, inputMessage.GetID()) } }(i) } wg.Wait() } func TestKatexParallel(t *testing.T) { c := qt.New(t) opts := Options{ Runtime: quickjsBinary, Main: katexBinary, PoolSize: 6, } d, err := Start[KatexInput, KatexOutput](opts) c.Assert(err, qt.IsNil) defer func() { c.Assert(d.Close(), qt.IsNil) }() var wg sync.WaitGroup for i := 1; i <= 10; i++ { wg.Add(1) go func(i int) { defer wg.Done() ctx := context.Background() for j := range 1 { base := i * 100 id := uint32(base + j) input := katexInputTemplate inputMessage := Message[KatexInput]{ Header: Header{ Version: currentVersion, ID: id, }, Data: input, } result, err := d.Execute(ctx, inputMessage) if err != nil { t.Error(err) return } if result.GetID() != inputMessage.GetID() { t.Errorf("%d vs %d", result.GetID(), inputMessage.GetID()) return } } }(i) } wg.Wait() } func BenchmarkExecuteKatex(b *testing.B) { opts := Options{ Runtime: quickjsBinary, Main: katexBinary, } d, err := Start[KatexInput, KatexOutput](opts) if err != nil { b.Fatal(err) } defer d.Close() ctx := context.Background() input := katexInputTemplate for i := 0; b.Loop(); i++ { message := Message[KatexInput]{ Header: Header{ Version: currentVersion, ID: uint32(i + 1), }, Data: input, } result, err := d.Execute(ctx, message) if err != nil { b.Fatal(err) } if result.GetID() != message.GetID() { b.Fatalf("%d vs %d", result.GetID(), message.GetID()) } } } func BenchmarkKatexStartStop(b *testing.B) { optsTemplate := Options{ Runtime: quickjsBinary, Main: katexBinary, CompilationCacheDir: b.TempDir(), } runBench := func(b *testing.B, opts Options) { for b.Loop() { d, err := Start[KatexInput, KatexOutput](opts) if err != nil { b.Fatal(err) } if err := d.Close(); err != nil { b.Fatal(err) } } } for _, poolSize := range []int{1, 8, 16} { name := fmt.Sprintf("PoolSize%d", poolSize) b.Run(name, func(b *testing.B) { opts := optsTemplate opts.PoolSize = poolSize runBench(b, opts) }) } } var katexInputTemplate = KatexInput{ Expression: "c = \\pm\\sqrt{a^2 + b^2}", Options: KatexOptions{Output: "html", DisplayMode: true}, } func BenchmarkExecuteKatexPara(b *testing.B) { optsTemplate := Options{ Runtime: quickjsBinary, Main: katexBinary, } runBench := func(b *testing.B, opts Options) { d, err := Start[KatexInput, KatexOutput](opts) if err != nil { b.Fatal(err) } defer d.Close() ctx := context.Background() b.ResetTimer() var id atomic.Uint32 b.RunParallel(func(pb *testing.PB) { for pb.Next() { message := Message[KatexInput]{ Header: Header{ Version: currentVersion, ID: id.Add(1), }, Data: katexInputTemplate, } result, err := d.Execute(ctx, message) if err != nil { b.Fatal(err) } if result.GetID() != message.GetID() { b.Fatalf("%d vs %d", result.GetID(), message.GetID()) } } }) } for _, poolSize := range []int{1, 8, 16} { name := fmt.Sprintf("PoolSize%d", poolSize) b.Run(name, func(b *testing.B) { opts := optsTemplate opts.PoolSize = poolSize runBench(b, opts) }) } } func BenchmarkExecuteGreet(b *testing.B) { opts := Options{ Runtime: quickjsBinary, Main: greetBinary, } d, err := Start[person, greeting](opts) if err != nil { b.Fatal(err) } defer d.Close() ctx := context.Background() input := person{ Name: "Person", } for i := 0; b.Loop(); i++ { message := Message[person]{ Header: Header{ Version: currentVersion, ID: uint32(i + 1), }, Data: input, } result, err := d.Execute(ctx, message) if err != nil { b.Fatal(err) } if result.GetID() != message.GetID() { b.Fatalf("%d vs %d", result.GetID(), message.GetID()) } } } func BenchmarkExecuteGreetPara(b *testing.B) { opts := Options{ Runtime: quickjsBinary, Main: greetBinary, PoolSize: 8, } d, err := Start[person, greeting](opts) if err != nil { b.Fatal(err) } defer d.Close() ctx := context.Background() inputTemplate := person{ Name: "Person", } b.ResetTimer() var id atomic.Uint32 b.RunParallel(func(pb *testing.PB) { for pb.Next() { message := Message[person]{ Header: Header{ Version: currentVersion, ID: id.Add(1), }, Data: inputTemplate, } result, err := d.Execute(ctx, message) if err != nil { b.Fatal(err) } if result.GetID() != message.GetID() { b.Fatalf("%d vs %d", result.GetID(), message.GetID()) } } }) } type greeting struct { Greeting string `json:"greeting"` } var ( greetBinary = Binary{ Name: "greet", Data: greetWasm, } katexBinary = Binary{ Name: "renderkatex", Data: katexWasm, } quickjsBinary = Binary{ Name: "javy_quickjs_provider_v2", Data: quickjsWasm, } )
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/internal/warpc/genjs/main.go
internal/warpc/genjs/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. //go:generate go run main.go package main import ( "fmt" "log" "os" "path/filepath" "strings" "github.com/evanw/esbuild/pkg/api" ) var scripts = []string{ "greet.js", "renderkatex.js", } func main() { for _, script := range scripts { filename := filepath.Join("../js", script) err := buildJSBundle(filename) if err != nil { log.Fatal(err) } } } func buildJSBundle(filename string) error { minify := true result := api.Build( api.BuildOptions{ EntryPoints: []string{filename}, Bundle: true, MinifyWhitespace: minify, MinifyIdentifiers: minify, MinifySyntax: minify, Target: api.ES2020, Outfile: strings.Replace(filename, ".js", ".bundle.js", 1), SourceRoot: "../js", }) if len(result.Errors) > 0 { return fmt.Errorf("build failed: %v", result.Errors) } if len(result.OutputFiles) != 1 { return fmt.Errorf("expected 1 output file, got %d", len(result.OutputFiles)) } of := result.OutputFiles[0] if err := os.WriteFile(filepath.FromSlash(of.Path), of.Contents, 0o644); err != nil { return fmt.Errorf("write file failed: %v", err) } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/client.go
modules/client.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 modules import ( "bufio" "bytes" "context" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "regexp" "sort" "strings" "time" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config" hglob "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gobwas/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs/files" "golang.org/x/mod/module" "github.com/gohugoio/hugo/common/hugio" "github.com/spf13/afero" ) var fileSeparator = string(os.PathSeparator) const ( goBinaryStatusOK goBinaryStatus = iota goBinaryStatusNotFound goBinaryStatusTooOld ) // The "vendor" dir is reserved for Go Modules. const vendord = "_vendor" const ( goModFilename = "go.mod" goSumFilename = "go.sum" // Checksum file for direct dependencies only, // that is, module imports with version set. hugoDirectSumFilename = "hugo.direct.sum" ) // NewClient creates a new Client that can be used to manage the Hugo Components // in a given workingDir. // The Client will resolve the dependencies recursively, but needs the top // level imports to start out. func NewClient(cfg ClientConfig) *Client { fs := cfg.Fs n := filepath.Join(cfg.WorkingDir, goModFilename) goModEnabled, _ := afero.Exists(fs, n) var goModFilename string if goModEnabled { goModFilename = n } logger := cfg.Logger if logger == nil { logger = loggers.NewDefault() } var noVendor glob.Glob if cfg.ModuleConfig.NoVendor != "" { noVendor, _ = hglob.GetGlob(hglob.NormalizePath(cfg.ModuleConfig.NoVendor)) } return &Client{ fs: fs, ccfg: cfg, logger: logger, noVendor: noVendor, moduleConfig: cfg.ModuleConfig, environ: cfg.toEnv(), GoModulesFilename: goModFilename, } } // Client contains most of the API provided by this package. type Client struct { fs afero.Fs logger loggers.Logger noVendor glob.Glob ccfg ClientConfig // The top level module config moduleConfig Config // Environment variables used in "go get" etc. environ []string // Set when Go modules are initialized in the current repo, that is: // a go.mod file exists. GoModulesFilename string // Set if we get a exec.ErrNotFound when running Go, which is most likely // due to being run on a system without Go installed. We record it here // so we can give an instructional error at the end if module/theme // resolution fails. goBinaryStatus goBinaryStatus } // Graph writes a module dependency graph to the given writer. func (c *Client) Graph(w io.Writer) error { mc, coll := c.collect(true) if coll.err != nil { return coll.err } for _, module := range mc.AllModules { if module.Owner() == nil { continue } dep := pathVersion(module.Owner()) + " " + pathVersion(module) if replace := module.Replace(); replace != nil { if replace.Version() != "" { dep += " => " + pathVersion(replace) } else { // Local dir. dep += " => " + replace.Dir() } } fmt.Fprintln(w, dep) } return nil } // Tidy can be used to remove unused dependencies from go.mod and go.sum. func (c *Client) Tidy() error { tc, coll := c.collect(false) if coll.err != nil { return coll.err } if coll.skipTidy { return nil } return c.tidy(tc.AllModules, false) } // Vendor writes all the module dependencies to a _vendor folder. // // Unlike Go, we support it for any level. // // We, by default, use the /_vendor folder first, if found. To disable, // run with // // hugo --ignoreVendorPaths=".*" // // Given a module tree, Hugo will pick the first module for a given path, // meaning that if the top-level module is vendored, that will be the full // set of dependencies. func (c *Client) Vendor() error { vendorDir := filepath.Join(c.ccfg.WorkingDir, vendord) if err := c.rmVendorDir(vendorDir); err != nil { return err } if err := c.fs.MkdirAll(vendorDir, 0o755); err != nil { return err } // Write the modules list to modules.txt. // // On the form: // // # github.com/alecthomas/chroma v0.6.3 // // This is how "go mod vendor" does it. Go also lists // the packages below it, but that is currently not applicable to us. // var modulesContent bytes.Buffer tc, coll := c.collect(true) if coll.err != nil { return coll.err } for _, t := range tc.AllModules { if t.Owner() == nil { // This is the project. continue } if c.shouldNotVendor(t.PathVersionQuery(false)) || c.shouldNotVendor(t.PathVersionQuery(true)) { continue } if !t.IsGoMod() && !t.Vendor() { // We currently do not vendor components living in the // theme directory, see https://github.com/gohugoio/hugo/issues/5993 continue } // See https://github.com/gohugoio/hugo/issues/8239 // This is an error situation. We need something to vendor. if t.Mounts() == nil { return fmt.Errorf("cannot vendor module %q, need at least one mount", t.PathVersionQuery(false)) } fmt.Fprintln(&modulesContent, "# "+t.PathVersionQuery(true)+" "+t.Version()) dir := t.Dir() for _, mount := range t.Mounts() { sourceFilename := filepath.Join(dir, mount.Source) targetFilename := filepath.Join(vendorDir, t.PathVersionQuery(true), mount.Source) fi, err := c.fs.Stat(sourceFilename) if err != nil { return fmt.Errorf("failed to vendor module: %w", err) } if fi.IsDir() { if err := hugio.CopyDir(c.fs, sourceFilename, targetFilename, nil); err != nil { return fmt.Errorf("failed to copy module to vendor dir: %w", err) } } else { targetDir := filepath.Dir(targetFilename) if err := c.fs.MkdirAll(targetDir, 0o755); err != nil { return fmt.Errorf("failed to make target dir: %w", err) } if err := hugio.CopyFile(c.fs, sourceFilename, targetFilename); err != nil { return fmt.Errorf("failed to copy module file to vendor: %w", err) } } } // Include the resource cache if present. resourcesDir := filepath.Join(dir, files.FolderResources) _, err := c.fs.Stat(resourcesDir) if err == nil { if err := hugio.CopyDir(c.fs, resourcesDir, filepath.Join(vendorDir, t.PathVersionQuery(true), files.FolderResources), nil); err != nil { return fmt.Errorf("failed to copy resources to vendor dir: %w", err) } } // Include the config directory if present. configDir := filepath.Join(dir, "config") _, err = c.fs.Stat(configDir) if err == nil { if err := hugio.CopyDir(c.fs, configDir, filepath.Join(vendorDir, t.PathVersionQuery(true), "config"), nil); err != nil { return fmt.Errorf("failed to copy config dir to vendor dir: %w", err) } } // Also include any theme.toml or config.* or hugo.* files in the root. configFiles, _ := afero.Glob(c.fs, filepath.Join(dir, "config.*")) configFiles2, _ := afero.Glob(c.fs, filepath.Join(dir, "hugo.*")) configFiles = append(configFiles, configFiles2...) configFiles = append(configFiles, filepath.Join(dir, "theme.toml")) for _, configFile := range configFiles { if err := hugio.CopyFile(c.fs, configFile, filepath.Join(vendorDir, t.PathVersionQuery(true), filepath.Base(configFile))); err != nil { if !herrors.IsNotExist(err) { return err } } } } if modulesContent.Len() > 0 { if err := afero.WriteFile(c.fs, filepath.Join(vendorDir, vendorModulesFilename), modulesContent.Bytes(), 0o666); err != nil { return err } } return nil } // Get runs "go get" with the supplied arguments. func (c *Client) Get(args ...string) error { if len(args) == 0 || (len(args) == 1 && strings.Contains(args[0], "-u")) { update := len(args) != 0 patch := update && (args[0] == "-u=patch") // // We need to be explicit about the modules to get. var modules []string // Update all active modules if the -u flag presents. if update { mc, coll := c.collect(true) if coll.err != nil { return coll.err } for _, m := range mc.AllModules { if m.Owner() == nil || !isProbablyModule(m.Path()) { continue } modules = append(modules, m.Path()) } } else { for _, m := range c.moduleConfig.Imports { if !isProbablyModule(m.Path) { // Skip themes/components stored below /themes etc. // There may be false positives in the above, but those // should be rare, and they will fail below with an // "cannot find module providing ..." message. continue } modules = append(modules, m.Path) } } for _, m := range modules { var args []string if update && !patch { args = append(args, "-u") } else if update && patch { args = append(args, "-u=patch") } args = append(args, m) if err := c.get(args...); err != nil { return err } } return nil } return c.get(args...) } func (c *Client) get(args ...string) error { if err := c.runGo(context.Background(), c.logger.StdOut(), append([]string{"get"}, args...)...); err != nil { return fmt.Errorf("failed to get %q: %w", args, err) } return nil } // Init initializes this as a Go Module with the given path. // If path is empty, Go will try to guess. // If this succeeds, this project will be marked as Go Module. func (c *Client) Init(path string) error { err := c.runGo(context.Background(), c.logger.StdOut(), "mod", "init", path) if err != nil { return fmt.Errorf("failed to init modules: %w", err) } c.GoModulesFilename = filepath.Join(c.ccfg.WorkingDir, goModFilename) return nil } var verifyErrorDirRe = regexp.MustCompile(`dir has been modified \((.*?)\)`) // Verify checks that the dependencies of the current module, // which are stored in a local downloaded source cache, have not been // modified since being downloaded. func (c *Client) Verify(clean bool) error { // TODO(bep) add path to mod clean err := c.runVerify() if err != nil { if clean { m := verifyErrorDirRe.FindAllStringSubmatch(err.Error(), -1) for i := range m { c, err := hugofs.MakeReadableAndRemoveAllModulePkgDir(c.fs, m[i][1]) if err != nil { return err } fmt.Println("Cleaned", c) } // Try to verify it again. err = c.runVerify() } } return err } func (c *Client) Clean(pattern string) error { mods, err := c.listGoMods() if err != nil { return err } var g glob.Glob if pattern != "" { var err error g, err = hglob.GetGlob(pattern) if err != nil { return err } } for _, m := range mods { if m.Replace != nil || m.Main { continue } if g != nil && !g.Match(m.Path) { continue } dirCount, err := hugofs.MakeReadableAndRemoveAllModulePkgDir(c.fs, m.Dir) if err == nil { c.logger.Printf("hugo: removed %d dirs in module cache for %q", dirCount, m.Path) } } return err } func (c *Client) runVerify() error { return c.runGo(context.Background(), io.Discard, "mod", "verify") } func isProbablyModule(path string) bool { return module.CheckPath(path) == nil } func (c *Client) downloadModuleVersion(path, version string) (*goModule, error) { args := []string{"mod", "download", "-json", fmt.Sprintf("%s@%s", path, version)} b := &bytes.Buffer{} err := c.runGo(context.Background(), b, args...) if err != nil { return nil, fmt.Errorf("failed to download module %s@%s: %w", path, version, err) } m := &goModule{} if err := json.NewDecoder(b).Decode(m); err != nil { return nil, fmt.Errorf("failed to decode module download result: %w", err) } if m.Error != nil { return nil, errors.New(m.Error.Err) } return m, nil } func (c *Client) listGoMods() (goModules, error) { if c.GoModulesFilename == "" || !c.moduleConfig.hasModuleImport() { return nil, nil } downloadModules := func(modules ...string) error { args := []string{"mod", "download"} args = append(args, modules...) out := io.Discard err := c.runGo(context.Background(), out, args...) if err != nil { return fmt.Errorf("failed to download modules: %w", err) } return nil } if err := downloadModules(); err != nil { return nil, err } listAndDecodeModules := func(handle func(m *goModule) error, modules ...string) error { b := &bytes.Buffer{} args := []string{"list", "-m", "-json"} if len(modules) > 0 { args = append(args, modules...) } else { args = append(args, "all") } err := c.runGo(context.Background(), b, args...) if err != nil { return fmt.Errorf("failed to list modules: %w", err) } dec := json.NewDecoder(b) for { m := &goModule{} if err := dec.Decode(m); err != nil { if err == io.EOF { break } return fmt.Errorf("failed to decode modules list: %w", err) } if err := handle(m); err != nil { return err } } return nil } var modules goModules err := listAndDecodeModules(func(m *goModule) error { modules = append(modules, m) return nil }) if err != nil { return nil, err } // From Go 1.17, go lazy loads transitive dependencies. // That does not work for us. // So, download these modules and update the Dir in the modules list. var modulesToDownload []string for _, m := range modules { if m.Dir == "" { modulesToDownload = append(modulesToDownload, fmt.Sprintf("%s@%s", m.Path, m.Version)) } } if len(modulesToDownload) > 0 { if err := downloadModules(modulesToDownload...); err != nil { return nil, err } err := listAndDecodeModules(func(m *goModule) error { if mm := modules.GetByPath(m.Path); mm != nil { mm.Dir = m.Dir } return nil }, modulesToDownload...) if err != nil { return nil, err } } return modules, err } func (c *Client) writeHugoDirectSum(mods Modules) error { if c.GoModulesFilename == "" { return nil } var sums []modSum for _, m := range mods { if m.Owner() == nil { // This is the project. continue } if m.IsGoMod() && m.VersionQuery() != "" { sums = append(sums, modSum{pathVersionKey: pathVersionKey{path: m.Path(), version: m.Version()}, sum: m.Sum()}) } } // Read the existing sums. existingSums, err := c.readModSumFile(hugoDirectSumFilename) if err != nil { return err } if len(sums) == 0 && len(existingSums) == 0 { // Nothing to do. return nil } dirty := len(sums) != len(existingSums) for _, s1 := range sums { if s2, ok := existingSums[s1.pathVersionKey]; ok { if s1.sum != s2 { return fmt.Errorf("verifying %s@%s: checksum mismatch: %s != %s", s1.path, s1.version, s1.sum, s2) } } else if !dirty { dirty = true } } if !dirty { // Nothing changed. return nil } // Write the sums file. // First sort the sums for reproducible output. sort.Slice(sums, func(i, j int) bool { pvi, pvj := sums[i].pathVersionKey, sums[j].pathVersionKey return pvi.path < pvj.path || (pvi.path == pvj.path && pvi.version < pvj.version) }) f, err := c.fs.OpenFile(filepath.Join(c.ccfg.WorkingDir, hugoDirectSumFilename), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o666) if err != nil { return err } defer f.Close() for _, s := range sums { fmt.Fprintf(f, "%s %s %s\n", s.pathVersionKey.path, s.pathVersionKey.version, s.sum) } return nil } func (c *Client) readModSumFile(filename string) (map[pathVersionKey]string, error) { b, err := afero.ReadFile(c.fs, filepath.Join(c.ccfg.WorkingDir, filename)) if err != nil { if herrors.IsNotExist(err) { return make(map[pathVersionKey]string), nil } return nil, err } lines := bytes.Split(b, []byte{'\n'}) sums := make(map[pathVersionKey]string) for _, line := range lines { parts := bytes.Fields(line) if len(parts) == 3 { sums[pathVersionKey{path: string(parts[0]), version: string(parts[1])}] = string(parts[2]) } } return sums, nil } func (c *Client) rewriteGoMod(name string, isGoMod map[string]bool) error { data, err := c.rewriteGoModRewrite(name, isGoMod) if err != nil { return err } if data != nil { if err := afero.WriteFile(c.fs, filepath.Join(c.ccfg.WorkingDir, name), data, 0o666); err != nil { return err } } return nil } func (c *Client) rewriteGoModRewrite(name string, isGoMod map[string]bool) ([]byte, error) { if name == goModFilename && c.GoModulesFilename == "" { // Already checked. return nil, nil } modlineSplitter := getModlineSplitter(name == goModFilename) b := &bytes.Buffer{} f, err := c.fs.Open(filepath.Join(c.ccfg.WorkingDir, name)) if err != nil { if herrors.IsNotExist(err) { // It's been deleted. return nil, nil } return nil, err } defer f.Close() scanner := bufio.NewScanner(f) var dirty bool for scanner.Scan() { line := scanner.Text() var doWrite bool if parts := modlineSplitter(line); parts != nil { modname, modver := parts[0], parts[1] modver = strings.TrimSuffix(modver, "/"+goModFilename) modnameVer := modname + " " + modver doWrite = isGoMod[modnameVer] } else { doWrite = true } if doWrite { fmt.Fprintln(b, line) } else { dirty = true } } if !dirty { // Nothing changed return nil, nil } return b.Bytes(), nil } func (c *Client) rmVendorDir(vendorDir string) error { modulestxt := filepath.Join(vendorDir, vendorModulesFilename) if _, err := c.fs.Stat(vendorDir); err != nil { return nil } _, err := c.fs.Stat(modulestxt) if err != nil { // If we have a _vendor dir without modules.txt it sounds like // a _vendor dir created by others. return errors.New("found _vendor dir without modules.txt, skip delete") } return c.fs.RemoveAll(vendorDir) } func (c *Client) runGo( ctx context.Context, stdout io.Writer, args ...string, ) error { if c.goBinaryStatus != 0 { return nil } stderr := new(bytes.Buffer) argsv := collections.StringSliceToInterfaceSlice(args) argsv = append(argsv, hexec.WithEnviron(c.environ)) argsv = append(argsv, hexec.WithStderr(goOutputReplacerWriter{w: io.MultiWriter(stderr, os.Stderr)})) argsv = append(argsv, hexec.WithStdout(stdout)) argsv = append(argsv, hexec.WithDir(c.ccfg.WorkingDir)) argsv = append(argsv, hexec.WithContext(ctx)) cmd, err := c.ccfg.Exec.New("go", argsv...) if err != nil { return err } if err := cmd.Run(); err != nil { if ee, ok := err.(*exec.Error); ok && ee.Err == exec.ErrNotFound { c.goBinaryStatus = goBinaryStatusNotFound return nil } if strings.Contains(stderr.String(), "invalid version: unknown revision") { // See https://github.com/gohugoio/hugo/issues/6825 c.logger.Println(`An unknown revision most likely means that someone has deleted the remote ref (e.g. with a force push to GitHub). To resolve this, you need to manually edit your go.mod file and replace the version for the module in question with a valid ref. The easiest is to just enter a valid branch name there, e.g. master, which would be what you put in place of 'v0.5.1' in the example below. require github.com/gohugoio/hugo-mod-jslibs/instantpage v0.5.1 If you then run 'hugo mod graph' it should resolve itself to the most recent version (or commit if no semver versions are available).`) } _, ok := err.(*exec.ExitError) if !ok { return fmt.Errorf("failed to execute 'go %v': %s %T", args, err, err) } // Too old Go version if strings.Contains(stderr.String(), "flag provided but not defined") { c.goBinaryStatus = goBinaryStatusTooOld return nil } return fmt.Errorf("go command failed: %s", stderr) } return nil } var goOutputReplacer = strings.NewReplacer( "go: to add module requirements and sums:", "hugo: to add module requirements and sums:", "go mod tidy", "hugo mod tidy", ) type goOutputReplacerWriter struct { w io.Writer } func (w goOutputReplacerWriter) Write(p []byte) (n int, err error) { s := goOutputReplacer.Replace(string(p)) _, err = w.w.Write([]byte(s)) if err != nil { return 0, err } return len(p), nil } func (c *Client) tidy(mods Modules, goModOnly bool) error { isGoMod := make(map[string]bool) for _, m := range mods { if m.Owner() == nil { continue } if m.IsGoMod() { // Matching the format in go.mod pathVer := m.Path() + " " + m.Version() isGoMod[pathVer] = true } } if err := c.rewriteGoMod(goModFilename, isGoMod); err != nil { return err } if goModOnly { return nil } if err := c.rewriteGoMod(goSumFilename, isGoMod); err != nil { return err } return nil } func (c *Client) shouldNotVendor(path string) bool { return c.noVendor != nil && c.noVendor.Match(path) } func (c *Client) createThemeDirname(modulePath string, isProjectMod bool) (string, error) { invalid := fmt.Errorf("invalid module path %q; must be relative to themesDir when defined outside of the project", modulePath) modulePath = filepath.Clean(modulePath) if filepath.IsAbs(modulePath) { if isProjectMod { return modulePath, nil } return "", invalid } moduleDir := filepath.Join(c.ccfg.ThemesDir, modulePath) if !isProjectMod && !strings.HasPrefix(moduleDir, c.ccfg.ThemesDir) { return "", invalid } return moduleDir, nil } // ClientConfig configures the module Client. type ClientConfig struct { Fs afero.Fs Logger loggers.Logger // If set, it will be run before we do any duplicate checks for modules // etc. HookBeforeFinalize func(m *ModulesConfig) error // Ignore any _vendor directory for module paths matching the given pattern. // This can be nil. IgnoreVendor glob.Glob // Ignore any module not found errors. IgnoreModuleDoesNotExist bool // Absolute path to the project dir. WorkingDir string // Absolute path to the project's themes dir. ThemesDir string // The publish dir. PublishDir string // Eg. "production" Environment string Exec *hexec.Exec CacheDir string // Module cache ModuleConfig Config } func (c ClientConfig) shouldIgnoreVendor(path string) bool { return c.IgnoreVendor != nil && c.IgnoreVendor.Match(path) } func (cfg ClientConfig) toEnv() []string { mcfg := cfg.ModuleConfig var env []string keyVals := []string{ "PWD", cfg.WorkingDir, "GO111MODULE", "on", "GOFLAGS", "-modcacherw", "GOPATH", cfg.CacheDir, "GOWORK", mcfg.Workspace, // Requires Go 1.18, see https://tip.golang.org/doc/go1.18 // GOCACHE was introduced in Go 1.15. This matches the location derived from GOPATH above. "GOCACHE", filepath.Join(cfg.CacheDir, "pkg", "mod"), } if mcfg.Proxy != "" { keyVals = append(keyVals, "GOPROXY", mcfg.Proxy) } if mcfg.Private != "" { keyVals = append(keyVals, "GOPRIVATE", mcfg.Private) } if mcfg.NoProxy != "" { keyVals = append(keyVals, "GONOPROXY", mcfg.NoProxy) } if mcfg.Auth != "" { // GOAUTH was introduced in Go 1.24, see https://tip.golang.org/doc/go1.24. keyVals = append(keyVals, "GOAUTH", mcfg.Auth) } config.SetEnvVars(&env, keyVals...) return env } type goBinaryStatus int type goModule struct { Path string // module path Version string // module version Versions []string // available module versions (with -versions) Replace *goModule // replaced by this module Time *time.Time // time version was created Update *goModule // available update, if any (with -u) Sum string // checksum Main bool // is this the main module? Indirect bool // is this module only an indirect dependency of main module? Dir string // directory holding files for this module, if any GoMod string // path to go.mod file for this module, if any Error *goModuleError // error loading module } type goModuleError struct { Err string // the error itself } type goModules []*goModule type modSum struct { pathVersionKey sum string } func (modules goModules) GetByPath(p string) *goModule { if modules == nil { return nil } for _, m := range modules { if strings.EqualFold(p, m.Path) { return m } } return nil } func (modules goModules) GetMain() *goModule { for _, m := range modules { if m.Main { return m } } return nil } func getModlineSplitter(isGoMod bool) func(line string) []string { if isGoMod { return func(line string) []string { if strings.HasPrefix(line, "require (") { return nil } if !strings.HasPrefix(line, "require") && !strings.HasPrefix(line, "\t") { return nil } line = strings.TrimPrefix(line, "require") line = strings.TrimSpace(line) line = strings.TrimSuffix(line, "// indirect") return strings.Fields(line) } } return func(line string) []string { return strings.Fields(line) } } func pathVersion(m Module) string { versionStr := m.Version() if m.Vendor() { versionStr += "+vendor" } if versionStr == "" { return m.Path() } return fmt.Sprintf("%s@%s", m.Path(), versionStr) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/collect_test.go
modules/collect_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 modules import ( "testing" qt "github.com/frankban/quicktest" ) func TestPathKey(t *testing.T) { c := qt.New(t) for _, test := range []struct { in string expect string }{ {"github.com/foo", "github.com/foo"}, {"github.com/foo/v2", "github.com/foo"}, {"github.com/foo/v12", "github.com/foo"}, {"github.com/foo/v3d", "github.com/foo/v3d"}, {"MyTheme", "mytheme"}, } { c.Assert(pathBase(test.in), qt.Equals, test.expect) } } func TestFilterUnwantedMounts(t *testing.T) { mounts := []Mount{ {Source: "a", Target: "b", Lang: "en"}, {Source: "a", Target: "b", Lang: "en"}, {Source: "b", Target: "c", Lang: "en"}, } filtered := filterDuplicateMounts(mounts) c := qt.New(t) c.Assert(len(filtered), qt.Equals, 2) c.Assert(filtered, qt.DeepEquals, []Mount{{Source: "a", Target: "b", Lang: "en"}, {Source: "b", Target: "c", Lang: "en"}}) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/config.go
modules/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 modules import ( "fmt" "os" "path/filepath" "slices" "strings" "github.com/bep/logg" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/common/version" "github.com/gohugoio/hugo/hugofs/files" hglob "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/config" "github.com/mitchellh/mapstructure" ) const WorkspaceDisabled = "off" var DefaultModuleConfig = Config{ // Default to direct, which means "git clone" and similar. We // will investigate proxy settings in more depth later. // See https://github.com/golang/go/issues/26334 Proxy: "direct", // Comma separated glob list matching paths that should not use the // proxy configured above. NoProxy: "none", // Comma separated glob list matching paths that should be // treated as private. Private: "*.*", // Default is no workspace resolution. Workspace: WorkspaceDisabled, // A list of replacement directives mapping a module path to a directory // or a theme component in the themes folder. // Note that this will turn the component into a traditional theme component // that does not partake in vendoring etc. // The syntax is the similar to the replacement directives used in go.mod, e.g: // github.com/mod1 -> ../mod1,github.com/mod2 -> ../mod2 Replacements: nil, } // ApplyProjectConfigDefaults applies default/missing module configuration for // the main project. func ApplyProjectConfigDefaults(logger logg.Logger, mod Module, cfgs ...config.AllProvider) error { moda := mod.(*moduleAdapter) // To bridge between old and new configuration format we need // a way to make sure all of the core components are configured on // the basic level. componentsConfigured := make(map[string]bool) for _, mnt := range moda.mounts { if !strings.HasPrefix(mnt.Target, files.JsConfigFolderMountPrefix) { componentsConfigured[mnt.Component()] = true } } var mounts []Mount for _, component := range []string{ files.ComponentFolderContent, files.ComponentFolderData, files.ComponentFolderLayouts, files.ComponentFolderI18n, files.ComponentFolderArchetypes, files.ComponentFolderAssets, files.ComponentFolderStatic, } { if componentsConfigured[component] { continue } first := cfgs[0] dirsBase := first.DirsBase() isMultihost := first.IsMultihost() for i, cfg := range cfgs { dirs := cfg.Dirs() var dir string var dropLang bool switch component { case files.ComponentFolderContent: dir = dirs.ContentDir dropLang = dir == dirsBase.ContentDir case files.ComponentFolderData: //lint:ignore SA1019 Keep as adapter for now. dir = dirs.DataDir case files.ComponentFolderLayouts: //lint:ignore SA1019 Keep as adapter for now. dir = dirs.LayoutDir case files.ComponentFolderI18n: //lint:ignore SA1019 Keep as adapter for now. dir = dirs.I18nDir case files.ComponentFolderArchetypes: //lint:ignore SA1019 Keep as adapter for now. dir = dirs.ArcheTypeDir case files.ComponentFolderAssets: //lint:ignore SA1019 Keep as adapter for now. dir = dirs.AssetDir case files.ComponentFolderStatic: // For static dirs, we only care about the language in multihost setups. dropLang = !isMultihost } var perLang bool switch component { case files.ComponentFolderContent, files.ComponentFolderStatic: perLang = true default: } if i > 0 && !perLang { continue } var lang string var sites sitesmatrix.Sites if perLang && !dropLang { l := cfg.Language().(*langs.Language) lang = l.Lang sites = sitesmatrix.Sites{ Matrix: sitesmatrix.StringSlices{ Languages: []string{l.Lang}, }, } } // Static mounts are a little special. if component == files.ComponentFolderStatic { staticDirs := cfg.StaticDirs() for _, dir := range staticDirs { mounts = append(mounts, Mount{Sites: sites, Source: dir, Target: component}) } continue } if dir != "" { mnt := Mount{Source: dir, Target: component, Sites: sites} if err := mnt.init(logger); err != nil { return fmt.Errorf("failed to init mount %q %d: %w", lang, i, err) } mounts = append(mounts, mnt) } } } moda.mounts = append(moda.mounts, mounts...) moda.mounts = filterDuplicateMounts(moda.mounts) return nil } // DecodeConfig creates a modules Config from a given Hugo configuration. func DecodeConfig(logger logg.Logger, cfg config.Provider) (Config, error) { return decodeConfig(logger, cfg, nil) } func decodeConfig(logger logg.Logger, cfg config.Provider, pathReplacements map[string]string) (Config, error) { c := DefaultModuleConfig c.replacementsMap = pathReplacements if cfg == nil { return c, nil } themeSet := cfg.IsSet("theme") moduleSet := cfg.IsSet("module") if moduleSet { m := cfg.GetStringMap("module") if err := mapstructure.WeakDecode(m, &c); err != nil { return c, err } if c.replacementsMap == nil { if len(c.Replacements) == 1 { c.Replacements = strings.Split(c.Replacements[0], ",") } for i, repl := range c.Replacements { c.Replacements[i] = strings.TrimSpace(repl) } c.replacementsMap = make(map[string]string) for _, repl := range c.Replacements { parts := strings.Split(repl, "->") if len(parts) != 2 { return c, fmt.Errorf(`invalid module.replacements: %q; configure replacement pairs on the form "oldpath->newpath" `, repl) } c.replacementsMap[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) } } if c.replacementsMap != nil && c.Imports != nil { for i, imp := range c.Imports { if newImp, found := c.replacementsMap[imp.Path]; found { imp.Path = newImp imp.pathProjectReplaced = true c.Imports[i] = imp } } } for i, mnt := range c.Mounts { mnt.Source = filepath.Clean(mnt.Source) mnt.Target = filepath.Clean(mnt.Target) if err := mnt.init(logger); err != nil { return c, fmt.Errorf("failed to init mount %d: %w", i, err) } c.Mounts[i] = mnt } if c.Workspace == "" { c.Workspace = WorkspaceDisabled } if c.Workspace != WorkspaceDisabled { c.Workspace = filepath.Clean(c.Workspace) if !filepath.IsAbs(c.Workspace) { workingDir := cfg.GetString("workingDir") c.Workspace = filepath.Join(workingDir, c.Workspace) } if _, err := os.Stat(c.Workspace); err != nil { //lint:ignore ST1005 end user message. return c, fmt.Errorf("module workspace %q does not exist. Check your module.workspace setting (or HUGO_MODULE_WORKSPACE env var).", c.Workspace) } } } if themeSet { imports := config.GetStringSlicePreserveString(cfg, "theme") for _, imp := range imports { c.Imports = append(c.Imports, Import{ Path: imp, }) } } return c, nil } // Config holds a module config. type Config struct { // File system mounts. Mounts []Mount // Module imports. Imports []Import // Meta info about this module (license information etc.). Params map[string]any // Will be validated against the running Hugo version. HugoVersion HugoVersion // Optional Glob pattern matching module paths to skip when vendoring, e.g. “github.com/**” NoVendor string // When enabled, we will pick the vendored module closest to the module // using it. // The default behavior is to pick the first. // Note that there can still be only one dependency of a given module path, // so once it is in use it cannot be redefined. VendorClosest bool // A comma separated (or a slice) list of module path to directory replacement mapping, // e.g. github.com/bep/my-theme -> ../..,github.com/bep/shortcodes -> /some/path. // This is mostly useful for temporary locally development of a module, and then it makes sense to set it as an // OS environment variable, e.g: env HUGO_MODULE_REPLACEMENTS="github.com/bep/my-theme -> ../..". // Any relative path is relate to themesDir, and absolute paths are allowed. Replacements []string replacementsMap map[string]string // Defines the proxy server to use to download remote modules. Default is direct, which means “git clone” and similar. // Configures GOPROXY when running the Go command for module operations. Proxy string // Comma separated glob list matching paths that should not use the proxy configured above. // Configures GONOPROXY when running the Go command for module operations. NoProxy string // Comma separated glob list matching paths that should be treated as private. // Configures GOPRIVATE when running the Go command for module operations. Private string // Configures GOAUTH when running the Go command for module operations. // This is a semicolon-separated list of authentication commands for go-import and HTTPS module mirror interactions. // This is useful for private repositories. // See `go help goauth` for more information. Auth string // Defaults to "off". // Set to a work file, e.g. hugo.work, to enable Go "Workspace" mode. // Can be relative to the working directory or absolute. // Requires Go 1.18+. // Note that this can also be set via OS env, e.g. export HUGO_MODULE_WORKSPACE=/my/hugo.work. Workspace string } // hasModuleImport reports whether the project config have one or more // modules imports, e.g. github.com/bep/myshortcodes. func (c Config) hasModuleImport() bool { for _, imp := range c.Imports { if isProbablyModule(imp.Path) { return true } } return false } // HugoVersion holds Hugo binary version requirements for a module. type HugoVersion struct { // The minimum Hugo version that this module works with. Min version.VersionString // The maximum Hugo version that this module works with. Max version.VersionString // Set if the extended version is needed. Extended bool } func (v HugoVersion) String() string { extended := "" if v.Extended { extended = " extended" } if v.Min != "" && v.Max != "" { return fmt.Sprintf("%s/%s%s", v.Min, v.Max, extended) } if v.Min != "" { return fmt.Sprintf("Min %s%s", v.Min, extended) } if v.Max != "" { return fmt.Sprintf("Max %s%s", v.Max, extended) } return extended } // IsValid reports whether this version is valid compared to the running // Hugo binary. func (v HugoVersion) IsValid() bool { current := hugo.CurrentVersion.Version() if v.Min != "" && current.Compare(v.Min) > 0 { return false } if v.Max != "" && current.Compare(v.Max) < 0 { return false } return true } type Import struct { // Module path Path string // The common case is to leave this empty and let Go Modules resolve the version. // Can be set to a version query, e.g. "v1.2.3", ">=v1.2.0", "latest", which will // make this a direct dependency. Version string // Set when Path is replaced in project config. pathProjectReplaced bool // Ignore any config in config.toml (will still follow imports). IgnoreConfig bool // Do not follow any configured imports. IgnoreImports bool // Do not mount any folder in this import. NoMounts bool // Never vendor this import (only allowed in main project). NoVendor bool // Turn off this module. Disable bool // File mounts. Mounts []Mount } type Mount struct { // Relative path in source repo, e.g. "scss". Source string // Relative target path, e.g. "assets/bootstrap/scss". Target string // Any file in this mount will be associated with this language. // Deprecated, use Sites instead. Lang string `json:"-"` // Sites defines which sites this mount applies to. Sites sitesmatrix.Sites // A slice of Glob patterns (string or slice) to exclude or include in this mount. // To exclude, prefix with "! ". Files []string // Include only files matching the given Glob patterns (string or slice). // Deprecated, use Files instead. IncludeFiles any `json:"-"` // Exclude all files matching the given Glob patterns (string or slice). // Deprecated, use Files instead. ExcludeFiles any `json:"-"` // Disable watching in watch mode for this mount. DisableWatch bool } func (m Mount) Equal(o Mount) bool { if m.Lang != o.Lang { return false } if m.Source != o.Source { return false } if m.Target != o.Target { return false } if m.DisableWatch != o.DisableWatch { return false } if !m.Sites.Equal(o.Sites) { return false } patterns, hasLegacy11, hasLegacy12 := m.FilesToFilter() patterns2, hasLegacy21, hasLegacy22 := o.FilesToFilter() if hasLegacy11 != hasLegacy21 || hasLegacy12 != hasLegacy22 { return false } return slices.Equal(patterns, patterns2) } func (m Mount) FilesToFilter() (patterns []string, hasLegacyIncludeFiles, hasLegacyExcludeFiles bool) { patterns = m.Files // Legacy config, add IncludeFiles first. for _, pattern := range types.ToStringSlicePreserveString(m.IncludeFiles) { hasLegacyIncludeFiles = true patterns = append(patterns, pattern) } for _, pattern := range types.ToStringSlicePreserveString(m.ExcludeFiles) { hasLegacyExcludeFiles = true patterns = append(patterns, hglob.NegationPrefix+pattern) } return patterns, hasLegacyIncludeFiles, hasLegacyExcludeFiles } func (m Mount) Component() string { return strings.Split(m.Target, fileSeparator)[0] } func (m Mount) ComponentAndName() (string, string) { c, n, _ := strings.Cut(m.Target, fileSeparator) return c, n } func (m *Mount) init(logger logg.Logger) error { if m.Lang != "" { // We moved this to a more flixeble setup in Hugo 0.153.0. m.Sites.Matrix.Languages = append(m.Sites.Matrix.Languages, m.Lang) m.Lang = "" hugo.DeprecateWithLogger("module.mounts.lang", "Replaced by the more powerful 'sites.matrix' setting, see https://gohugo.io/configuration/module/#mounts", "v0.153.0", logger) } m.Sites.Matrix.Languages = hstrings.UniqueStringsReuse(m.Sites.Matrix.Languages) return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/client_test.go
modules/client_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 modules import ( "bytes" "fmt" "os" "path/filepath" "sync/atomic" "testing" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config/security" hglob "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugofs" qt "github.com/frankban/quicktest" ) func TestClient(t *testing.T) { modName := "hugo-modules-basic-test" modPath := "github.com/gohugoio/tests/" + modName defaultImport := "modh2_2" expect := `github.com/gohugoio/tests/hugo-modules-basic-test github.com/gohugoio/hugoTestModules1_darwin/modh2_2@v1.4.0 github.com/gohugoio/hugoTestModules1_darwin/modh2_2@v1.4.0 github.com/gohugoio/hugoTestModules1_darwin/modh2_2_1v@v1.3.0 github.com/gohugoio/hugoTestModules1_darwin/modh2_2@v1.4.0 github.com/gohugoio/hugoTestModules1_darwin/modh2_2_2@v1.3.0 ` c := qt.New(t) var clientID uint64 // we increment this to get each test in its own directory. newClient := func(c *qt.C, withConfig func(cfg *ClientConfig), imp string) (*Client, func()) { atomic.AddUint64(&clientID, uint64(1)) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("%s-%d", modName, clientID)) c.Assert(err, qt.IsNil) themesDir := filepath.Join(workingDir, "themes") err = os.Mkdir(themesDir, 0o777) c.Assert(err, qt.IsNil) publishDir := filepath.Join(workingDir, "public") err = os.Mkdir(publishDir, 0o777) c.Assert(err, qt.IsNil) ccfg := ClientConfig{ Fs: hugofs.Os, CacheDir: filepath.Join(workingDir, "modcache"), WorkingDir: workingDir, ThemesDir: themesDir, PublishDir: publishDir, Exec: hexec.New(security.DefaultConfig, "", loggers.NewDefault()), } withConfig(&ccfg) ccfg.ModuleConfig.Imports = []Import{{Path: "github.com/gohugoio/hugoTestModules1_darwin/" + imp}} client := NewClient(ccfg) return client, clean } c.Run("All", func(c *qt.C) { client, clean := newClient(c, func(cfg *ClientConfig) { cfg.ModuleConfig = DefaultModuleConfig }, defaultImport) defer clean() // Test Init c.Assert(client.Init(modPath), qt.IsNil) // Test Collect mc, err := client.Collect() c.Assert(err, qt.IsNil) c.Assert(len(mc.AllModules), qt.Equals, 4) for _, m := range mc.AllModules { c.Assert(m, qt.Not(qt.IsNil)) } // Test Graph var graphb bytes.Buffer c.Assert(client.Graph(&graphb), qt.IsNil) c.Assert(graphb.String(), qt.Equals, expect) // Test Vendor c.Assert(client.Vendor(), qt.IsNil) graphb.Reset() c.Assert(client.Graph(&graphb), qt.IsNil) expectVendored := `project github.com/gohugoio/hugoTestModules1_darwin/modh2_2@v1.4.0+vendor project github.com/gohugoio/hugoTestModules1_darwin/modh2_2_1v@v1.3.0+vendor project github.com/gohugoio/hugoTestModules1_darwin/modh2_2_2@v1.3.0+vendor ` c.Assert(graphb.String(), qt.Equals, expectVendored) // Test Tidy c.Assert(client.Tidy(), qt.IsNil) }) c.Run("IgnoreVendor", func(c *qt.C) { client, clean := newClient( c, func(cfg *ClientConfig) { cfg.ModuleConfig = DefaultModuleConfig cfg.IgnoreVendor = globAll }, defaultImport) defer clean() c.Assert(client.Init(modPath), qt.IsNil) _, err := client.Collect() c.Assert(err, qt.IsNil) c.Assert(client.Vendor(), qt.IsNil) var graphb bytes.Buffer c.Assert(client.Graph(&graphb), qt.IsNil) c.Assert(graphb.String(), qt.Equals, expect) }) c.Run("NoVendor", func(c *qt.C) { mcfg := DefaultModuleConfig mcfg.NoVendor = "**" client, clean := newClient( c, func(cfg *ClientConfig) { cfg.ModuleConfig = mcfg }, defaultImport) defer clean() c.Assert(client.Init(modPath), qt.IsNil) _, err := client.Collect() c.Assert(err, qt.IsNil) c.Assert(client.Vendor(), qt.IsNil) var graphb bytes.Buffer c.Assert(client.Graph(&graphb), qt.IsNil) c.Assert(graphb.String(), qt.Equals, expect) }) c.Run("VendorClosest", func(c *qt.C) { mcfg := DefaultModuleConfig mcfg.VendorClosest = true client, clean := newClient( c, func(cfg *ClientConfig) { cfg.ModuleConfig = mcfg s := "github.com/gohugoio/hugoTestModules1_darwin/modh1_1v" g, _ := hglob.GetGlob(s) cfg.IgnoreVendor = g }, "modh1v") defer clean() c.Assert(client.Init(modPath), qt.IsNil) _, err := client.Collect() c.Assert(err, qt.IsNil) c.Assert(client.Vendor(), qt.IsNil) var graphb bytes.Buffer c.Assert(client.Graph(&graphb), qt.IsNil) c.Assert(graphb.String(), qt.Contains, "github.com/gohugoio/hugoTestModules1_darwin/modh1_1v@v1.3.0 github.com/gohugoio/hugoTestModules1_darwin/modh1_1_1v@v1.1.0+vendor") }) // https://github.com/gohugoio/hugo/issues/7908 c.Run("createThemeDirname", func(c *qt.C) { mcfg := DefaultModuleConfig client, clean := newClient( c, func(cfg *ClientConfig) { cfg.ModuleConfig = mcfg }, defaultImport) defer clean() dirname, err := client.createThemeDirname("foo", false) c.Assert(err, qt.IsNil) c.Assert(dirname, qt.Equals, filepath.Join(client.ccfg.ThemesDir, "foo")) dirname, err = client.createThemeDirname("../../foo", true) c.Assert(err, qt.IsNil) c.Assert(dirname, qt.Equals, filepath.Join(client.ccfg.ThemesDir, "../../foo")) _, err = client.createThemeDirname("../../foo", false) c.Assert(err, qt.Not(qt.IsNil)) absDir := filepath.Join(client.ccfg.WorkingDir, "..", "..") dirname, err = client.createThemeDirname(absDir, true) c.Assert(err, qt.IsNil) c.Assert(dirname, qt.Equals, absDir) dirname, err = client.createThemeDirname(absDir, false) fmt.Println(dirname) c.Assert(err, qt.Not(qt.IsNil)) }) } var globAll, _ = hglob.GetGlob("**") func TestGetModlineSplitter(t *testing.T) { c := qt.New(t) gomodSplitter := getModlineSplitter(true) c.Assert(gomodSplitter("\tgithub.com/BurntSushi/toml v0.3.1"), qt.DeepEquals, []string{"github.com/BurntSushi/toml", "v0.3.1"}) c.Assert(gomodSplitter("\tgithub.com/cpuguy83/go-md2man v1.0.8 // indirect"), qt.DeepEquals, []string{"github.com/cpuguy83/go-md2man", "v1.0.8"}) c.Assert(gomodSplitter("require ("), qt.IsNil) gosumSplitter := getModlineSplitter(false) c.Assert(gosumSplitter("github.com/BurntSushi/toml v0.3.1"), qt.DeepEquals, []string{"github.com/BurntSushi/toml", "v0.3.1"}) } func TestClientConfigToEnv(t *testing.T) { c := qt.New(t) ccfg := ClientConfig{ WorkingDir: "/mywork", CacheDir: "/mycache", } env := ccfg.toEnv() c.Assert(env, qt.DeepEquals, []string{"PWD=/mywork", "GO111MODULE=on", "GOFLAGS=-modcacherw", "GOPATH=/mycache", "GOWORK=", filepath.FromSlash("GOCACHE=/mycache/pkg/mod")}) ccfg = ClientConfig{ WorkingDir: "/mywork", CacheDir: "/mycache", ModuleConfig: Config{ Proxy: "https://proxy.example.org", Private: "myprivate", NoProxy: "mynoproxy", Workspace: "myworkspace", Auth: "myauth", }, } env = ccfg.toEnv() c.Assert(env, qt.DeepEquals, []string{ "PWD=/mywork", "GO111MODULE=on", "GOFLAGS=-modcacherw", "GOPATH=/mycache", "GOWORK=myworkspace", filepath.FromSlash("GOCACHE=/mycache/pkg/mod"), "GOPROXY=https://proxy.example.org", "GOPRIVATE=myprivate", "GONOPROXY=mynoproxy", "GOAUTH=myauth", }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/config_test.go
modules/config_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package modules import ( "fmt" "os" "path/filepath" "testing" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/version" "github.com/gohugoio/hugo/config" qt "github.com/frankban/quicktest" ) func TestConfigHugoVersionIsValid(t *testing.T) { c := qt.New(t) for _, test := range []struct { in HugoVersion expect bool }{ {HugoVersion{Min: "0.33.0"}, true}, {HugoVersion{Min: "0.56.0-DEV"}, true}, {HugoVersion{Min: "0.33.0", Max: "0.55.0"}, false}, {HugoVersion{Min: "0.33.0", Max: "0.199.0"}, true}, } { c.Assert(test.in.IsValid(), qt.Equals, test.expect, qt.Commentf("%#v", test.in)) } } func TestDecodeConfig(t *testing.T) { c := qt.New(t) c.Run("Basic", func(c *qt.C) { tempDir := c.TempDir() tomlConfig := ` workingDir = %q [module] workspace = "hugo.work" [module.hugoVersion] min = "0.54.2" max = "0.199.0" extended = true [[module.mounts]] source="src/project/blog" target="content/blog" lang="en" [[module.imports]] path="github.com/bep/mycomponent" [[module.imports.mounts]] source="scss" target="assets/bootstrap/scss" [[module.imports.mounts]] source="src/markdown/blog" target="content/blog" lang="en" ` hugoWorkFilename := filepath.Join(tempDir, "hugo.work") f, _ := os.Create(hugoWorkFilename) f.Close() cfg, err := config.FromConfigString(fmt.Sprintf(tomlConfig, tempDir), "toml") c.Assert(err, qt.IsNil) mcfg, err := DecodeConfig(loggers.NewDefault().Logger(), cfg) c.Assert(err, qt.IsNil) v056 := version.VersionString("0.56.0") hv := mcfg.HugoVersion c.Assert(v056.Compare(hv.Min), qt.Equals, -1) c.Assert(v056.Compare(hv.Max), qt.Equals, 1) c.Assert(hv.Extended, qt.Equals, true) if hugo.IsExtended { c.Assert(hv.IsValid(), qt.Equals, true) } c.Assert(mcfg.Workspace, qt.Equals, hugoWorkFilename) c.Assert(len(mcfg.Mounts), qt.Equals, 1) c.Assert(len(mcfg.Imports), qt.Equals, 1) imp := mcfg.Imports[0] imp.Path = "github.com/bep/mycomponent" c.Assert(imp.Mounts[1].Source, qt.Equals, "src/markdown/blog") c.Assert(imp.Mounts[1].Target, qt.Equals, "content/blog") c.Assert(imp.Mounts[1].Lang, qt.Equals, "en") }) c.Run("Replacements", func(c *qt.C) { for _, tomlConfig := range []string{` [module] replacements="a->b,github.com/bep/mycomponent->c" [[module.imports]] path="github.com/bep/mycomponent" `, ` [module] replacements=["a->b","github.com/bep/mycomponent->c"] [[module.imports]] path="github.com/bep/mycomponent" `} { cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) mcfg, err := DecodeConfig(loggers.NewDefault().Logger(), cfg) c.Assert(err, qt.IsNil) c.Assert(mcfg.Replacements, qt.DeepEquals, []string{"a->b", "github.com/bep/mycomponent->c"}) c.Assert(mcfg.replacementsMap, qt.DeepEquals, map[string]string{ "a": "b", "github.com/bep/mycomponent": "c", }) c.Assert(mcfg.Imports[0].Path, qt.Equals, "c") } }) } func TestDecodeConfigBothOldAndNewProvided(t *testing.T) { c := qt.New(t) tomlConfig := ` theme = ["b", "c"] [module] [[module.imports]] path="a" ` cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) modCfg, err := DecodeConfig(loggers.NewDefault().Logger(), cfg) c.Assert(err, qt.IsNil) c.Assert(len(modCfg.Imports), qt.Equals, 3) c.Assert(modCfg.Imports[0].Path, qt.Equals, "a") } // Test old style theme import. func TestDecodeConfigTheme(t *testing.T) { c := qt.New(t) tomlConfig := ` theme = ["a", "b"] ` cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) mcfg, err := DecodeConfig(loggers.NewDefault().Logger(), cfg) c.Assert(err, qt.IsNil) c.Assert(len(mcfg.Imports), qt.Equals, 2) c.Assert(mcfg.Imports[0].Path, qt.Equals, "a") c.Assert(mcfg.Imports[1].Path, qt.Equals, "b") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/modules_integration_test.go
modules/modules_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 modules_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestModuleImportWithVersion(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" [[module.imports]] path = "github.com/bep/hugo-mod-misc/dummy-content" version = "v0.2.0" [[module.imports]] path = "github.com/bep/hugo-mod-misc/dummy-content" version = "v0.1.0" [[module.imports.mounts]] source = "content" target = "content/v1" -- layouts/all.html -- Title: {{ .Title }}|Summary: {{ .Summary }}| Deps: {{ range hugo.Deps}}{{ printf "%s@%s" .Path .Version }}|{{ end }}$ ` b := hugolib.Test(t, files, hugolib.TestOptWithOSFs()) b.AssertFileContent("public/index.html", "Deps: project@|github.com/bep/hugo-mod-misc/dummy-content@v0.2.0|github.com/bep/hugo-mod-misc/dummy-content@v0.1.0|$") b.AssertFileContent("public/blog/music/autumn-leaves/index.html", "Autumn Leaves is a popular jazz standard") // v0.2.0 b.AssertFileContent("public/v1/blog/music/autumn-leaves/index.html", "Lorem markdownum, placidi peremptis") // v0.1.0 }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/mount_filters_integration_test.go
modules/mount_filters_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 modules_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestModulesFiltersFiles(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [module] [[module.mounts]] source = "content" target = "content" files = ["! **b.md", "**.md"] # The order matters here. -- content/a.md -- +++ title = "A" +++ Content A -- content/b.md -- +++ title = "B" +++ Content B -- content/c.md -- +++ title = "C" +++ Content C -- layouts/all.html -- All. {{ .Title }}| ` b := hugolib.Test(t, files, hugolib.TestOptInfo()) b.AssertLogContains("! deprecated") b.AssertFileContent("public/a/index.html", "All. A|") b.AssertFileContent("public/c/index.html", "All. C|") b.AssertFileExists("public/b/index.html", false) } // File filter format <= 0.152.0. func TestModulesFiltersFilesLegacy(t *testing.T) { // This cannot be parallel. files := ` -- hugo.toml -- [module] [[module.mounts]] source = "content" target = "content" includefiles = ["**{a,c}.md"] #includes was evaluated before excludes <= 0.152.0 excludefiles = ["**b.md"] -- content/a.md -- +++ title = "A" +++ Content A -- content/b.md -- +++ title = "B" +++ Content B -- content/c.md -- +++ title = "C" +++ Content C -- layouts/all.html -- All. {{ .Title }}| ` b := hugolib.Test(t, files, hugolib.TestOptInfo()) b.AssertFileContent("public/a/index.html", "All. A|") b.AssertFileContent("public/c/index.html", "All. C|") b.AssertFileExists("public/b/index.html", false) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/module.go
modules/module.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 modules provides a client that can be used to manage Hugo Components, // what's referred to as Hugo Modules. Hugo Modules is built on top of Go Modules, // but also supports vendoring and components stored directly in the themes dir. package modules import ( "net/url" "time" "github.com/gohugoio/hugo/config" ) var _ Module = (*moduleAdapter)(nil) type Module interface { // Optional config read from the configFilename above. Cfg() config.Provider // The decoded module config and mounts. Config() Config // Optional configuration filenames (e.g. "/themes/mytheme/config.json"). // This will be added to the special configuration watch list when in // server mode. ConfigFilenames() []string // Directory holding files for this module. Dir() string // Returns whether this is a Go Module. IsGoMod() bool // Any directory remappings. Mounts() []Mount // In the dependency tree, this is the first module that defines this module // as a dependency. Owner() Module // Returns the path to this module. // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", // or the path below your /theme folder, e.g. "mytheme". Path() string // For direct dependencies, this will be Path + "@" + VersionQuery. // For managed dependencies, this will be the same as Path. PathVersionQuery(escapeQuery bool) string // Replaced by this module. Replace() Module // Returns whether Dir points below the _vendor dir. Vendor() bool // The module version. Version() string // The version query requested in the import. VersionQuery() string // The expected cryptographic hash of the module. Sum() string // Time version was created. Time() time.Time // Whether this module's dir is a watch candidate. Watch() bool } type Modules []Module type moduleAdapter struct { path string dir string version string versionQuery string vendor bool projectMod bool owner Module mounts []Mount configFilenames []string cfg config.Provider config Config // Set if a Go module. gomod *goModule } func (m *moduleAdapter) Cfg() config.Provider { return m.cfg } func (m *moduleAdapter) Config() Config { return m.config } func (m *moduleAdapter) ConfigFilenames() []string { return m.configFilenames } func (m *moduleAdapter) Dir() string { // This may point to the _vendor dir. if !m.IsGoMod() || m.dir != "" { return m.dir } return m.gomod.Dir } func (m *moduleAdapter) IsGoMod() bool { return m.gomod != nil } func (m *moduleAdapter) Mounts() []Mount { return m.mounts } func (m *moduleAdapter) Owner() Module { return m.owner } func (m *moduleAdapter) Path() string { if !m.IsGoMod() || m.path != "" { return m.path } return m.gomod.Path } func (m *moduleAdapter) PathVersionQuery(escapeQuery bool) string { // We added version as a config option in Hugo v0.150.0, so // to make this backward compatible, we only add the version // if it was explicitly requested. pathBase := m.Path() if m.versionQuery == "" || !m.IsGoMod() { return pathBase } q := m.versionQuery if escapeQuery { q = url.QueryEscape(q) } return pathBase + "@" + q } func (m *moduleAdapter) Replace() Module { if m.IsGoMod() && !m.Vendor() && m.gomod.Replace != nil { return &moduleAdapter{ gomod: m.gomod.Replace, owner: m.owner, } } return nil } func (m *moduleAdapter) Vendor() bool { return m.vendor } func (m *moduleAdapter) Version() string { if !m.IsGoMod() || m.version != "" { return m.version } return m.gomod.Version } func (m *moduleAdapter) VersionQuery() string { return m.versionQuery } func (m *moduleAdapter) Sum() string { if !m.IsGoMod() { return "" } return m.gomod.Sum } func (m *moduleAdapter) Time() time.Time { if !m.IsGoMod() || m.gomod.Time == nil { return time.Time{} } return *m.gomod.Time } func (m *moduleAdapter) Watch() bool { if m.Owner() == nil { // Main project return true } if !m.IsGoMod() { // Module inside /themes return true } if m.Replace() != nil { // Version is not set when replaced by a local folder. return m.Replace().Version() == "" } // Any module set up in a workspace file will have Indirect set to false. // That leaves modules inside the read-only module cache. return !m.gomod.Indirect }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/config_integration_test.go
modules/config_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 modules_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestMountsProjectDefaults(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [languages] [languages.en] weight = 1 [languages.sv] weight = 2 [module] [[module.mounts]] source = 'content' target = 'content' lang = 'en' -- content/p1.md -- ` b := hugolib.Test(t, files) b.Assert(len(b.H.Configs.Modules), qt.Equals, 1) projectMod := b.H.Configs.Modules[0] b.Assert(projectMod.Path(), qt.Equals, "project") mounts := projectMod.Mounts() b.Assert(len(mounts), qt.Equals, 7) contentMount := mounts[0] b.Assert(contentMount.Source, qt.Equals, "content") b.Assert(contentMount.Sites.Matrix.Languages, qt.DeepEquals, []string{"en"}) } func TestMountsLangIsDeprecated(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [module] [[module.mounts]] source = 'content' target = 'content' lang = 'en' -- layouts/all.html -- All. ` b := hugolib.Test(t, files, hugolib.TestOptInfo()) b.AssertLogContains("deprecated") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/collect.go
modules/collect.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 modules import ( "bufio" "errors" "fmt" "io/fs" "net/url" "os" "path/filepath" "regexp" "slices" "strings" "time" "github.com/bep/debounce" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/version" "golang.org/x/mod/module" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/config" "github.com/spf13/afero" ) var ErrNotExist = errors.New("module does not exist") const vendorModulesFilename = "modules.txt" func (h *Client) Collect() (ModulesConfig, error) { mc, coll := h.collect(true) if coll.err != nil { return mc, coll.err } if err := (&mc).setActiveMods(h.logger); err != nil { return mc, err } if h.ccfg.HookBeforeFinalize != nil { if err := h.ccfg.HookBeforeFinalize(&mc); err != nil { return mc, err } } if err := (&mc).finalize(); err != nil { return mc, err } return mc, nil } func (h *Client) collect(tidy bool) (ModulesConfig, *collector) { if h == nil { panic("nil client") } c := &collector{ Client: h, } c.collect() if c.err != nil { return ModulesConfig{}, c } // https://github.com/gohugoio/hugo/issues/6115 /*if !c.skipTidy && tidy { if err := h.tidy(c.modules, true); err != nil { c.err = err return ModulesConfig{}, c } }*/ var workspaceFilename string if h.ccfg.ModuleConfig.Workspace != WorkspaceDisabled { workspaceFilename = h.ccfg.ModuleConfig.Workspace } return ModulesConfig{ AllModules: c.modules, GoModulesFilename: c.GoModulesFilename, GoWorkspaceFilename: workspaceFilename, }, c } type ModulesConfig struct { // All active modules. AllModules Modules // Set if this is a Go modules enabled project. GoModulesFilename string // Set if a Go workspace file is configured. GoWorkspaceFilename string } func (m ModulesConfig) HasConfigFile() bool { for _, mod := range m.AllModules { if len(mod.ConfigFilenames()) > 0 { return true } } return false } func (m *ModulesConfig) setActiveMods(logger loggers.Logger) error { for _, mod := range m.AllModules { if !mod.Config().HugoVersion.IsValid() { logger.Warnf(`Module %q is not compatible with this Hugo version: %s; run "hugo mod graph" for more information.`, mod.Path(), mod.Config().HugoVersion) } } return nil } func (m *ModulesConfig) finalize() error { for _, mod := range m.AllModules { m := mod.(*moduleAdapter) m.mounts = filterDuplicateMounts(m.mounts) } return nil } // filterDuplicateMounts removes duplicate mounts while preserving order. // The input slice will not be modified. func filterDuplicateMounts(mounts []Mount) []Mount { var x []Mount for _, m1 := range mounts { var found bool if slices.ContainsFunc(x, m1.Equal) { found = true } if !found { x = append(x, m1) } } return x } type pathVersionKey struct { path string version string } type collected struct { // Pick the first and prevent circular loops. seenPaths map[string]*moduleAdapter // Maps module path to a _vendor dir. These values are fetched from // _vendor/modules.txt, and the first (top-most) will win. vendored map[string]vendoredModule // Set if a Go modules enabled project. gomods goModules // Ordered list of collected modules, including Go Modules and theme // components stored below /themes. modules Modules } // Collects and creates a module tree. type collector struct { *Client // Store away any non-fatal error and return at the end. err error // Set to disable any Tidy operation in the end. skipTidy bool *collected } func (c *collector) initModules() error { c.collected = &collected{ seenPaths: make(map[string]*moduleAdapter), vendored: make(map[string]vendoredModule), gomods: goModules{}, } // If both these are true, we don't even need Go installed to build. if c.ccfg.IgnoreVendor == nil && c.isVendored(c.ccfg.WorkingDir) { return nil } // We may fail later if we don't find the mods. return c.loadModules() } func (c *collector) isPathSeen(p string, owner *moduleAdapter) *moduleAdapter { // Remove any major version suffix. // We do allow multiple major versions in the same project, // but not as transitive dependencies. p = pathBase(p) if v, ok := c.seenPaths[p]; ok { return v } c.seenPaths[p] = owner return nil } func (c *collector) getVendoredDir(path string) (vendoredModule, bool) { v, found := c.vendored[path] return v, found } func (c *collector) getAndCreateModule(owner *moduleAdapter, moduleImport Import) (*moduleAdapter, error) { var ( mod *goModule moduleDir string versionMod string requestedVersionQuery string = moduleImport.Version vendored bool ) modulePath := moduleImport.Path vendorPath := modulePath vendorPathEscaped := modulePath if requestedVersionQuery != "" { vendorPath += "@" + requestedVersionQuery vendorPathEscaped += "@" + url.QueryEscape(requestedVersionQuery) } var realOwner Module = owner if !(c.ccfg.shouldIgnoreVendor(vendorPath)) { if err := c.collectModulesTXT(owner); err != nil { return nil, err } // Try _vendor first. var vm vendoredModule vm, vendored = c.getVendoredDir(vendorPathEscaped) if vendored { moduleDir = vm.Dir realOwner = vm.Owner versionMod = vm.Version if owner.projectMod { // We want to keep the go.mod intact with the versions and all. c.skipTidy = true } } } if moduleDir == "" { if requestedVersionQuery == "" { mod = c.gomods.GetByPath(modulePath) if mod != nil { moduleDir = mod.Dir } } if moduleDir == "" { if isProbablyModule(modulePath) { if requestedVersionQuery != "" { var err error mod, err = c.downloadModuleVersion(modulePath, requestedVersionQuery) if err != nil { return nil, err } if mod == nil { return nil, fmt.Errorf("module %q not found", modulePath) } moduleDir = mod.Dir versionMod = mod.Version } else if c.GoModulesFilename != "" { // See https://golang.org/ref/mod#version-queries // This will select the latest release-version (not beta etc.). const versionQuery = "upgrade" // Try to "go get" it and reload the module configuration. // Note that we cannot use c.Get for this, as that may // trigger a new module collection and potentially create a infinite loop. if err := c.get(fmt.Sprintf("%s@%s", modulePath, versionQuery)); err != nil { return nil, err } if err := c.loadModules(); err != nil { return nil, err } mod = c.gomods.GetByPath(modulePath) if mod != nil { moduleDir = mod.Dir } } } // Fall back to project/themes/<mymodule> if moduleDir == "" { var err error moduleDir, err = c.createThemeDirname(modulePath, owner.projectMod || moduleImport.pathProjectReplaced) if err != nil { c.err = err return nil, nil } if found, _ := afero.Exists(c.fs, moduleDir); !found { //lint:ignore ST1005 end user message. c.err = c.wrapModuleNotFound(fmt.Errorf(`module %q not found in %q; either add it as a Hugo Module or store it in %q.`, modulePath, moduleDir, c.ccfg.ThemesDir)) return nil, nil } } } } if found, _ := afero.Exists(c.fs, moduleDir); !found { c.err = c.wrapModuleNotFound(fmt.Errorf("%q not found", moduleDir)) return nil, nil } if !strings.HasSuffix(moduleDir, fileSeparator) { moduleDir += fileSeparator } ma := &moduleAdapter{ dir: moduleDir, vendor: vendored, gomod: mod, version: versionMod, versionQuery: requestedVersionQuery, // This may be the owner of the _vendor dir owner: realOwner, } if mod == nil { ma.path = modulePath } if !moduleImport.IgnoreConfig { if err := c.applyThemeConfig(ma); err != nil { return nil, err } } if err := c.applyMounts(moduleImport, ma); err != nil { return nil, err } return ma, nil } func (c *collector) addAndRecurse(owner *moduleAdapter) error { moduleConfig := owner.Config() if owner.projectMod { if err := c.applyMounts(Import{}, owner); err != nil { return fmt.Errorf("failed to apply mounts for project: %w", err) } } seen := make(map[pathVersionKey]bool) for _, moduleImport := range moduleConfig.Imports { if moduleImport.Disable { continue } // Prevent cyclic references. if v := c.isPathSeen(moduleImport.Path, owner); v != nil && v != owner { continue } tc, err := c.getAndCreateModule(owner, moduleImport) if err != nil { return err } if tc == nil { continue } pk := pathVersionKey{path: tc.Path(), version: tc.Version()} seenInCurrent := seen[pk] if seenInCurrent { // Only one import of the same module per project. if owner.projectMod { // In Hugo v0.150.0 we introduced direct dependencies, and it may be tempting to import the same version // with different mount setups. We may allow that in the future, but we need to get some experience first. // For now, we just warn. The user needs to add multiple mount points in the same import. c.logger.Warnf("module with path %q is imported for the same version %q more than once", tc.Path(), tc.Version()) } continue } seen[pk] = true c.modules = append(c.modules, tc) if moduleImport.IgnoreImports { continue } if err := c.addAndRecurse(tc); err != nil { return err } } return nil } func (c *collector) applyMounts(moduleImport Import, mod *moduleAdapter) error { if moduleImport.NoMounts { mod.mounts = nil return nil } mounts := moduleImport.Mounts modConfig := mod.Config() if len(mounts) == 0 { // Mounts not defined by the import. mounts = modConfig.Mounts } if !mod.projectMod && len(mounts) == 0 { // Create default mount points for every component folder that // exists in the module. for _, componentFolder := range files.ComponentFolders { sourceDir := filepath.Join(mod.Dir(), componentFolder) _, err := c.fs.Stat(sourceDir) if err == nil { mounts = append(mounts, Mount{ Source: componentFolder, Target: componentFolder, }) } } } var err error mounts, err = c.normalizeMounts(mod, mounts) if err != nil { return err } mounts, err = c.mountCommonJSConfig(mod, mounts) if err != nil { return err } mod.mounts = mounts return nil } func (c *collector) applyThemeConfig(tc *moduleAdapter) error { var ( configFilename string themeCfg map[string]any hasConfigFile bool err error ) LOOP: for _, configBaseName := range config.DefaultConfigNames { for _, configFormats := range config.ValidConfigFileExtensions { configFilename = filepath.Join(tc.Dir(), configBaseName+"."+configFormats) hasConfigFile, _ = afero.Exists(c.fs, configFilename) if hasConfigFile { break LOOP } } } // The old theme information file. themeTOML := filepath.Join(tc.Dir(), "theme.toml") hasThemeTOML, _ := afero.Exists(c.fs, themeTOML) if hasThemeTOML { data, err := afero.ReadFile(c.fs, themeTOML) if err != nil { return err } themeCfg, err = metadecoders.Default.UnmarshalToMap(data, metadecoders.TOML) if err != nil { c.logger.Warnf("Failed to read module config for %q in %q: %s", tc.Path(), themeTOML, err) } else { maps.PrepareParams(themeCfg) } } if hasConfigFile { if configFilename != "" { var err error tc.cfg, err = config.FromFile(c.fs, configFilename) if err != nil { return err } } tc.configFilenames = append(tc.configFilenames, configFilename) } // Also check for a config dir, which we overlay on top of the file configuration. configDir := filepath.Join(tc.Dir(), "config") dcfg, dirnames, err := config.LoadConfigFromDir(c.fs, configDir, c.ccfg.Environment) if err != nil { return err } if len(dirnames) > 0 { tc.configFilenames = append(tc.configFilenames, dirnames...) if hasConfigFile { // Set will overwrite existing keys. tc.cfg.Set("", dcfg.Get("")) } else { tc.cfg = dcfg } } config, err := decodeConfig(c.logger.Logger(), tc.cfg, c.moduleConfig.replacementsMap) if err != nil { return err } const oldVersionKey = "min_version" if hasThemeTOML { // Merge old with new if minVersion, found := themeCfg[oldVersionKey]; found { if config.HugoVersion.Min == "" { config.HugoVersion.Min = version.VersionString(cast.ToString(minVersion)) } } if config.Params == nil { config.Params = make(map[string]any) } for k, v := range themeCfg { if k == oldVersionKey { continue } config.Params[k] = v } } tc.config = config return nil } func (c *collector) collect() { defer c.logger.PrintTimerIfDelayed(time.Now(), "hugo: collected modules") d := debounce.New(2 * time.Second) d(func() { c.logger.Println("hugo: downloading modules …") }) defer d(func() {}) if err := c.initModules(); err != nil { c.err = err return } projectMod := createProjectModule(c.gomods.GetMain(), c.ccfg.WorkingDir, c.moduleConfig) if err := c.addAndRecurse(projectMod); err != nil { c.err = err return } // Add the project mod on top. c.modules = append(Modules{projectMod}, c.modules...) if err := c.writeHugoDirectSum(c.modules); err != nil { c.err = err return } } func (c *collector) isVendored(dir string) bool { _, err := c.fs.Stat(filepath.Join(dir, vendord, vendorModulesFilename)) return err == nil } func (c *collector) collectModulesTXT(owner Module) error { vendorDir := filepath.Join(owner.Dir(), vendord) filename := filepath.Join(vendorDir, vendorModulesFilename) f, err := c.fs.Open(filename) if err != nil { if herrors.IsNotExist(err) { return nil } return err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { // # github.com/alecthomas/chroma v0.6.3 line := scanner.Text() line = strings.Trim(line, "# ") line = strings.TrimSpace(line) if line == "" { continue } parts := strings.Fields(line) if len(parts) != 2 { return fmt.Errorf("invalid modules list: %q", filename) } path := parts[0] shouldAdd := c.Client.moduleConfig.VendorClosest if !shouldAdd { if _, found := c.vendored[path]; !found { shouldAdd = true } } if shouldAdd { c.vendored[path] = vendoredModule{ Owner: owner, Dir: filepath.Join(vendorDir, path), Version: parts[1], } } } return nil } func (c *collector) loadModules() error { modules, err := c.listGoMods() if err != nil { return err } c.gomods = modules return nil } // Matches postcss.config.js etc. var commonJSConfigs = regexp.MustCompile(`(babel|postcss|tailwind)\.config\.js`) func (c *collector) mountCommonJSConfig(owner *moduleAdapter, mounts []Mount) ([]Mount, error) { for _, m := range mounts { if strings.HasPrefix(m.Target, files.JsConfigFolderMountPrefix) { // This follows the convention of the other component types (assets, content, etc.), // if one or more is specified by the user, we skip the defaults. // These mounts were added to Hugo in 0.75. return mounts, nil } } // Mount the common JS config files. d, err := c.fs.Open(owner.Dir()) if err != nil { return mounts, fmt.Errorf("failed to open dir %q: %q", owner.Dir(), err) } defer d.Close() fis, err := d.(fs.ReadDirFile).ReadDir(-1) if err != nil { return mounts, fmt.Errorf("failed to read dir %q: %q", owner.Dir(), err) } for _, fi := range fis { n := fi.Name() should := n == files.FilenamePackageHugoJSON || n == files.FilenamePackageJSON should = should || commonJSConfigs.MatchString(n) if should { mounts = append(mounts, Mount{ Source: n, Target: filepath.Join(files.ComponentFolderAssets, files.FolderJSConfig, n), }) } } return mounts, nil } func (c *collector) nodeModulesRoot(s string) string { s = filepath.ToSlash(s) if strings.HasPrefix(s, "node_modules/") { return s } if strings.HasPrefix(s, "../../node_modules/") { // See #14083. This was a common construct to mount node_modules from the project root. // This started failing in v0.152.0 when we tightened the validation. return strings.TrimPrefix(s, "../../") } return "" } func (c *collector) normalizeMounts(owner *moduleAdapter, mounts []Mount) ([]Mount, error) { var out []Mount dir := owner.Dir() for _, mnt := range mounts { errMsg := fmt.Sprintf("invalid module config for %q", owner.Path()) if mnt.Source == "" || mnt.Target == "" { return nil, errors.New(errMsg + ": both source and target must be set") } // Special case for node_modules imports in themes/modules. // See #14089. var isModuleNodeModulesImport bool if !owner.projectMod { nodeModulesImportSource := c.nodeModulesRoot(mnt.Source) if nodeModulesImportSource != "" { isModuleNodeModulesImport = true mnt.Source = nodeModulesImportSource } } mnt.Source = filepath.Clean(mnt.Source) mnt.Target = filepath.Clean(mnt.Target) var sourceDir string if !owner.projectMod && !filepath.IsLocal(mnt.Source) { return nil, fmt.Errorf("%s: %q: mount source must be a local path for modules/themes", errMsg, mnt.Source) } if filepath.IsAbs(mnt.Source) { // Abs paths in the main project is allowed. sourceDir = mnt.Source } else { sourceDir = filepath.Join(dir, mnt.Source) } // Verify that Source exists _, err := c.fs.Stat(sourceDir) if err != nil { if paths.IsSameFilePath(sourceDir, c.ccfg.PublishDir) { // This is a little exotic, but there are use cases for mounting the public folder. // This will typically also be in .gitingore, so create it. if err := c.fs.MkdirAll(sourceDir, 0o755); err != nil { return nil, fmt.Errorf("%s: %q", errMsg, err) } } else if strings.HasSuffix(sourceDir, files.FilenameHugoStatsJSON) { // A common pattern for Tailwind 3 is to mount that file to get it on the server watch list. // A common pattern is also to add hugo_stats.json to .gitignore. // Create an empty file. f, err := c.fs.Create(sourceDir) if err != nil { return nil, fmt.Errorf("%s: %q", errMsg, err) } f.Close() } else { if isModuleNodeModulesImport { // A module imported a path inside node_modules, but it didn't exist. // Make this a special case and also try relative to the project root. sourceDir = filepath.Join(c.ccfg.WorkingDir, mnt.Source) _, err := c.fs.Stat(sourceDir) if err != nil { continue } mnt.Source = sourceDir } else { continue } } } // Verify that target points to one of the predefined component dirs targetBase := mnt.Target idxPathSep := strings.Index(mnt.Target, string(os.PathSeparator)) if idxPathSep != -1 { targetBase = mnt.Target[0:idxPathSep] } if !files.IsComponentFolder(targetBase) { return nil, fmt.Errorf("%s: mount target must be one of: %v", errMsg, files.ComponentFolders) } if err := mnt.init(c.logger.Logger()); err != nil { return nil, fmt.Errorf("%s: %w", errMsg, err) } out = append(out, mnt) } return out, nil } func (c *collector) wrapModuleNotFound(err error) error { if c.Client.ccfg.IgnoreModuleDoesNotExist { return nil } err = fmt.Errorf(err.Error()+": %w", ErrNotExist) if c.GoModulesFilename == "" { return err } baseMsg := "we found a go.mod file in your project, but" switch c.goBinaryStatus { case goBinaryStatusNotFound: return fmt.Errorf(baseMsg+" you need to install Go to use it. See https://golang.org/dl/ : %q", err) case goBinaryStatusTooOld: return fmt.Errorf(baseMsg+" you need to a newer version of Go to use it. See https://golang.org/dl/ : %w", err) } return err } type vendoredModule struct { Owner Module Dir string Version string } func createProjectModule(gomod *goModule, workingDir string, conf Config) *moduleAdapter { // Create a pseudo module for the main project. var path string if gomod == nil { path = "project" } return &moduleAdapter{ path: path, dir: workingDir, gomod: gomod, projectMod: true, config: conf, } } func pathBase(p string) string { prefix, _, _ := module.SplitPathVersion(p) return strings.ToLower(prefix) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/npm/package_builder_test.go
modules/npm/package_builder_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 npm import ( "strings" "testing" qt "github.com/frankban/quicktest" ) const templ = `{ "name": "foo", "version": "0.1.1", "scripts": {}, "dependencies": { "react-dom": "1.1.1", "tailwindcss": "1.2.0", "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5" }, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0", "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5" } }` func TestPackageBuilder(t *testing.T) { c := qt.New(t) b := newPackageBuilder("", strings.NewReader(templ)) c.Assert(b.Err(), qt.IsNil) b.Add("mymod", strings.NewReader(`{ "dependencies": { "react-dom": "9.1.1", "add1": "1.1.1" }, "devDependencies": { "tailwindcss": "error", "add2": "2.1.1" } }`)) b.Add("mymod", strings.NewReader(`{ "dependencies": { "react-dom": "error", "add1": "error", "add3": "3.1.1" }, "devDependencies": { "tailwindcss": "error", "add2": "error", "add4": "4.1.1" } }`)) c.Assert(b.Err(), qt.IsNil) c.Assert(b.dependencies, qt.DeepEquals, map[string]any{ "@babel/cli": "7.8.4", "add1": "1.1.1", "add3": "3.1.1", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "react-dom": "1.1.1", "tailwindcss": "1.2.0", }) c.Assert(b.devDependencies, qt.DeepEquals, map[string]any{ "tailwindcss": "1.2.0", "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "add2": "2.1.1", "add4": "4.1.1", "@babel/preset-env": "7.9.5", "postcss-cli": "7.1.0", }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/modules/npm/package_builder.go
modules/npm/package_builder.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 npm import ( "bytes" "encoding/json" "fmt" "io" "io/fs" "strings" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugofs" "github.com/spf13/afero" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) const ( dependenciesKey = "dependencies" devDependenciesKey = "devDependencies" packageJSONName = "package.json" packageJSONTemplate = `{ "name": "%s", "version": "%s" }` ) func Pack(sourceFs, assetsWithDuplicatesPreservedFs afero.Fs) error { var b *packageBuilder // Have a package.hugo.json? fi, err := sourceFs.Stat(files.FilenamePackageHugoJSON) if err != nil { // Have a package.json? fi, err = sourceFs.Stat(packageJSONName) if err == nil { // Preserve the original in package.hugo.json. if err = hugio.CopyFile(sourceFs, packageJSONName, files.FilenamePackageHugoJSON); err != nil { return fmt.Errorf("npm pack: failed to copy package file: %w", err) } } else { // Create one. name := "project" // Use the Hugo site's folder name as the default name. // The owner can change it later. rfi, err := sourceFs.Stat("") if err == nil { name = rfi.Name() } packageJSONContent := fmt.Sprintf(packageJSONTemplate, name, "0.1.0") if err = afero.WriteFile(sourceFs, files.FilenamePackageHugoJSON, []byte(packageJSONContent), 0o666); err != nil { return err } fi, err = sourceFs.Stat(files.FilenamePackageHugoJSON) if err != nil { return err } } } meta := fi.(hugofs.FileMetaInfo).Meta() masterFilename := meta.Filename f, err := meta.Open() if err != nil { return fmt.Errorf("npm pack: failed to open package file: %w", err) } b = newPackageBuilder(meta.Module, f) f.Close() d, err := assetsWithDuplicatesPreservedFs.Open(files.FolderJSConfig) if err != nil { return nil } fis, err := d.(fs.ReadDirFile).ReadDir(-1) if err != nil { return fmt.Errorf("npm pack: failed to read assets: %w", err) } for _, fi := range fis { if fi.IsDir() { continue } if fi.Name() != files.FilenamePackageHugoJSON { continue } meta := fi.(hugofs.FileMetaInfo).Meta() if meta.Filename == masterFilename { continue } f, err := meta.Open() if err != nil { return fmt.Errorf("npm pack: failed to open package file: %w", err) } b.Add(meta.Module, f) f.Close() } if b.Err() != nil { return fmt.Errorf("npm pack: failed to build: %w", b.Err()) } // Replace the dependencies in the original template with the merged set. b.originalPackageJSON[dependenciesKey] = b.dependencies b.originalPackageJSON[devDependenciesKey] = b.devDependencies var commentsm map[string]any comments, found := b.originalPackageJSON["comments"] if found { commentsm = maps.ToStringMap(comments) } else { commentsm = make(map[string]any) } commentsm[dependenciesKey] = b.dependenciesComments commentsm[devDependenciesKey] = b.devDependenciesComments b.originalPackageJSON["comments"] = commentsm // Write it out to the project package.json packageJSONData := new(bytes.Buffer) encoder := json.NewEncoder(packageJSONData) encoder.SetEscapeHTML(false) encoder.SetIndent("", strings.Repeat(" ", 2)) if err := encoder.Encode(b.originalPackageJSON); err != nil { return fmt.Errorf("npm pack: failed to marshal JSON: %w", err) } if err := afero.WriteFile(sourceFs, packageJSONName, packageJSONData.Bytes(), 0o666); err != nil { return fmt.Errorf("npm pack: failed to write package.json: %w", err) } return nil } func newPackageBuilder(source string, first io.Reader) *packageBuilder { b := &packageBuilder{ devDependencies: make(map[string]any), devDependenciesComments: make(map[string]any), dependencies: make(map[string]any), dependenciesComments: make(map[string]any), } m := b.unmarshal(first) if b.err != nil { return b } b.addm(source, m) b.originalPackageJSON = m return b } type packageBuilder struct { err error // The original package.hugo.json. originalPackageJSON map[string]any devDependencies map[string]any devDependenciesComments map[string]any dependencies map[string]any dependenciesComments map[string]any } func (b *packageBuilder) Add(source string, r io.Reader) *packageBuilder { if b.err != nil { return b } m := b.unmarshal(r) if b.err != nil { return b } b.addm(source, m) return b } func (b *packageBuilder) addm(source string, m map[string]any) { if source == "" { source = "project" } // The version selection is currently very simple. // We may consider minimal version selection or something // after testing this out. // // But for now, the first version string for a given dependency wins. // These packages will be added by order of import (project, module1, module2...), // so that should at least give the project control over the situation. if devDeps, found := m[devDependenciesKey]; found { mm := maps.ToStringMapString(devDeps) for k, v := range mm { if _, added := b.devDependencies[k]; !added { b.devDependencies[k] = v b.devDependenciesComments[k] = source } } } if deps, found := m[dependenciesKey]; found { mm := maps.ToStringMapString(deps) for k, v := range mm { if _, added := b.dependencies[k]; !added { b.dependencies[k] = v b.dependenciesComments[k] = source } } } } func (b *packageBuilder) unmarshal(r io.Reader) map[string]any { m := make(map[string]any) err := json.Unmarshal(helpers.ReaderToBytes(r), &m) if err != nil { b.err = err } return m } func (b *packageBuilder) Err() error { return b.err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/deps/deps.go
deps/deps.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 deps import ( "context" "fmt" "io" "os" "path/filepath" "sort" "strings" "sync" "sync/atomic" "github.com/bep/logg" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/allconfig" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/internal/js" "github.com/gohugoio/hugo/internal/warpc" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/tpl/tplimpl" "github.com/gohugoio/hugo/metrics" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/tpl" "github.com/spf13/afero" ) // Deps holds dependencies used by many. // There will be normally only one instance of deps in play // at a given time, i.e. one per Site built. type Deps struct { // The logger to use. Log loggers.Logger `json:"-"` ExecHelper *hexec.Exec // The file systems to use. Fs *hugofs.Fs `json:"-"` // The PathSpec to use *helpers.PathSpec `json:"-"` // The ContentSpec to use *helpers.ContentSpec `json:"-"` // The SourceSpec to use SourceSpec *source.SourceSpec `json:"-"` // The Resource Spec to use ResourceSpec *resources.Spec // The configuration to use Conf config.AllProvider `json:"-"` // The memory cache to use. MemCache *dynacache.Cache // The translation func to use Translate func(ctx context.Context, translationID string, templateData any) string `json:"-"` // The site building. Site page.Site TemplateStore *tplimpl.TemplateStore // Used in tests OverloadedTemplateFuncs map[string]any TranslationProvider ResourceProvider Metrics metrics.Provider // BuildStartListeners will be notified before a build starts. BuildStartListeners *Listeners[any] // BuildEndListeners will be notified after a build finishes. BuildEndListeners *Listeners[any] // OnChangeListeners will be notified when something changes. OnChangeListeners *Listeners[identity.Identity] // Resources that gets closed when the build is done or the server shuts down. BuildClosers *types.Closers // This is common/global for all sites. BuildState *BuildState // Misc counters. Counters *Counters // Holds RPC dispatchers for Katex etc. // TODO(bep) rethink this re. a plugin setup, but this will have to do for now. WasmDispatchers *warpc.Dispatchers // The JS batcher client. JSBatcherClient js.BatcherClient isClosed bool *globalErrHandler } func (d Deps) Clone(s page.Site, conf config.AllProvider) (*Deps, error) { d.Conf = conf d.Site = s d.ExecHelper = nil d.ContentSpec = nil if err := d.Init(); err != nil { return nil, err } return &d, nil } func (d *Deps) GetTemplateStore() *tplimpl.TemplateStore { return d.TemplateStore } func (d *Deps) Init() error { if d.Conf == nil { panic("conf is nil") } if d.Fs == nil { // For tests. d.Fs = hugofs.NewFrom(afero.NewMemMapFs(), d.Conf.BaseConfig()) } if d.Log == nil { d.Log = loggers.NewDefault() } if d.globalErrHandler == nil { d.globalErrHandler = &globalErrHandler{ logger: d.Log, } } if d.BuildState == nil { d.BuildState = &BuildState{} } if d.Counters == nil { d.Counters = &Counters{} } if d.BuildState.DeferredExecutions == nil { if d.BuildState.DeferredExecutionsGroupedByRenderingContext == nil { d.BuildState.DeferredExecutionsGroupedByRenderingContext = make(map[tpl.RenderingContext]*DeferredExecutions) } d.BuildState.DeferredExecutions = &DeferredExecutions{ Executions: maps.NewCache[string, *tpl.DeferredExecution](), FilenamesWithPostPrefix: maps.NewCache[string, bool](), } } if d.BuildStartListeners == nil { d.BuildStartListeners = &Listeners[any]{} } if d.BuildEndListeners == nil { d.BuildEndListeners = &Listeners[any]{} } if d.BuildClosers == nil { d.BuildClosers = &types.Closers{} } if d.OnChangeListeners == nil { d.OnChangeListeners = &Listeners[identity.Identity]{} } if d.Metrics == nil && d.Conf.TemplateMetrics() { d.Metrics = metrics.NewProvider(d.Conf.TemplateMetricsHints()) } if d.ExecHelper == nil { d.ExecHelper = hexec.New(d.Conf.GetConfigSection("security").(security.Config), d.Conf.WorkingDir(), d.Log) } if d.MemCache == nil { d.MemCache = dynacache.New(dynacache.Options{Watching: d.Conf.Watching(), Log: d.Log}) } if d.PathSpec == nil { hashBytesReceiverFunc := func(name string, match []byte) { s := string(match) switch s { case postpub.PostProcessPrefix: d.BuildState.AddFilenameWithPostPrefix(name) case tpl.HugoDeferredTemplatePrefix: d.BuildState.DeferredExecutions.FilenamesWithPostPrefix.Set(name, true) } } // Skip binary files. mediaTypes := d.Conf.GetConfigSection("mediaTypes").(media.Types) hashBytesShouldCheck := func(name string) bool { ext := strings.TrimPrefix(filepath.Ext(name), ".") return mediaTypes.IsTextSuffix(ext) } d.Fs.PublishDir = hugofs.NewHasBytesReceiver( d.Fs.PublishDir, hashBytesShouldCheck, hashBytesReceiverFunc, []byte(tpl.HugoDeferredTemplatePrefix), []byte(postpub.PostProcessPrefix)) pathSpec, err := helpers.NewPathSpec(d.Fs, d.Conf, d.Log, nil) if err != nil { return err } d.PathSpec = pathSpec } else { var err error d.PathSpec, err = helpers.NewPathSpec(d.Fs, d.Conf, d.Log, d.PathSpec.BaseFs) if err != nil { return err } } if d.ContentSpec == nil { contentSpec, err := helpers.NewContentSpec(d.Conf, d.Log, d.Content.Fs, d.ExecHelper) if err != nil { return err } d.ContentSpec = contentSpec } if d.SourceSpec == nil { d.SourceSpec = source.NewSourceSpec(d.PathSpec, nil, d.Fs.Source) } var common *resources.SpecCommon if d.ResourceSpec != nil { common = d.ResourceSpec.SpecCommon } fileCaches, err := filecache.NewCaches(d.PathSpec) if err != nil { return fmt.Errorf("failed to create file caches from configuration: %w", err) } resourceSpec, err := resources.NewSpec(d.PathSpec, common, d.WasmDispatchers, fileCaches, d.MemCache, d.BuildState, d.Log, d, d.ExecHelper, d.BuildClosers, d.BuildState) if err != nil { return fmt.Errorf("failed to create resource spec: %w", err) } d.ResourceSpec = resourceSpec return nil } // TODO(bep) rework this to get it in line with how we manage templates. func (d *Deps) Compile(prototype *Deps) error { var err error if prototype == nil { if err = d.TranslationProvider.NewResource(d); err != nil { return err } return nil } if err = d.TranslationProvider.CloneResource(d, prototype); err != nil { return err } return nil } // MkdirTemp returns a temporary directory path that will be cleaned up on exit. func (d Deps) MkdirTemp(pattern string) (string, error) { filename, err := os.MkdirTemp("", pattern) if err != nil { return "", err } d.BuildClosers.Add( types.CloserFunc( func() error { return os.RemoveAll(filename) }, ), ) return filename, nil } type globalErrHandler struct { logger loggers.Logger // Channel for some "hard to get to" build errors buildErrors chan error // Used to signal that the build is done. quit chan struct{} } // SendError sends the error on a channel to be handled later. // This can be used in situations where returning and aborting the current // operation isn't practical. func (e *globalErrHandler) SendError(err error) { if e.buildErrors != nil { select { case <-e.quit: case e.buildErrors <- err: default: } return } e.logger.Errorln(err) } func (e *globalErrHandler) StartErrorCollector() chan error { e.quit = make(chan struct{}) e.buildErrors = make(chan error, 10) return e.buildErrors } func (e *globalErrHandler) StopErrorCollector() { if e.buildErrors != nil { close(e.quit) close(e.buildErrors) } } // Listeners represents an event listener. type Listeners[T any] struct { sync.Mutex // A list of funcs to be notified about an event. // If the return value is true, the listener will be removed. listeners []func(...T) bool } // Add adds a function to a Listeners instance. func (b *Listeners[T]) Add(f func(...T) bool) { if b == nil { return } b.Lock() defer b.Unlock() b.listeners = append(b.listeners, f) } // Notify executes all listener functions. func (b *Listeners[T]) Notify(vs ...T) { b.Lock() defer b.Unlock() temp := b.listeners[:0] for _, notify := range b.listeners { if !notify(vs...) { temp = append(temp, notify) } } b.listeners = temp } // ResourceProvider is used to create and refresh, and clone resources needed. type ResourceProvider interface { NewResource(dst *Deps) error CloneResource(dst, src *Deps) error } func (d *Deps) Close() error { if d.isClosed { return nil } d.isClosed = true if d.MemCache != nil { d.MemCache.Stop() } if d.WasmDispatchers != nil { d.WasmDispatchers.Close() } return d.BuildClosers.Close() } // DepsCfg contains configuration options that can be used to configure Hugo // on a global level, i.e. logging etc. // Nil values will be given default values. type DepsCfg struct { // The logger to use. Only set in some tests. // TODO(bep) get rid of this. TestLogger loggers.Logger // The logging level to use. LogLevel logg.Level // Logging output. StdErr io.Writer // The console output. StdOut io.Writer // The file systems to use Fs *hugofs.Fs // The Site in use Site page.Site Configs *allconfig.Configs // Template handling. TemplateProvider ResourceProvider // i18n handling. TranslationProvider ResourceProvider // Build triggered by the IntegrationTest framework. IsIntegrationTest bool // ChangesFromBuild for changes passed back to the server/watch process. ChangesFromBuild chan []identity.Identity } // BuildState are state used during a build. type BuildState struct { counter uint64 mu sync.Mutex // protects state below. OnSignalRebuild func(ids ...identity.Identity) // A set of filenames in /public that // contains a post-processing prefix. filenamesWithPostPrefix map[string]bool DeferredExecutions *DeferredExecutions // Deferred executions grouped by rendering context. DeferredExecutionsGroupedByRenderingContext map[tpl.RenderingContext]*DeferredExecutions } // Misc counters. type Counters struct { // Counter for the math.Counter function. MathCounter atomic.Uint64 } type DeferredExecutions struct { // A set of filenames in /public that // contains a post-processing prefix. FilenamesWithPostPrefix *maps.Cache[string, bool] // Maps a placeholder to a deferred execution. Executions *maps.Cache[string, *tpl.DeferredExecution] } var _ identity.SignalRebuilder = (*BuildState)(nil) // StartStageRender will be called before a stage is rendered. func (b *BuildState) StartStageRender(stage tpl.RenderingContext) { } // StopStageRender will be called after a stage is rendered. func (b *BuildState) StopStageRender(stage tpl.RenderingContext) { b.DeferredExecutionsGroupedByRenderingContext[stage] = b.DeferredExecutions b.DeferredExecutions = &DeferredExecutions{ Executions: maps.NewCache[string, *tpl.DeferredExecution](), FilenamesWithPostPrefix: maps.NewCache[string, bool](), } } func (b *BuildState) SignalRebuild(ids ...identity.Identity) { b.OnSignalRebuild(ids...) } func (b *BuildState) AddFilenameWithPostPrefix(filename string) { b.mu.Lock() defer b.mu.Unlock() if b.filenamesWithPostPrefix == nil { b.filenamesWithPostPrefix = make(map[string]bool) } b.filenamesWithPostPrefix[filename] = true } func (b *BuildState) GetFilenamesWithPostPrefix() []string { b.mu.Lock() defer b.mu.Unlock() var filenames []string for filename := range b.filenamesWithPostPrefix { filenames = append(filenames, filename) } sort.Strings(filenames) return filenames } func (b *BuildState) Incr() int { return int(atomic.AddUint64(&b.counter, uint64(1))) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/deps/deps_test.go
deps/deps_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 deps_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/deps" ) func TestBuildFlags(t *testing.T) { c := qt.New(t) var bf deps.BuildState bf.Incr() bf.Incr() bf.Incr() c.Assert(bf.Incr(), qt.Equals, 4) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/content_render_hooks_test.go
hugolib/content_render_hooks_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 requiredF by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" ) func TestRenderHooksRSS(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org" disableKinds = ["taxonomy", "term"] -- layouts/home.html -- {{ $p := site.GetPage "p1.md" }} {{ $p2 := site.GetPage "p2.md" }} P1: {{ $p.Content }} P2: {{ $p2.Content }} -- layouts/index.xml -- {{ $p2 := site.GetPage "p2.md" }} {{ $p3 := site.GetPage "p3.md" }} P2: {{ $p2.Content }} P3: {{ $p3.Content }} -- layouts/_markup/render-link.html -- html-link: {{ .Destination | safeURL }}| -- layouts/_markup/render-link.rss.xml -- xml-link: {{ .Destination | safeURL }}| -- layouts/_markup/render-heading.html -- html-heading: {{ .Text }}| -- layouts/_markup/render-heading.rss.xml -- xml-heading: {{ .Text }}| -- content/p1.md -- --- title: "p1" --- P1. [I'm an inline-style link](https://www.gohugo.io) # Heading in p1 -- content/p2.md -- --- title: "p2" --- P2. [I'm an inline-style link](https://www.bep.is) # Heading in p2 -- content/p3.md -- --- title: "p3" outputs: ["rss"] --- P3. [I'm an inline-style link](https://www.example.org) ` b := Test(t, files) b.AssertFileContent("public/index.html", ` P1: <p>P1. html-link: https://www.gohugo.io|</p> html-heading: Heading in p1| html-heading: Heading in p2| `) b.AssertFileContent("public/index.xml", ` P2: <p>P2. xml-link: https://www.bep.is|</p> P3: <p>P3. xml-link: https://www.example.org|</p> xml-heading: Heading in p2| `) } // Issue 13242. func TestRenderHooksRSSOnly(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org" disableKinds = ["taxonomy", "term"] -- layouts/home.html -- {{ $p := site.GetPage "p1.md" }} {{ $p2 := site.GetPage "p2.md" }} P1: {{ $p.Content }} P2: {{ $p2.Content }} -- layouts/index.xml -- {{ $p2 := site.GetPage "p2.md" }} {{ $p3 := site.GetPage "p3.md" }} P2: {{ $p2.Content }} P3: {{ $p3.Content }} -- layouts/_markup/render-link.rss.xml -- xml-link: {{ .Destination | safeURL }}| -- layouts/_markup/render-heading.rss.xml -- xml-heading: {{ .Text }}| -- content/p1.md -- --- title: "p1" --- P1. [I'm an inline-style link](https://www.gohugo.io) # Heading in p1 -- content/p2.md -- --- title: "p2" --- P2. [I'm an inline-style link](https://www.bep.is) # Heading in p2 -- content/p3.md -- --- title: "p3" outputs: ["rss"] --- P3. [I'm an inline-style link](https://www.example.org) ` b := Test(t, files) b.AssertFileContent("public/index.html", ` P1: <p>P1. <a href="https://www.gohugo.io">I&rsquo;m an inline-style link</a></p> <h1 id="heading-in-p1">Heading in p1</h1> <h1 id="heading-in-p2">Heading in p2</h1> `) b.AssertFileContent("public/index.xml", ` P2: <p>P2. xml-link: https://www.bep.is|</p> P3: <p>P3. xml-link: https://www.example.org|</p> xml-heading: Heading in p2| `) } // https://github.com/gohugoio/hugo/issues/6629 func TestRenderLinkWithMarkupInText(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL="https://example.org" [markup] [markup.goldmark] [markup.goldmark.renderer] unsafe = true -- layouts/home.html -- {{ $p := site.GetPage "p1.md" }} P1: {{ $p.Content }} -- layouts/_markup/render-link.html -- html-link: {{ .Destination | safeURL }}|Text: {{ .Text }}|Plain: {{ .PlainText | safeHTML }} -- layouts/_markup/render-image.html -- html-image: {{ .Destination | safeURL }}|Text: {{ .Text }}|Plain: {{ .PlainText | safeHTML }} -- content/p1.md -- --- title: "p1" --- START: [**should be bold**](https://gohugo.io)END Some regular **markup**. Image: ![Hello<br> Goodbye](image.jpg)END ` b := Test(t, files) b.AssertFileContent("public/index.html", ` P1: <p>START: html-link: https://gohugo.io|Text: <strong>should be bold</strong>|Plain: should be boldEND</p> <p>Some regular <strong>markup</strong>.</p> <p>html-image: image.jpg|Text: Hello<br> Goodbye|Plain: Hello GoodbyeEND</p> `) } func TestRenderHookContentFragmentsOnSelf(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT"] -- content/p1.md -- --- title: "p1" --- ## A {#z} ## B ## C -- content/p2.md -- --- title: "p2" --- ## D ## E ## F -- layouts/_markup/render-heading.html -- Heading: {{ .Text }}| {{ with .Page }} Self Fragments: {{ .Fragments.Identifiers }}| {{ end }} {{ with (site.GetPage "p1.md") }} P1 Fragments: {{ .Fragments.Identifiers }}| {{ end }} -- layouts/single.html -- {{ .Content}} ` b := Test(t, files) b.AssertFileContent("public/p1/index.html", ` Self Fragments: [b c z] P1 Fragments: [b c z] `) b.AssertFileContent("public/p2/index.html", ` Self Fragments: [d e f] P1 Fragments: [b c z] `) } func TestDefaultRenderHooksMultilingual(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT"] defaultContentLanguage = "nn" defaultContentLanguageInSubdir = true [markup] [markup.goldmark] duplicateResourceFiles = false [markup.goldmark.renderhooks] [markup.goldmark.renderhooks.link] #enableDefault = false [markup.goldmark.renderhooks.image] #enableDefault = false [languages] [languages.en] weight = 1 [languages.nn] weight = 2 -- content/p1/index.md -- --- title: "p1" --- [P2](p2) ![Pixel](pixel.png) -- content/p2/index.md -- --- title: "p2" --- [P1](p1) ![Pixel](pixel.jpg) -- content/p1/index.en.md -- --- title: "p1 en" --- [P2](p2) ![Pixel](pixel.png) -- content/p2/index.en.md -- --- title: "p2 en" --- [P1](p1) ![Pixel](pixel.png) -- content/p1/pixel.nn.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- content/p2/pixel.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- layouts/single.html -- {{ .Title }}|{{ .Content }}|$ ` t.Run("Default multilingual", func(t *testing.T) { b := Test(t, files) b.AssertFileContent("public/nn/p1/index.html", "p1|<p><a href=\"/nn/p2/\">P2</a\n></p>", "<img src=\"/nn/p1/pixel.nn.png\" alt=\"Pixel\">") b.AssertFileContent("public/en/p1/index.html", "p1 en|<p><a href=\"/en/p2/\">P2</a\n></p>", "<img src=\"/nn/p1/pixel.nn.png\" alt=\"Pixel\">") }) t.Run("Disabled", func(t *testing.T) { b := Test(t, strings.ReplaceAll(files, "#enableDefault = false", "enableDefault = false")) b.AssertFileContent("public/nn/p1/index.html", "p1|<p><a href=\"p2\">P2</a>", "<img src=\"pixel.png\" alt=\"Pixel\">") }) } func TestRenderHooksDefaultEscape(t *testing.T) { files := ` -- hugo.toml -- [markup.goldmark.extensions.typographer] disable = true [markup.goldmark.renderHooks.image] enableDefault = ENABLE [markup.goldmark.renderHooks.link] enableDefault = ENABLE [markup.goldmark.parser] wrapStandAloneImageWithinParagraph = false [markup.goldmark.parser.attribute] block = true title = true -- content/_index.md -- --- title: "Home" --- Link: [text-"<>&](/destination-"<> 'title-"<>&') Image: ![alt-"<>&](/destination-"<> 'title-"<>&') {class="><script>alert()</script>" id="baz"} -- layouts/home.html -- {{ .Content }} ` for _, enabled := range []bool{true, false} { t.Run(fmt.Sprint(enabled), func(t *testing.T) { t.Parallel() b := Test(t, strings.ReplaceAll(files, "ENABLE", fmt.Sprint(enabled))) // The escaping is slightly different between the two. if enabled { b.AssertFileContent("public/index.html", "Link: <a href=\"/destination-%22%3C%3E\" title=\"title-&#34;&lt;&gt;&amp;\">text-&quot;&lt;&gt;&amp;</a>", "img src=\"/destination-%22%3C%3E\" alt=\"alt-&#34;&lt;&gt;&amp;\" title=\"title-&#34;&lt;&gt;&amp;\">", "&gt;&lt;script&gt;", ) } else { b.AssertFileContent("public/index.html", "Link: <a href=\"/destination-%22%3C%3E\" title=\"title-&quot;&lt;&gt;&amp;\">text-&quot;&lt;&gt;&amp;</a>", "Image: <img src=\"/destination-%22%3C%3E\" alt=\"alt-&quot;&lt;&gt;&amp;\" title=\"title-&quot;&lt;&gt;&amp;\">", ) } }) } } // Issue 13410. func TestRenderHooksMultilineTitlePlainText(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/p1.md -- --- title: "p1" --- First line. Second line. ---------------- -- layouts/_markup/render-heading.html -- Plain text: {{ .PlainText }}|Text: {{ .Text }}| -- layouts/single.html -- Content: {{ .Content}}| } ` b := Test(t, files) b.AssertFileContent("public/p1/index.html", "Content: Plain text: First line.\nSecond line.|", "|Text: First line.\nSecond line.||\n", ) } func TestContentOutputReuseRenderHooksAndShortcodesHTMLOnly(t *testing.T) { files := ` -- hugo.toml -- -- layouts/home.html -- HTML: {{ .Title }}|{{ .Content }}| -- layouts/index.xml -- XML: {{ .Title }}|{{ .Content }}| -- layouts/_markup/render-heading.html -- Render heading. -- layouts/_shortcodes/myshortcode.html -- My shortcode. -- content/_index.md -- --- title: "Home" --- ## Heading {{< myshortcode >}} ` b := Test(t, files) s := b.H.Sites[0] b.Assert(s.home.pageOutputTemplateVariationsState.Load(), qt.Equals, uint32(1)) b.AssertFileContent("public/index.html", "HTML: Home|Render heading.\nMy shortcode.\n|") b.AssertFileContent("public/index.xml", "XML: Home|Render heading.\nMy shortcode.\n|") } func TestContentOutputNoReuseRenderHooksInBothHTMLAnXML(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] -- layouts/home.html -- HTML: {{ .Title }}|{{ .Content }}| -- layouts/index.xml -- XML: {{ .Title }}|{{ .Content }}| -- layouts/_markup/render-heading.html -- Render heading. -- layouts/_markup/render-heading.xml -- Render heading XML. -- content/_index.md -- --- title: "Home" --- ## Heading ` b := Test(t, files) s := b.H.Sites[0] b.Assert(s.home.pageOutputTemplateVariationsState.Load() > 1, qt.IsTrue) b.AssertFileContentExact("public/index.xml", "XML: Home|Render heading XML.|") b.AssertFileContentExact("public/index.html", "HTML: Home|Render heading.|") } func TestContentOutputNoReuseShortcodesInBothHTMLAnXML(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] -- layouts/home.html -- HTML: {{ .Title }}|{{ .Content }}| -- layouts/index.xml -- XML: {{ .Title }}|{{ .Content }}| -- layouts/_markup/render-heading.html -- Render heading. -- layouts/_shortcodes/myshortcode.html -- My shortcode HTML. -- layouts/_shortcodes/myshortcode.xml -- My shortcode XML. -- content/_index.md -- --- title: "Home" --- ## Heading {{< myshortcode >}} ` b := Test(t, files) b.AssertFileContentExact("public/index.xml", "My shortcode XML.") b.AssertFileContentExact("public/index.html", "My shortcode HTML.") s := b.H.Sites[0] b.Assert(s.home.pageOutputTemplateVariationsState.Load() > 1, qt.IsTrue) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/language_test.go
hugolib/language_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 hugolib import ( "fmt" "testing" qt "github.com/frankban/quicktest" ) func TestI18n(t *testing.T) { c := qt.New(t) testCases := []struct { name string langCode string }{ { name: "pt-br lowercase", langCode: "pt-br", }, { name: "pt-br uppercase", langCode: "PT-BR", }, } for _, tc := range testCases { tc := tc c.Run(tc.name, func(c *qt.C) { files := fmt.Sprintf(` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "%s" [languages] [languages.%s] weight = 1 -- i18n/%s.toml -- hello.one = "Hello" -- layouts/home.html -- Hello: {{ i18n "hello" 1 }} -- content/p1.md -- `, tc.langCode, tc.langCode, tc.langCode) b := Test(c, files) b.AssertFileContent("public/index.html", "Hello: Hello") }) } } func TestLanguageBugs(t *testing.T) { c := qt.New(t) // Issue #8672 c.Run("Config with language, menu in root only", func(c *qt.C) { files := ` -- hugo.toml -- theme = "test-theme" [[menus.foo]] name = "foo-a" [languages.en] -- themes/test-theme/hugo.toml -- [languages.en] ` b := Test(c, files) menus := b.H.Sites[0].Menus() c.Assert(menus, qt.HasLen, 1) }) } func TestLanguageNumberFormatting(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org" defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] timeZone="UTC" weight=10 [languages.nn] weight=20 -- layouts/home.html -- FormatNumber: {{ 512.5032 | lang.FormatNumber 2 }} FormatPercent: {{ 512.5032 | lang.FormatPercent 2 }} FormatCurrency: {{ 512.5032 | lang.FormatCurrency 2 "USD" }} FormatAccounting: {{ 512.5032 | lang.FormatAccounting 2 "NOK" }} FormatNumberCustom: {{ lang.FormatNumberCustom 2 12345.6789 }} -- content/p1.md -- ` b := Test(t, files) b.AssertFileContent("public/en/index.html", ` FormatNumber: 512.50 FormatPercent: 512.50% FormatCurrency: $512.50 FormatAccounting: NOK512.50 FormatNumberCustom: 12,345.68 `, ) b.AssertFileContent("public/nn/index.html", ` FormatNumber: 512,50 FormatPercent: 512,50 % FormatCurrency: 512,50 USD FormatAccounting: 512,50 kr FormatNumberCustom: 12,345.68 `) } // Issue 11993. func TestI18nDotFile(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" -- i18n/.keep -- -- data/.keep -- ` Test(t, files) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/hugo_sites.go
hugolib/hugo_sites.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 hugolib import ( "context" "errors" "fmt" "io" "iter" "strings" "sync" "sync/atomic" "time" "github.com/bep/logg" "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/config/allconfig" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/hugolib/doctree" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/resources" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/common/hsync" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/para" "github.com/gohugoio/hugo/common/terminal" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/page" ) // HugoSites represents the sites to build. Each site represents a language. type HugoSites struct { // The current sites slice. // When rendering, this slice will be shifted out. Sites []*Site // All sites for all versions and roles. sitesVersionsRoles [][][]*Site sitesVersionsRolesMap map[sitesmatrix.Vector]*Site sitesLanguages []*Site // sample set with all languages. Configs *allconfig.Configs hugoInfo hugo.HugoInfo // Render output formats for all sites. renderFormats output.Formats // The currently rendered Site. currentSite *Site *deps.Deps gitInfo *gitInfo codeownerInfo *codeownerInfo // As loaded from the /data dirs data map[string]any // Cache for page listings. cachePages *dynacache.Partition[string, page.Pages] // Cache for content sources. cacheContentSource *dynacache.Partition[uint64, *resources.StaleValue[[]byte]] // Before Hugo 0.122.0 we managed all translations in a map using a translationKey // that could be overridden in front matter. // Now the different page dimensions (e.g. language) are built-in to the page trees above. // But we sill need to support the overridden translationKey, but that should // be relatively rare and low volume. translationKeyPages *maps.SliceCache[page.Page] pageTrees *pageTrees previousPageTreesWalkContext *doctree.WalkContext[contentNode] // Set for rebuilds only. previousSeenTerms *maps.Map[term, sitesmatrix.Vectors] // Set for rebuilds only. printUnusedTemplatesInit sync.Once printPathWarningsInit sync.Once // File change events with filename stored in this map will be skipped. skipRebuildForFilenamesMu sync.Mutex skipRebuildForFilenames map[string]bool init *hugoSitesInit workersSite *para.Workers numWorkersSites int numWorkers int *progressReporter *fatalErrorHandler *buildCounters // Tracks invocations of the Build method. buildCounter atomic.Uint64 } type progressReporter struct { mu sync.Mutex t time.Time progress float64 queue []func() (state terminal.ProgressState, progress float64) state terminal.ProgressState renderProgressStart float64 numPagesToRender atomic.Uint64 } func (p *progressReporter) Start() { p.mu.Lock() defer p.mu.Unlock() p.t = htime.Now() } func (h *HugoSites) allSites(include func(s *Site) bool) iter.Seq[*Site] { return func(yield func(s *Site) bool) { for _, v := range h.sitesVersionsRoles { for _, r := range v { for _, s := range r { if include != nil && !include(s) { continue } if !yield(s) { return } } } } } } // allSiteLanguages will range over the first site in each language that's not skipped. func (h *HugoSites) allSiteLanguages(include func(s *Site) bool) iter.Seq[*Site] { return func(yield func(s *Site) bool) { LOOP: for _, v := range h.sitesVersionsRoles { for _, r := range v { for _, s := range r { if include != nil && !include(s) { continue LOOP } if !yield(r[0]) { return } continue LOOP } } } } } func (h *HugoSites) getFirstTaxonomyConfig(s string) (v viewName) { for _, ss := range h.sitesLanguages { if v = ss.pageMap.cfg.getTaxonomyConfig(s); !v.IsZero() { return } } return } // returns one of the sites with the language of the given vector. func (h *HugoSites) languageSiteForSiteVector(v sitesmatrix.Vector) *Site { return h.sitesLanguages[v.Language()] } // ShouldSkipFileChangeEvent allows skipping filesystem event early before // the build is started. func (h *HugoSites) ShouldSkipFileChangeEvent(ev fsnotify.Event) bool { h.skipRebuildForFilenamesMu.Lock() defer h.skipRebuildForFilenamesMu.Unlock() return h.skipRebuildForFilenames[ev.Name] } func (h *HugoSites) Close() error { return h.Deps.Close() } func (h *HugoSites) isRebuild() bool { return h.buildCounter.Load() > 0 } func (h *HugoSites) resolveFirstSite(matrix sitesmatrix.VectorStore) *Site { var s *Site var ok bool matrix.ForEachVector(func(v sitesmatrix.Vector) bool { if s, ok = h.sitesVersionsRolesMap[v]; ok { return false } return true }) if s == nil { panic(fmt.Sprintf("no site found for matrix %s", matrix)) } return s } type buildCounters struct { contentRenderCounter atomic.Uint64 pageRenderCounter atomic.Uint64 } func (c *buildCounters) loggFields() logg.Fields { return logg.Fields{ {Name: "pages", Value: c.pageRenderCounter.Load()}, {Name: "content", Value: c.contentRenderCounter.Load()}, } } type fatalErrorHandler struct { mu sync.Mutex h *HugoSites err error done bool donec chan bool // will be closed when done } // FatalError error is used in some rare situations where it does not make sense to // continue processing, to abort as soon as possible and log the error. func (f *fatalErrorHandler) FatalError(err error) { f.mu.Lock() defer f.mu.Unlock() if !f.done { f.done = true close(f.donec) } f.err = err } // Stop stops the fatal error handler without setting an error. func (f *fatalErrorHandler) Stop() { f.mu.Lock() defer f.mu.Unlock() if !f.done { f.done = true close(f.donec) } } func (f *fatalErrorHandler) getErr() error { f.mu.Lock() defer f.mu.Unlock() return f.err } func (f *fatalErrorHandler) Done() <-chan bool { return f.donec } type hugoSitesInit struct { // Loads the data from all of the /data folders. data hsync.FuncResetter // Loads the Git info and CODEOWNERS for all the pages if enabled. gitInfo hsync.FuncResetter } func (h *HugoSites) Data() map[string]any { if err := h.init.data.Do(context.Background()); err != nil { h.SendError(fmt.Errorf("failed to load data: %w", err)) return nil } return h.data } // Pages returns all pages for all sites. func (h *HugoSites) Pages() page.Pages { key := "pages" v, err := h.cachePages.GetOrCreate(key, func(string) (page.Pages, error) { var pages page.Pages for _, s := range h.Sites { pages = append(pages, s.Pages()...) } page.SortByDefault(pages) return pages, nil }) if err != nil { panic(err) } return v } // Pages returns all regularpages for all sites. func (h *HugoSites) RegularPages() page.Pages { key := "regular-pages" v, err := h.cachePages.GetOrCreate(key, func(string) (page.Pages, error) { var pages page.Pages for _, s := range h.Sites { pages = append(pages, s.RegularPages()...) } page.SortByDefault(pages) return pages, nil }) if err != nil { panic(err) } return v } func (h *HugoSites) gitInfoForPage(p page.Page) (*source.GitInfo, error) { if err := h.init.gitInfo.Do(context.Background()); err != nil { return nil, err } if h.gitInfo == nil { return nil, nil } return h.gitInfo.forPage(p), nil } func (h *HugoSites) codeownersForPage(p page.Page) ([]string, error) { if err := h.init.gitInfo.Do(context.Background()); err != nil { return nil, err } if h.codeownerInfo == nil { return nil, nil } return h.codeownerInfo.forPage(p), nil } func (h *HugoSites) reportProgress(f func() (state terminal.ProgressState, progress float64)) { h.progressReporter.mu.Lock() defer h.progressReporter.mu.Unlock() if h.progressReporter.t.IsZero() { // Not started yet, queue it up and return. h.progressReporter.queue = append(h.progressReporter.queue, f) return } handleOne := func(skip func(state terminal.ProgressState, progress float64) bool, handle func() (state terminal.ProgressState, progress float64)) { state, progress := handle() if skip != nil && skip(state, progress) { return } if h.progressReporter.progress > 0 && h.progressReporter.state == state && progress <= h.progressReporter.progress { // Only report progress forward. return } h.progressReporter.state = state h.progressReporter.progress = progress terminal.ReportProgress(h.Log.StdOut(), state, h.progressReporter.progress) } // Drain queue first. skip := func(state terminal.ProgressState, progress float64) bool { // Skip qued up intermediate states if we already are in normal state. return h.progressReporter.state == terminal.ProgressNormal && state == terminal.ProgressIntermediate } for _, ff := range h.progressReporter.queue { handleOne(skip, ff) } h.progressReporter.queue = nil handleOne(nil, f) } func (h *HugoSites) onPageRender() { pagesRendered := h.buildCounters.pageRenderCounter.Add(1) numPagesToRender := h.progressReporter.numPagesToRender.Load() n := numPagesToRender / 30 if n == 0 { n = 1 } if pagesRendered%n == 0 { h.reportProgress(func() (terminal.ProgressState, float64) { pr := h.progressReporter if pr.renderProgressStart == 0.0 && pr.state == terminal.ProgressNormal { pr.renderProgressStart = pr.progress } pagesProgress := pr.renderProgressStart + float64(pagesRendered)/float64(numPagesToRender)*(1.0-pr.renderProgressStart) return terminal.ProgressNormal, pagesProgress }) } } func (h *HugoSites) filterAndJoinErrors(errs []error) error { if len(errs) == 0 { return nil } seen := map[string]bool{} var n int for _, err := range errs { if err == nil { continue } errMsg := herrors.Cause(err).Error() // We don't need to see many "Could not resolve "@alpinejs/persists"" if !seen[errMsg] { seen[errMsg] = true errs[n] = err n++ } } errs = errs[:n] for i, err := range errs { errs[i] = herrors.ImproveRenderErr(err) } const limit = 10 if len(errs) > limit { errs = errs[:limit] } return errors.Join(errs...) } func (h *HugoSites) isMultilingual() bool { return len(h.Sites) > 1 } // TODO(bep) consolidate func (h *HugoSites) LanguageSet() map[string]int { set := make(map[string]int) for i, s := range h.Sites { set[s.language.Lang] = i } return set } func (h *HugoSites) NumLogErrors() int { if h == nil { return 0 } return h.Log.LoggCount(logg.LevelError) } func (h *HugoSites) PrintProcessingStats(w io.Writer) { stats := make([]*helpers.ProcessingStats, len(h.Sites)) for i := range h.Sites { stats[i] = h.Sites[i].PathSpec.ProcessingStats } helpers.ProcessingStatsTable(w, stats...) } // GetContentPage finds a Page with content given the absolute filename. // Returns nil if none found. func (h *HugoSites) GetContentPage(filename string) page.Page { var p page.Page h.withPage(func(s string, p2 *pageState) bool { if p2.File() == nil { return false } if p2.File().FileInfo().Meta().Filename == filename { p = p2 return true } for _, r := range p2.Resources().ByType(pageResourceType) { p3 := r.(page.Page) if p3.File() != nil && p3.File().FileInfo().Meta().Filename == filename { p = p3 return true } } return false }) return p } func (h *HugoSites) loadGitInfo() error { if h.Configs.Base.EnableGitInfo { gi, err := newGitInfo(h.Deps) if err != nil { h.Log.Errorln("Failed to read Git log:", err) } else { h.gitInfo = gi } co, err := newCodeOwners(h.Configs.LoadingInfo.BaseConfig.WorkingDir) if err != nil { h.Log.Errorln("Failed to read CODEOWNERS:", err) } else { h.codeownerInfo = co } } return nil } // Reset resets the sites and template caches etc., making it ready for a full rebuild. func (h *HugoSites) reset() { h.fatalErrorHandler = &fatalErrorHandler{ h: h, donec: make(chan bool), } } // resetLogs resets the log counters etc. Used to do a new build on the same sites. func (h *HugoSites) resetLogs() { h.Log.Reset() for _, s := range h.Sites { s.Deps.Log.Reset() } } func (h *HugoSites) withSite(fn func(s *Site) error) error { for _, s := range h.Sites { if err := fn(s); err != nil { return err } } return nil } func (h *HugoSites) withPage(fn func(s string, p *pageState) bool) { h.withSite(func(s *Site) error { w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: s.pageMap.treePages, LockType: doctree.LockTypeRead, Handle: func(s string, n contentNode) (radix.WalkFlag, error) { if fn(s, n.(*pageState)) { return radix.WalkStop, nil } return radix.WalkContinue, nil }, } return w.Walk(context.Background()) }) } // BuildCfg holds build options used to, as an example, skip the render step. type BuildCfg struct { // Skip rendering. Useful for testing. SkipRender bool // Use this to indicate what changed (for rebuilds). WhatChanged *WhatChanged // This is a partial re-render of some selected pages. PartialReRender bool // Set in server mode when the last build failed for some reason. ErrRecovery bool // Recently visited or touched URLs. This is used for partial re-rendering. RecentlyTouched *types.EvictingQueue[string] // Can be set to build only with a sub set of the content source. ContentInclusionFilter *hglob.FilenameFilter // Set when the buildlock is already acquired (e.g. the archetype content builder). NoBuildLock bool testCounters *buildCounters } // shouldRender returns whether this output format should be rendered or not. func (cfg *BuildCfg) shouldRender(infol logg.LevelLogger, p *pageState) bool { if p.skipRender() { return false } if !p.renderOnce { return true } // The render state is incremented on render and reset when a related change is detected. // Note that this is set per output format. shouldRender := p.renderState == 0 if !shouldRender { return false } fastRenderMode := p.s.Conf.FastRenderMode() if !fastRenderMode || p.s.h.buildCounter.Load() == 0 { return shouldRender } if !p.render { // Not be to rendered for this output format. return false } if relURL := p.getRelURL(); relURL != "" { if cfg.RecentlyTouched.Contains(relURL) { infol.Logf("render recently touched URL %q (%s)", relURL, p.outputFormat().Name) return true } } // In fast render mode, we want to avoid re-rendering the sitemaps etc. and // other big listings whenever we e.g. change a content file, // but we want partial renders of the recently touched pages to also include // alternative formats of the same HTML page (e.g. RSS, JSON). for _, po := range p.pageOutputs { if po.render && po.f.IsHTML && cfg.RecentlyTouched.Contains(po.getRelURL()) { infol.Logf("render recently touched URL %q, %s version of %s", po.getRelURL(), po.f.Name, p.outputFormat().Name) return true } } return false } func (s *Site) preparePagesForRender(isRenderingSite bool, idx int) error { var err error initPage := func(p *pageState) error { if err = p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } return s.pageMap.forEeachPageIncludingBundledPages(nil, func(p *pageState) (bool, error) { return false, initPage(p) }, ) } func (h *HugoSites) loadData() error { h.data = make(map[string]any) w := hugofs.NewWalkway( hugofs.WalkwayConfig{ Fs: h.PathSpec.BaseFs.Data.Fs, IgnoreFile: h.SourceSpec.IgnoreFile, PathParser: h.Conf.PathParser(), WalkFn: func(ctx context.Context, path string, fi hugofs.FileMetaInfo) error { if fi.IsDir() { return nil } pi := fi.Meta().PathInfo if pi == nil { panic("no path info") } return h.handleDataFile(source.NewFileInfo(fi)) }, }) if err := w.Walk(); err != nil { return err } return nil } func (h *HugoSites) handleDataFile(r *source.File) error { var current map[string]any f, err := r.FileInfo().Meta().Open() if err != nil { return fmt.Errorf("data: failed to open %q: %w", r.LogicalName(), err) } defer f.Close() // Crawl in data tree to insert data current = h.data dataPath := r.FileInfo().Meta().PathInfo.Unnormalized().Dir()[1:] keyParts := strings.SplitSeq(dataPath, "/") for key := range keyParts { if key != "" { if _, ok := current[key]; !ok { current[key] = make(map[string]any) } current = current[key].(map[string]any) } } data, err := h.readData(r) if err != nil { return h.errWithFileContext(err, r) } if data == nil { return nil } // filepath.Walk walks the files in lexical order, '/' comes before '.' higherPrecedentData := current[r.BaseFileName()] switch data.(type) { case map[string]any: switch higherPrecedentData.(type) { case nil: current[r.BaseFileName()] = data case map[string]any: // merge maps: insert entries from data for keys that // don't already exist in higherPrecedentData higherPrecedentMap := higherPrecedentData.(map[string]any) for key, value := range data.(map[string]any) { if _, exists := higherPrecedentMap[key]; exists { // this warning could happen if // 1. A theme uses the same key; the main data folder wins // 2. A sub folder uses the same key: the sub folder wins // TODO(bep) figure out a way to detect 2) above and make that a WARN h.Log.Infof("Data for key '%s' in path '%s' is overridden by higher precedence data already in the data tree", key, r.Path()) } else { higherPrecedentMap[key] = value } } default: // can't merge: higherPrecedentData is not a map h.Log.Warnf("The %T data from '%s' overridden by "+ "higher precedence %T data already in the data tree", data, r.Path(), higherPrecedentData) } case []any: if higherPrecedentData == nil { current[r.BaseFileName()] = data } else { // we don't merge array data h.Log.Warnf("The %T data from '%s' overridden by "+ "higher precedence %T data already in the data tree", data, r.Path(), higherPrecedentData) } default: h.Log.Errorf("unexpected data type %T in file %s", data, r.LogicalName()) } return nil } func (h *HugoSites) errWithFileContext(err error, f *source.File) error { realFilename := f.FileInfo().Meta().Filename return herrors.NewFileErrorFromFile(err, realFilename, h.Fs.Source, nil) } func (h *HugoSites) readData(f *source.File) (any, error) { file, err := f.FileInfo().Meta().Open() if err != nil { return nil, fmt.Errorf("readData: failed to open data file: %w", err) } defer file.Close() content := helpers.ReaderToBytes(file) format := metadecoders.FormatFromString(f.Ext()) return metadecoders.Default.Unmarshal(content, format) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/fileInfo.go
hugolib/fileInfo.go
// Copyright 2017-present The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "github.com/spf13/afero" "github.com/gohugoio/hugo/source" ) type fileInfo struct { *source.File } func (fi *fileInfo) Open() (afero.File, error) { f, err := fi.FileInfo().Meta().Open() if err != nil { err = fmt.Errorf("fileInfo: %w", err) } return f, err } func (fi *fileInfo) Lang() string { return fi.File.Lang() } func (fi *fileInfo) String() string { if fi == nil || fi.File == nil { return "" } return fi.Path() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/site_stats_test.go
hugolib/site_stats_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 hugolib import ( "bytes" "fmt" "testing" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" ) func TestSiteStats(t *testing.T) { t.Parallel() c := qt.New(t) files := ` -- hugo.toml -- baseURL = "http://example.com/blog" defaultContentLanguage = "nn" [pagination] pagerSize = 1 [languages] [languages.nn] languageName = "Nynorsk" weight = 1 title = "Hugo på norsk" [languages.en] languageName = "English" weight = 2 title = "Hugo in English" -- layouts/single.html -- Single|{{ .Title }}|{{ .Content }} {{ $img1 := resources.Get "myimage1.png" }} {{ $img1 = $img1.Fit "100x100" }} -- layouts/list.html -- List|{{ .Title }}|Pages: {{ .Paginator.TotalPages }}|{{ .Content }} -- layouts/terms.html -- Terms List|{{ .Title }}|{{ .Content }} ` pageTemplate := `--- title: "T%d" tags: %s categories: %s aliases: [/Ali%d] --- # Doc ` for i := range 2 { for j := range 2 { pageID := i + j + 1 files += fmt.Sprintf("\n-- content/p%d.md --\n", pageID) files += fmt.Sprintf(pageTemplate, pageID, fmt.Sprintf("- tag%d", j), fmt.Sprintf("- category%d", j), pageID) } } for i := range 5 { files += fmt.Sprintf("\n-- assets/myimage%d.png --\niVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", i+1) } b := Test(t, files) h := b.H stats := []*helpers.ProcessingStats{ h.Sites[0].PathSpec.ProcessingStats, h.Sites[1].PathSpec.ProcessingStats, } var buff bytes.Buffer helpers.ProcessingStatsTable(&buff, stats...) s := buff.String() c.Assert(s, qt.Contains, "Pages │ 19 │ 7") c.Assert(s, qt.Contains, "Processed images │ 1 │") } func TestSiteLastmod(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/" -- content/_index.md -- --- date: 2023-01-01 --- -- content/posts/_index.md -- --- date: 2023-02-01 --- -- content/posts/post-1.md -- --- date: 2023-03-01 --- -- content/posts/post-2.md -- --- date: 2023-04-01 --- -- layouts/home.html -- site.Lastmod: {{ .Site.Lastmod.Format "2006-01-02" }} home.Lastmod: {{ site.Home.Lastmod.Format "2006-01-02" }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "site.Lastmod: 2023-04-01\nhome.Lastmod: 2023-01-01") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/configdir_test.go
hugolib/configdir_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 hugolib import "testing" func TestConfigDir(t *testing.T) { t.Parallel() files := ` -- config/_default/params.toml -- a = "acp1" d = "dcp1" -- config/_default/config.toml -- [params] a = "ac1" b = "bc1" -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] ignoreErrors = ["error-missing-instagram-accesstoken"] [params] a = "a1" b = "b1" c = "c1" -- layouts/home.html -- Params: {{ site.Params}} ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Params: map[a:acp1 b:bc1 c:c1 d:dcp1] `) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__ref.go
hugolib/page__ref.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "github.com/gohugoio/hugo/common/text" "github.com/mitchellh/mapstructure" ) func newPageRef(p *pageState) pageRef { return pageRef{p: p} } type pageRef struct { p *pageState } func (p pageRef) Ref(argsm map[string]any) (string, error) { return p.ref(argsm, p.p) } func (p pageRef) RefFrom(argsm map[string]any, source any) (string, error) { return p.ref(argsm, source) } func (p pageRef) RelRef(argsm map[string]any) (string, error) { return p.relRef(argsm, p.p) } func (p pageRef) RelRefFrom(argsm map[string]any, source any) (string, error) { return p.relRef(argsm, source) } func (p pageRef) decodeRefArgs(args map[string]any) (refArgs, *Site, error) { var ra refArgs err := mapstructure.WeakDecode(args, &ra) if err != nil { return ra, nil, nil } s := p.p.s if ra.Lang != "" && ra.Lang != p.p.s.Language().Lang { // Find correct site found := false for _, ss := range p.p.s.h.Sites { if ss.Lang() == ra.Lang { found = true s = ss } } if !found { p.p.s.siteRefLinker.logNotFound(ra.Path, fmt.Sprintf("no site found with lang %q", ra.Lang), nil, text.Position{}) return ra, nil, nil } } return ra, s, nil } func (p pageRef) ref(argsm map[string]any, source any) (string, error) { args, s, err := p.decodeRefArgs(argsm) if err != nil { return "", fmt.Errorf("invalid arguments to Ref: %w", err) } if s == nil { return p.p.s.siteRefLinker.notFoundURL, nil } if args.Path == "" { return "", nil } return s.siteRefLinker.refLink(args.Path, source, false, args.OutputFormat) } func (p pageRef) relRef(argsm map[string]any, source any) (string, error) { args, s, err := p.decodeRefArgs(argsm) if err != nil { return "", fmt.Errorf("invalid arguments to Ref: %w", err) } if s == nil { return p.p.s.siteRefLinker.notFoundURL, nil } if args.Path == "" { return "", nil } return s.siteRefLinker.refLink(args.Path, source, true, args.OutputFormat) } type refArgs struct { Path string Lang string OutputFormat string }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/hugo_sites_multihost_test.go
hugolib/hugo_sites_multihost_test.go
package hugolib import ( "testing" qt "github.com/frankban/quicktest" ) func TestMultihost(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- defaultContentLanguage = "fr" defaultContentLanguageInSubdir = false staticDir = ["s1", "s2"] enableRobotsTXT = true [pagination] pagerSize = 1 [permalinks] other = "/somewhere/else/:filename" [taxonomies] tag = "tags" [languages] [languages.en] staticDir2 = ["staticen"] baseURL = "https://example.com/docs" weight = 10 title = "In English" languageName = "English" [languages.fr] staticDir2 = ["staticfr"] baseURL = "https://example.fr" weight = 20 title = "Le Français" languageName = "Français" -- assets/css/main.css -- body { color: red; } -- content/mysect/mybundle/index.md -- --- tags: [a, b] title: "My Bundle fr" --- My Bundle -- content/mysect/mybundle/index.en.md -- --- tags: [c, d] title: "My Bundle en" --- My Bundle -- content/mysect/mybundle/foo.txt -- Foo -- layouts/list.html -- List|{{ .Title }}|{{ .Lang }}|{{ .Permalink}}|{{ .RelPermalink }}| -- layouts/single.html -- Single|{{ .Title }}|{{ .Lang }}|{{ .Permalink}}|{{ .RelPermalink }}| {{ $foo := .Resources.Get "foo.txt" | fingerprint }} Foo: {{ $foo.Permalink }}| {{ $css := resources.Get "css/main.css" | fingerprint }} CSS: {{ $css.Permalink }}|{{ $css.RelPermalink }}| -- layouts/robots.txt -- robots|{{ site.Language.Lang }} -- layouts/404.html -- 404|{{ site.Language.Lang }} ` b := Test(t, files) b.Assert(b.H.Conf.IsMultilingual(), qt.Equals, true) b.Assert(b.H.Conf.IsMultihost(), qt.Equals, true) // helpers.PrintFs(b.H.Fs.PublishDir, "", os.Stdout) // Check regular pages. b.AssertFileContent("public/en/mysect/mybundle/index.html", "Single|My Bundle en|en|https://example.com/docs/mysect/mybundle/|") b.AssertFileContent("public/fr/mysect/mybundle/index.html", "Single|My Bundle fr|fr|https://example.fr/mysect/mybundle/|") // Check robots.txt b.AssertFileContent("public/en/robots.txt", "robots|en") b.AssertFileContent("public/fr/robots.txt", "robots|fr") // Check sitemap.xml b.AssertFileContent("public/en/sitemap.xml", "https://example.com/docs/mysect/mybundle/") b.AssertFileContent("public/fr/sitemap.xml", "https://example.fr/mysect/mybundle/") // Check 404 b.AssertFileContent("public/en/404.html", "404|en") b.AssertFileContent("public/fr/404.html", "404|fr") // Check tags. b.AssertFileContent("public/en/tags/d/index.html", "List|D|en|https://example.com/docs/tags/d/") b.AssertFileContent("public/fr/tags/b/index.html", "List|B|fr|https://example.fr/tags/b/") b.AssertFileExists("public/en/tags/b/index.html", false) b.AssertFileExists("public/fr/tags/d/index.html", false) // en/mysect/mybundle/foo.txt fingerprinted b.AssertFileContent("public/en/mysect/mybundle/foo.1cbec737f863e4922cee63cc2ebbfaafcd1cff8b790d8cfd2e6a5d550b648afa.txt", "Foo") b.AssertFileContent("public/en/mysect/mybundle/index.html", "Foo: https://example.com/docs/mysect/mybundle/foo.1cbec737f863e4922cee63cc2ebbfaafcd1cff8b790d8cfd2e6a5d550b648afa.txt|") b.AssertFileContent("public/fr/mysect/mybundle/foo.1cbec737f863e4922cee63cc2ebbfaafcd1cff8b790d8cfd2e6a5d550b648afa.txt", "Foo") b.AssertFileContent("public/fr/mysect/mybundle/index.html", "Foo: https://example.fr/mysect/mybundle/foo.1cbec737f863e4922cee63cc2ebbfaafcd1cff8b790d8cfd2e6a5d550b648afa.txt|") // Assets CSS fingerprinted // Note that before Hugo v0.149.0 we rendered the project starting with defaultContentLanguage, // now with a more complex matrix, we have one sort order. b.AssertFileContent("public/en/mysect/mybundle/index.html", "CSS: https://example.com/docs/css/main.5de625c36355cce7c1d5408826a0b21abfb49fb6c0e1f16c945a6f2aef38200c.css|") b.AssertFileContent("public/en/css/main.5de625c36355cce7c1d5408826a0b21abfb49fb6c0e1f16c945a6f2aef38200c.css", "body { color: red; }") b.AssertFileContent("public/fr/mysect/mybundle/index.html", "CSS: https://example.com/docs/css/main.5de625c36355cce7c1d5408826a0b21abfb49fb6c0e1f16c945a6f2aef38200c.css|") b.AssertFileContent("public/fr/css/main.5de625c36355cce7c1d5408826a0b21abfb49fb6c0e1f16c945a6f2aef38200c.css", "body { color: red; }") } func TestMultihostResourcePerLanguageMultihostMinify(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] baseURL = "https://example.en" weight = 1 contentDir = "content/en" [languages.fr] baseURL = "https://example.fr" weight = 2 contentDir = "content/fr" -- content/en/section/mybundle/index.md -- --- title: "Mybundle en" --- -- content/fr/section/mybundle/index.md -- --- title: "Mybundle fr" --- -- content/en/section/mybundle/styles.css -- .body { color: english; } -- content/fr/section/mybundle/styles.css -- .body { color: french; } -- layouts/single.html -- {{ $data := .Resources.GetMatch "styles*" | minify }} {{ .Lang }}: {{ $data.Content}}|{{ $data.RelPermalink }}| ` b := Test(t, files) b.AssertFileContent("public/fr/section/mybundle/index.html", "fr: .body{color:french}|/section/mybundle/styles.min.css|", ) b.AssertFileContent("public/en/section/mybundle/index.html", "en: .body{color:english}|/section/mybundle/styles.min.css|", ) b.AssertFileContent("public/en/section/mybundle/styles.min.css", ".body{color:english}") b.AssertFileContent("public/fr/section/mybundle/styles.min.css", ".body{color:french}") } func TestResourcePerLanguageIssue12163(t *testing.T) { files := ` -- hugo.toml -- defaultContentLanguage = 'de' disableKinds = ['rss','sitemap','taxonomy','term'] [languages.de] baseURL = 'https://de.example.org/' contentDir = 'content/de' weight = 1 [languages.en] baseURL = 'https://en.example.org/' contentDir = 'content/en' weight = 2 -- content/de/mybundle/index.md -- --- title: mybundle-de --- -- content/de/mybundle/pixel.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- content/en/mybundle/index.md -- --- title: mybundle-en --- -- layouts/single.html -- {{ with .Resources.Get "pixel.png" }} {{ with .Resize "2x2" }} {{ .RelPermalink }}| {{ end }} {{ end }} ` b := Test(t, files) b.AssertFileExists("public/de/mybundle/index.html", true) b.AssertFileExists("public/en/mybundle/index.html", true) b.AssertFileExists("public/de/mybundle/pixel.png", true) b.AssertFileExists("public/en/mybundle/pixel.png", true) b.AssertFileExists("public/de/mybundle/pixel_hu_c8522c65d73a0421.png", true) // failing test below b.AssertFileExists("public/en/mybundle/pixel_hu_c8522c65d73a0421.png", true) } func TestMultihostResourceOneBaseURLWithSubPath(t *testing.T) { files := ` -- hugo.toml -- defaultContentLanguage = "en" [languages] [languages.en] baseURL = "https://example.com/docs" weight = 1 contentDir = "content/en" [languages.en.permalinks] section = "/enpages/:slug/" [languages.fr] baseURL = "https://example.fr" contentDir = "content/fr" -- content/en/section/mybundle/index.md -- --- title: "Mybundle en" --- -- content/fr/section/mybundle/index.md -- --- title: "Mybundle fr" --- -- content/fr/section/mybundle/file1.txt -- File 1 fr. -- content/en/section/mybundle/file1.txt -- File 1 en. -- content/en/section/mybundle/file2.txt -- File 2 en. -- layouts/single.html -- {{ $files := .Resources.Match "file*" }} Files: {{ range $files }}{{ .Permalink }}|{{ end }}$ ` b := Test(t, files) b.AssertFileContent("public/en/enpages/mybundle-en/index.html", "Files: https://example.com/docs/enpages/mybundle-en/file1.txt|https://example.com/docs/enpages/mybundle-en/file2.txt|$") b.AssertFileContent("public/fr/section/mybundle/index.html", "Files: https://example.fr/section/mybundle/file1.txt|https://example.fr/section/mybundle/file2.txt|$") b.AssertFileContent("public/en/enpages/mybundle-en/file1.txt", "File 1 en.") b.AssertFileContent("public/fr/section/mybundle/file1.txt", "File 1 fr.") b.AssertFileContent("public/en/enpages/mybundle-en/file2.txt", "File 2 en.") b.AssertFileContent("public/fr/section/mybundle/file2.txt", "File 2 en.") } func TestMultihostAllButOneLanguageDisabledIssue12288(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- defaultContentLanguage = "en" disableLanguages = ["fr"] #baseURL = "https://example.com" [languages] [languages.en] baseURL = "https://example.en" weight = 1 [languages.fr] baseURL = "https://example.fr" weight = 2 -- assets/css/main.css -- body { color: red; } -- layouts/home.html -- {{ $css := resources.Get "css/main.css" | minify }} CSS: {{ $css.Permalink }}|{{ $css.RelPermalink }}| ` b := Test(t, files) b.AssertFileContent("public/css/main.min.css", "body{color:red}") b.AssertFileContent("public/index.html", "CSS: https://example.en/css/main.min.css|/css/main.min.css|") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__output.go
hugolib/page__output.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var paginatorNotSupported = page.PaginatorNotSupportedFunc(func() error { return fmt.Errorf("pagination not supported for this page") }) func newPageOutput( ps *pageState, pp pagePaths, f output.Format, render bool, ) *pageOutput { var targetPathsProvider targetPathsHolder var linksProvider resource.ResourceLinksProvider ft, found := pp.targetPaths[f.Name] if !found { // Link to the main output format ft = pp.targetPaths[pp.firstOutputFormat.Format.Name] } targetPathsProvider = ft linksProvider = ft var paginatorProvider page.PaginatorProvider var pag *pagePaginator if render && ps.IsNode() { pag = newPagePaginator(ps) paginatorProvider = pag } else { paginatorProvider = paginatorNotSupported } providers := struct { page.PaginatorProvider resource.ResourceLinksProvider targetPather }{ paginatorProvider, linksProvider, targetPathsProvider, } po := &pageOutput{ p: ps, f: f, pagePerOutputProviders: providers, MarkupProvider: page.NopPage, ContentProvider: page.NopPage, PageRenderProvider: page.NopPage, TableOfContentsProvider: page.NopPage, render: render, paginator: pag, dependencyManagerOutput: ps.s.Conf.NewIdentityManager(), } return po } // We create a pageOutput for every output format combination, even if this // particular page isn't configured to be rendered to that format. type pageOutput struct { p *pageState // Set if this page isn't configured to be rendered to this format. render bool f output.Format // Only set if render is set. // Note that this will be lazily initialized, so only used if actually // used in template(s). paginator *pagePaginator // These interface provides the functionality that is specific for this // output format. contentRenderer page.ContentRenderer pagePerOutputProviders page.MarkupProvider page.ContentProvider page.PageRenderProvider page.TableOfContentsProvider page.RenderShortcodesProvider // May be nil. pco *pageContentOutput dependencyManagerOutput identity.Manager renderState int // Reset when it needs to be rendered again. renderOnce bool // To make sure we at least try to render it once. } func (po *pageOutput) incrRenderState() { po.renderState++ po.renderOnce = true } // isRendered reports whether this output format or its content has been rendered. func (po *pageOutput) isRendered() bool { if po.renderState > 0 { return true } if po.pco != nil && po.pco.contentRendered.Load() { return true } return false } func (po *pageOutput) IdentifierBase() string { return po.p.f.Name } func (po *pageOutput) GetDependencyManager() identity.Manager { return po.dependencyManagerOutput } func (p *pageOutput) setContentProvider(cp *pageContentOutput) { if cp == nil { return } p.contentRenderer = cp p.ContentProvider = cp p.MarkupProvider = cp p.PageRenderProvider = cp p.TableOfContentsProvider = cp p.RenderShortcodesProvider = cp p.pco = cp }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/pagecollections.go
hugolib/pagecollections.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 hugolib import ( "fmt" "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" ) // pageFinder provides ways to find a Page in a Site. type pageFinder struct { pm *pageMap } func newPageFinder(m *pageMap) *pageFinder { if m == nil { panic("must provide a pageMap") } c := &pageFinder{pm: m} return c } // getPageRef resolves a Page from ref/relRef, with a slightly more comprehensive // search path than getPage. func (c *pageFinder) getPageRef(context page.Page, ref string) (page.Page, error) { n, err := c.getContentNode(context, true, ref) if err != nil { return nil, err } if p, ok := n.(page.Page); ok { return p, nil } return nil, nil } func (c *pageFinder) getPage(context page.Page, ref string) (page.Page, error) { n, err := c.getContentNode(context, false, ref) if err != nil { return nil, err } if p, ok := n.(page.Page); ok { return p, nil } return nil, nil } // Only used in tests. func (c *pageFinder) getPageOldVersion(kind string, sections ...string) page.Page { refs := append([]string{kind}, path.Join(sections...)) p, _ := c.getPageForRefs(refs...) return p } // This is an adapter func for the old API with Kind as first argument. // This is invoked when you do .Site.GetPage. We drop the Kind and fails // if there are more than 2 arguments, which would be ambiguous. func (c *pageFinder) getPageForRefs(ref ...string) (page.Page, error) { var refs []string for _, r := range ref { // A common construct in the wild is // .Site.GetPage "home" "" or // .Site.GetPage "home" "/" if r != "" && r != "/" { refs = append(refs, r) } } var key string if len(refs) > 2 { // This was allowed in Hugo <= 0.44, but we cannot support this with the // new API. This should be the most unusual case. return nil, fmt.Errorf(`too many arguments to .Site.GetPage: %v. Use lookups on the form {{ .Site.GetPage "/posts/mypage-md" }}`, ref) } if len(refs) == 0 || refs[0] == kinds.KindHome { key = "/" } else if len(refs) == 1 { if len(ref) == 2 && refs[0] == kinds.KindSection { // This is an old style reference to the "Home Page section". // Typically fetched via {{ .Site.GetPage "section" .Section }} // See https://github.com/gohugoio/hugo/issues/4989 key = "/" } else { key = refs[0] } } else { key = refs[1] } return c.getPage(nil, key) } const defaultContentExt = ".md" func (c *pageFinder) getContentNode(context page.Page, isReflink bool, ref string) (contentNode, error) { ref = paths.ToSlashTrimTrailing(ref) inRef := ref if ref == "" { ref = "/" } if paths.HasExt(ref) { return c.getContentNodeForRef(context, isReflink, true, inRef, ref) } // We are always looking for a content file and having an extension greatly simplifies the code that follows, // even in the case where the extension does not match this one. if ref == "/" { if n, err := c.getContentNodeForRef(context, isReflink, false, inRef, "/_index"+defaultContentExt); n != nil || err != nil { return n, err } } else if strings.HasSuffix(ref, "/index") { if n, err := c.getContentNodeForRef(context, isReflink, false, inRef, ref+"/index"+defaultContentExt); n != nil || err != nil { return n, err } if n, err := c.getContentNodeForRef(context, isReflink, false, inRef, ref+defaultContentExt); n != nil || err != nil { return n, err } } else { if n, err := c.getContentNodeForRef(context, isReflink, false, inRef, ref+defaultContentExt); n != nil || err != nil { return n, err } } return nil, nil } func (c *pageFinder) getContentNodeForRef(context page.Page, isReflink, hadExtension bool, inRef, ref string) (contentNode, error) { s := c.pm.s contentPathParser := s.Conf.PathParser() if context != nil && !strings.HasPrefix(ref, "/") { // Try the page-relative path first. // Branch pages: /mysection, "./mypage" => /mysection/mypage // Regular pages: /mysection/mypage.md, Path=/mysection/mypage, "./someotherpage" => /mysection/mypage/../someotherpage // Regular leaf bundles: /mysection/mypage/index.md, Path=/mysection/mypage, "./someotherpage" => /mysection/mypage/../someotherpage // Given the above, for regular pages we use the containing folder. var baseDir string if pi := context.PathInfo(); pi != nil { if pi.IsBranchBundle() || (hadExtension && strings.HasPrefix(ref, "../")) { baseDir = pi.Dir() } else { baseDir = pi.ContainerDir() } } rel := path.Join(baseDir, ref) relPath, _ := contentPathParser.ParseBaseAndBaseNameNoIdentifier(files.ComponentFolderContent, rel) n, err := c.getContentNodeFromPath(relPath) if n != nil || err != nil { return n, err } if hadExtension && context.File() != nil { if n, err := c.getContentNodeFromRefReverseLookup(inRef, context.File().FileInfo()); n != nil || err != nil { return n, err } } } if strings.HasPrefix(ref, ".") { // Page relative, no need to look further. return nil, nil } relPath, nameNoIdentifier := contentPathParser.ParseBaseAndBaseNameNoIdentifier(files.ComponentFolderContent, ref) n, err := c.getContentNodeFromPath(relPath) if n != nil || err != nil { return n, err } if hadExtension && s.home != nil && s.home.File() != nil { if n, err := c.getContentNodeFromRefReverseLookup(inRef, s.home.File().FileInfo()); n != nil || err != nil { return n, err } } var doSimpleLookup bool if isReflink || context == nil { slashCount := strings.Count(inRef, "/") doSimpleLookup = slashCount == 0 } if !doSimpleLookup { return nil, nil } n = c.pm.pageReverseIndex.Get(nameNoIdentifier) if n == ambiguousContentNode { return nil, fmt.Errorf("page reference %q is ambiguous", inRef) } return n, nil } func (c *pageFinder) getContentNodeFromRefReverseLookup(ref string, fi hugofs.FileMetaInfo) (contentNode, error) { s := c.pm.s meta := fi.Meta() dir := meta.Filename if !fi.IsDir() { dir = filepath.Dir(meta.Filename) } realFilename := filepath.Join(dir, ref) pcs, err := s.BaseFs.Content.ReverseLookup(realFilename, true) if err != nil { return nil, err } // There may be multiple matches, but we will only use the first one. for _, pc := range pcs { pi := s.Conf.PathParser().Parse(pc.Component, pc.Path) if n := c.pm.treePages.Get(pi.Base()); n != nil { return n, nil } } return nil, nil } func (c *pageFinder) getContentNodeFromPath(s string) (contentNode, error) { n := c.pm.treePages.Get(s) if n != nil { return n, nil } return nil, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/content_map_page_contentnode.go
hugolib/content_map_page_contentnode.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 hugolib import ( "fmt" "iter" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var _ contentNode = (*contentNodeSeq)(nil) var ( _ contentNode = (*resourceSource)(nil) _ contentNodeContentWeightProvider = (*pageState)(nil) _ contentNodeForSites = (*pageState)(nil) _ contentNodePage = (*contentNodes)(nil) _ contentNodePage = (*pageMetaSource)(nil) _ contentNodePage = (*pageState)(nil) _ contentNodeSourceEntryIDProvider = (*pageState)(nil) _ contentNodeSourceEntryIDProvider = (*pageMetaSource)(nil) _ contentNodeSourceEntryIDProvider = (*resourceSource)(nil) _ contentNodeLookupContentNode = (*contentNodesMap)(nil) _ contentNodeLookupContentNode = (contentNodes)(nil) _ contentNodeSingle = (*pageMetaSource)(nil) _ contentNodeSingle = (*pageState)(nil) _ contentNodeSingle = (*resourceSource)(nil) ) var ( _ contentNode = (*contentNodesMap)(nil) _ contentNodeMap = (*contentNodesMap)(nil) ) func (n contentNodesMap) ForEeachInAllDimensions(f func(contentNode) bool) { for _, nn := range n { if !f(nn) { return } } } func (n contentNodesMap) Path() string { return n.sample().Path() } type ( contentNode interface { Path() string contentNodeForEach } contentNodeBuildStateResetter interface { resetBuildState() } contentNodeSeq2 iter.Seq2[sitesmatrix.Vector, contentNode] contentNodeForSite interface { contentNode siteVector() sitesmatrix.Vector } contentNodeForEach interface { // forEeachContentNode iterates over all content nodes. // calling f with the site vector and the content node. // If f returns false, the iteration stops. // It returns false if the iteration was stopped early. forEeachContentNode(f func(sitesmatrix.Vector, contentNode) bool) bool } contentNodeForSites interface { contentNode siteVectors() sitesmatrix.VectorIterator } contentNodePage interface { contentNode nodeCategoryPage() // Marker interface. } contentNodeSingle interface { contentNode nodeCategorySingle() // Marker interface. } contentNodeLookupContentNode interface { contentNode lookupContentNode(v sitesmatrix.Vector) contentNode } contentNodeLookupContentNodes interface { lookupContentNodes(v sitesmatrix.Vector, fallback bool) iter.Seq[contentNodeForSite] } contentNodeSampleProvider interface { // sample is used to get a sample contentNode from a collection. sample() contentNode } contentNodeCascadeProvider interface { getCascade() *page.PageMatcherParamsConfigs } contentNodeContentWeightProvider interface { contentWeight() int } contentNodeIsEmptyProvider interface { isEmpty() bool } contentNodeSourceEntryIDProvider interface { nodeSourceEntryID() any } contentNodeMap interface { contentNode contentNodeLookupContentNode } ) type contentNodeSeq iter.Seq[contentNode] func (n contentNodeSeq) Path() string { return n.sample().Path() } func (n contentNodeSeq) isEmpty() bool { for range n { return false } return true } func (n contentNodeSeq) forEeachContentNode(f func(sitesmatrix.Vector, contentNode) bool) bool { for nn := range n { if !nn.forEeachContentNode(f) { return false } } return true } func (n contentNodeSeq) sample() contentNode { for nn := range n { return nn } return nil } func (n contentNodeSeq2) forEeachContentNode(f func(sitesmatrix.Vector, contentNode) bool) bool { for _, nn := range n { if !nn.forEeachContentNode(f) { return false } } return true } type contentNodes []contentNode func (n contentNodes) Path() string { return n.sample().Path() } func (m contentNodes) isEmpty() bool { return len(m) == 0 } func (n contentNodes) forEeachContentNode(f func(v sitesmatrix.Vector, n contentNode) bool) bool { for _, nn := range n { if !nn.forEeachContentNode(f) { return false } } return true } func (n contentNodes) lookupContentNode(v sitesmatrix.Vector) contentNode { for _, nn := range n { if vv := nn.(contentNodeLookupContentNode).lookupContentNode(v); vv != nil { return vv } } return nil } func (m *contentNodes) nodeCategoryPage() { // Marker method. } func (n contentNodes) sample() contentNode { if len(n) == 0 { panic("pageMetaSourcesSlice is empty") } return n[0] } type contentNodesMap map[sitesmatrix.Vector]contentNode var cnh helperContentNode type helperContentNode struct{} func (h helperContentNode) findContentNodeForSiteVector(q sitesmatrix.Vector, fallback bool, candidates contentNodeSeq) contentNodeForSite { var ( best contentNodeForSite = nil bestDistance int ) for n := range candidates { // The order of candidates is unstable, so we need to compare the matches to // get stable output. This compare will also make sure that we pick // language, version and role according to their individual sort order: // Closer is better, and matches above are better than matches below. if m := n.(contentNodeLookupContentNodes).lookupContentNodes(q, fallback); m != nil { for nn := range m { vec := nn.siteVector() if q == vec { // Exact match. return nn } distance := q.Distance(vec) if best == nil { best = nn bestDistance = distance } else { distanceAbs := absint(distance) bestDistanceAbs := absint(bestDistance) if distanceAbs < bestDistanceAbs { // Closer is better. best = nn bestDistance = distance } else if distanceAbs == bestDistanceAbs && distance > 0 { // Positive distance is better than negative. best = nn bestDistance = distance } } } } } return best } func (h helperContentNode) markStale(n contentNode) { n.forEeachContentNode( func(_ sitesmatrix.Vector, nn contentNode) bool { resource.MarkStale(nn) return true }, ) } func (h helperContentNode) resetBuildState(n contentNode) { n.forEeachContentNode( func(_ sitesmatrix.Vector, nn contentNode) bool { if nnn, ok := nn.(contentNodeBuildStateResetter); ok { nnn.resetBuildState() } return true }, ) } func (h helperContentNode) isBranchNode(n contentNode) bool { switch nn := n.(type) { case *pageMetaSource: return nn.pathInfo.IsBranchBundle() case *pageState: return nn.IsNode() case contentNodeSampleProvider: return h.isBranchNode(nn.sample()) default: return false } } func (h helperContentNode) isPageNode(n contentNode) bool { n, _ = h.one(n) switch n.(type) { case contentNodePage: return true default: return false } } func (helperContentNode) one(n contentNode) (nn contentNode, hasMore bool) { n.forEeachContentNode(func(_ sitesmatrix.Vector, n contentNode) bool { if nn == nil { nn = n return true } else { hasMore = true return false } }) return } func (h helperContentNode) GetIdentity(n contentNode) identity.Identity { switch nn := n.(type) { case identity.IdentityProvider: return nn.GetIdentity() case contentNodeSampleProvider: return h.GetIdentity(nn.sample()) default: return identity.Anonymous } } func (h helperContentNode) PathInfo(n contentNode) *paths.Path { switch nn := n.(type) { case interface{ PathInfo() *paths.Path }: return nn.PathInfo() case contentNodeSampleProvider: return h.PathInfo(nn.sample()) default: return nil } } func (h helperContentNode) toForEachIdentityProvider(n contentNode) identity.ForEeachIdentityProvider { return identity.ForEeachIdentityProviderFunc( func(cb func(id identity.Identity) bool) bool { return n.forEeachContentNode( func(vec sitesmatrix.Vector, nn contentNode) bool { return cb(h.GetIdentity(n)) }, ) }) } type weightedContentNode struct { n contentNode weight int term *pageWithOrdinal } func (n contentNodesMap) isEmpty() bool { return len(n) == 0 } func absint(i int) int { if i < 0 { return -i } return i } func contentNodeToContentNodesPage(n contentNode) (contentNodesMap, bool) { switch v := n.(type) { case contentNodesMap: return v, false case *pageState: return contentNodesMap{v.s.siteVector: v}, true default: panic(fmt.Sprintf("contentNodeToContentNodesPage: unexpected type %T", n)) } } func contentNodeToSeq(n contentNodeForEach) contentNodeSeq { if nn, ok := n.(contentNodeSeq); ok { return nn } return func(yield func(contentNode) bool) { n.forEeachContentNode(func(_ sitesmatrix.Vector, nn contentNode) bool { return yield(nn) }) } } func contentNodeToSeq2(n contentNodeForEach) contentNodeSeq2 { if nn, ok := n.(contentNodeSeq2); ok { return nn } return func(yield func(sitesmatrix.Vector, contentNode) bool) { n.forEeachContentNode(func(vec sitesmatrix.Vector, nn contentNode) bool { return yield(vec, nn) }) } } func (ps contentNodesMap) forEeachContentNode(f func(v sitesmatrix.Vector, n contentNode) bool) bool { for vec, nn := range ps { if !f(vec, nn) { return false } } return true } func (n contentNodesMap) lookupContentNode(v sitesmatrix.Vector) contentNode { if vv, ok := n[v]; ok { return vv } return nil } func (n contentNodesMap) sample() contentNode { for _, nn := range n { return nn } return nil } func (n contentNodesMap) siteVectors() sitesmatrix.VectorIterator { return n } func (n contentNodesMap) ForEachVector(yield func(v sitesmatrix.Vector) bool) bool { for v := range n { if !yield(v) { return false } } return true } func (n contentNodesMap) LenVectors() int { return len(n) } func (n contentNodesMap) VectorSample() sitesmatrix.Vector { for v := range n { return v } panic("no vectors") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/hugo_sites_build.go
hugolib/hugo_sites_build.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 hugolib import ( "bytes" "context" "encoding/json" "errors" "fmt" "os" "path" "path/filepath" "strings" "time" "github.com/bep/debounce" "github.com/bep/logg" "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/hugolib/doctree" "github.com/gohugoio/hugo/hugolib/pagesfromdata" "github.com/gohugoio/hugo/hugolib/segments" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/publisher" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/para" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/rungroup" "github.com/gohugoio/hugo/common/terminal" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/siteidentities" "github.com/gohugoio/hugo/resources/postpub" "github.com/spf13/afero" "github.com/fsnotify/fsnotify" ) // Build builds all sites. If filesystem events are provided, // this is considered to be a potential partial rebuild. func (h *HugoSites) Build(config BuildCfg, events ...fsnotify.Event) error { if h.isRebuild() && !h.Conf.Watching() { return errors.New("Build called multiple times when not in watch or server mode (typically with hugolib.Test(t, files).Build(); Build() is already called once by Test)") } if !h.isRebuild() && terminal.PrintANSIColors(os.Stdout) { // Don't show progress for fast builds. d := debounce.New(250 * time.Millisecond) d(func() { h.progressReporter.Start() h.reportProgress(func() (state terminal.ProgressState, progress float64) { // We don't know how many files to process below, so use the intermediate state as the first progress. return terminal.ProgressIntermediate, 1.0 }) }) defer d(func() {}) } infol := h.Log.InfoCommand("build") defer loggers.TimeTrackf(infol, time.Now(), nil, "") defer func() { h.reportProgress(func() (state terminal.ProgressState, progress float64) { return terminal.ProgressHidden, 1.0 }) h.buildCounter.Add(1) }() if h.Deps == nil { panic("must have deps") } if !config.NoBuildLock { unlock, err := h.BaseFs.LockBuild() if err != nil { return fmt.Errorf("failed to acquire a build lock: %w", err) } defer unlock() } defer func() { for _, s := range h.Sites { s.Deps.BuildEndListeners.Notify() } }() errCollector := h.StartErrorCollector() errs := make(chan error) go func(from, to chan error) { var errors []error i := 0 for e := range from { i++ if i > 50 { break } errors = append(errors, e) } to <- h.filterAndJoinErrors(errors) close(to) }(errCollector, errs) for _, s := range h.Sites { s.state = siteStateInit } if h.Metrics != nil { h.Metrics.Reset() } h.buildCounters = config.testCounters if h.buildCounters == nil { h.buildCounters = &buildCounters{} } // Need a pointer as this may be modified. conf := &config if conf.WhatChanged == nil { // Assume everything has changed conf.WhatChanged = &WhatChanged{needsPagesAssembly: true} } var prepareErr error if !config.PartialReRender { prepare := func() error { init := func(conf *BuildCfg) error { for _, s := range h.Sites { s.Deps.BuildStartListeners.Notify() } if len(events) > 0 || len(conf.WhatChanged.Changes()) > 0 { // Rebuild if err := h.initRebuild(conf); err != nil { return fmt.Errorf("initRebuild: %w", err) } } else { if err := h.initSites(); err != nil { return fmt.Errorf("initSites: %w", err) } } return nil } ctx := context.Background() if err := h.process(ctx, infol, conf, init, events...); err != nil { return fmt.Errorf("process: %w", err) } h.reportProgress(func() (state terminal.ProgressState, progress float64) { return terminal.ProgressNormal, 0.15 }) if err := h.assemble(ctx, infol, conf); err != nil { return fmt.Errorf("assemble: %w", err) } h.reportProgress(func() (state terminal.ProgressState, progress float64) { return terminal.ProgressNormal, 0.20 }) return nil } if prepareErr = prepare(); prepareErr != nil { h.SendError(prepareErr) } } for s := range h.allSites(nil) { s.state = siteStateReady } if prepareErr == nil { if err := h.render(infol, conf); err != nil { h.SendError(fmt.Errorf("render: %w", err)) } // Make sure to write any build stats to disk first so it's available // to the post processors. if err := h.writeBuildStats(); err != nil { return err } // We need to do this before render deferred. if err := h.printPathWarningsOnce(); err != nil { h.SendError(fmt.Errorf("printPathWarnings: %w", err)) } if err := h.renderDeferred(infol); err != nil { h.SendError(fmt.Errorf("renderDeferred: %w", err)) } // This needs to be done after the deferred rendering to get complete template usage coverage. if err := h.printUnusedTemplatesOnce(); err != nil { h.SendError(fmt.Errorf("printPathWarnings: %w", err)) } if err := h.postProcess(infol); err != nil { h.SendError(fmt.Errorf("postProcess: %w", err)) } } if h.Metrics != nil { var b bytes.Buffer h.Metrics.WriteMetrics(&b) h.Log.Printf("\nTemplate Metrics:\n\n") h.Log.Println(b.String()) } h.StopErrorCollector() err := <-errs if err != nil { return err } if err := h.fatalErrorHandler.getErr(); err != nil { return err } errorCount := h.Log.LoggCount(logg.LevelError) + loggers.Log().LoggCount(logg.LevelError) if errorCount > 0 { return fmt.Errorf("logged %d error(s)", errorCount) } return nil } // Build lifecycle methods below. // The order listed matches the order of execution. func (h *HugoSites) initSites() error { h.reset() return nil } func (h *HugoSites) initRebuild(config *BuildCfg) error { if !h.Configs.Base.Internal.Watch { return errors.New("rebuild called when not in watch mode") } h.pageTrees.treePagesResources.WalkPrefixRaw("", func(key string, n contentNode) (radix.WalkFlag, contentNode, error) { cnh.resetBuildState(n) return radix.WalkContinue, nil, nil }) for _, s := range h.Sites { s.resetBuildState(config.WhatChanged.needsPagesAssembly) } h.reset() h.resetLogs() return nil } // process prepares the Sites' sources for a full or partial rebuild. // This will also parse the source and create all the Page objects. func (h *HugoSites) process(ctx context.Context, l logg.LevelLogger, config *BuildCfg, init func(config *BuildCfg) error, events ...fsnotify.Event) error { l = l.WithField("step", "process") defer loggers.TimeTrackf(l, time.Now(), nil, "") if len(events) > 0 { // This is a rebuild triggered from file events. return h.processPartialFileEvents(ctx, l, config, init, events) } else if len(config.WhatChanged.Changes()) > 0 { // Rebuild triggered from remote events. if err := init(config); err != nil { return err } return h.processPartialRebuildChanges(ctx, l, config) } return h.processFull(ctx, l, config) } // assemble creates missing sections, applies aggregate values (e.g. dates, cascading params), // removes disabled pages etc. func (h *HugoSites) assemble(ctx context.Context, l logg.LevelLogger, bcfg *BuildCfg) error { l = l.WithField("step", "assemble") defer loggers.TimeTrackf(l, time.Now(), nil, "") if !bcfg.WhatChanged.needsPagesAssembly { changes := bcfg.WhatChanged.Drain() if len(changes) > 0 { if err := h.resolveAndClearStateForIdentities(ctx, l, nil, changes); err != nil { return err } } return nil } h.translationKeyPages.Reset() var assemblers []*sitePagesAssembler // Changes detected during assembly (e.g. aggregate date changes) for s := range h.allSites(nil) { assemblers = append(assemblers, &sitePagesAssembler{ s: s, assembleChanges: bcfg.WhatChanged, ctx: ctx, }) } apa := newAllPagesAssembler( ctx, h, assemblers[0].s.pageMap, bcfg.WhatChanged, ) for _, s := range assemblers { s.a = apa } if h.Conf.Watching() { defer func() { // Store previous walk context to detect cascade changes on next rebuild. h.previousPageTreesWalkContext = apa.rwRoot.WalkContext }() } if err := apa.createAllPages(); err != nil { return err } g, _ := h.workersSite.Start(ctx) for _, s := range assemblers { g.Run(func() error { return s.assemblePagesStep1() }) } if err := g.Wait(); err != nil { return err } changes := bcfg.WhatChanged.Drain() // Changes from the assemble step (e.g. lastMod, cascade) needs a re-calculation // of what needs to be re-built. if len(changes) > 0 { if err := h.resolveAndClearStateForIdentities(ctx, l, nil, changes); err != nil { return err } } for _, s := range assemblers { if err := s.assemblePagesStep2(); err != nil { return err } } // Handle new terms from assemblePagesStep2. changes = bcfg.WhatChanged.Drain() if len(changes) > 0 { if err := h.resolveAndClearStateForIdentities(ctx, l, nil, changes); err != nil { return err } } h.renderFormats = output.Formats{} for s := range h.allSites(nil) { s.initRenderFormats() h.renderFormats = append(h.renderFormats, s.renderFormats...) } for _, s := range assemblers { if err := s.assemblePagesStepFinal(); err != nil { return err } } return nil } // render renders the sites. func (h *HugoSites) render(l logg.LevelLogger, config *BuildCfg) error { l = l.WithField("step", "render") start := time.Now() defer func() { loggers.TimeTrackf(l, start, h.buildCounters.loggFields(), "") }() siteRenderContext := &siteRenderContext{cfg: config, infol: l, multihost: h.Configs.IsMultihost} renderErr := func(err error) error { if err == nil { return nil } // In Hugo 0.141.0 we replaced the special error handling for resources.GetRemote // with the more general try. if strings.Contains(err.Error(), "can't evaluate field Err in type") { if strings.Contains(err.Error(), "resource.Resource") { return fmt.Errorf("%s: Resource.Err was removed in Hugo v0.141.0 and replaced with a new try keyword, see https://gohugo.io/functions/go-template/try/", err) } else if strings.Contains(err.Error(), "template.HTML") { return fmt.Errorf("%s: 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/", err) } } return err } i := 0 for s := range h.allSites(nil) { if s.conf.Segments.Config.SegmentFilter.ShouldExcludeCoarse(segments.SegmentQuery{Site: s.siteVector}) { l.Logf("skip site %s not matching segments set in --renderSegments", s.resolveDimensionNames()) continue } siteRenderContext.languageIdx = s.siteVector.Language() h.currentSite = s for siteOutIdx, renderFormat := range s.renderFormats { if s.conf.Segments.Config.SegmentFilter.ShouldExcludeCoarse(segments.SegmentQuery{Output: renderFormat.Name, Site: s.siteVector}) { l.Logf("skip output format %q for site %s not matching segments set in --renderSegments", renderFormat.Name, s.resolveDimensionNames()) continue } if err := func() error { rc := tpl.RenderingContext{Site: s, SiteOutIdx: siteOutIdx} h.BuildState.StartStageRender(rc) defer h.BuildState.StopStageRender(rc) siteRenderContext.outIdx = siteOutIdx siteRenderContext.sitesOutIdx = i i++ select { case <-h.Done(): return nil default: for s2 := range h.allSites(nil) { if err := s2.preparePagesForRender(s == s2, siteRenderContext.sitesOutIdx); err != nil { return err } } if !config.SkipRender { ll := l.WithField("substep", "pages"). WithField("site", s.language.Lang). WithField("outputFormat", renderFormat.Name) start := time.Now() if config.PartialReRender { if err := s.renderPages(siteRenderContext); err != nil { return err } } else { if err := s.render(siteRenderContext); err != nil { return renderErr(err) } } loggers.TimeTrackf(ll, start, nil, "") } } return nil }(); err != nil { return err } } } return nil } func (h *HugoSites) renderDeferred(l logg.LevelLogger) error { l = l.WithField("step", "render deferred") start := time.Now() var deferredCount int for rc, de := range h.Deps.BuildState.DeferredExecutionsGroupedByRenderingContext { if de.FilenamesWithPostPrefix.Len() == 0 { continue } deferredCount += de.FilenamesWithPostPrefix.Len() s := rc.Site.(*Site) for _, s2 := range h.Sites { if err := s2.preparePagesForRender(s == s2, rc.SiteOutIdx); err != nil { return err } } if err := s.executeDeferredTemplates(de); err != nil { return herrors.ImproveRenderErr(err) } } loggers.TimeTrackf(l, start, logg.Fields{ logg.Field{Name: "count", Value: deferredCount}, }, "") return nil } func (s *Site) executeDeferredTemplates(de *deps.DeferredExecutions) error { handleFile := func(filename string) error { content, err := afero.ReadFile(s.BaseFs.PublishFs, filename) if err != nil { return err } k := 0 changed := false for { if k >= len(content) { break } l := bytes.Index(content[k:], []byte(tpl.HugoDeferredTemplatePrefix)) if l == -1 { break } m := bytes.Index(content[k+l:], []byte(tpl.HugoDeferredTemplateSuffix)) + len(tpl.HugoDeferredTemplateSuffix) low, high := k+l, k+l+m forward := l + m id := string(content[low:high]) if err := func() error { deferred, found := de.Executions.Get(id) if !found { panic(fmt.Sprintf("deferred execution with id %q not found", id)) } deferred.Mu.Lock() defer deferred.Mu.Unlock() if !deferred.Executed { tmpl := s.Deps.GetTemplateStore() ti := s.TemplateStore.LookupByPath(deferred.TemplatePath) if ti == nil { panic(fmt.Sprintf("template %q not found", deferred.TemplatePath)) } if err := func() error { buf := bufferpool.GetBuffer() defer bufferpool.PutBuffer(buf) err = tmpl.ExecuteWithContext(deferred.Ctx, ti, buf, deferred.Data) if err != nil { return err } deferred.Result = buf.String() deferred.Executed = true return nil }(); err != nil { return err } } content = append(content[:low], append([]byte(deferred.Result), content[high:]...)...) forward = len(deferred.Result) changed = true return nil }(); err != nil { return err } k += forward } if changed { return afero.WriteFile(s.BaseFs.PublishFs, filename, content, 0o666) } return nil } g := rungroup.Run(context.Background(), rungroup.Config[string]{ NumWorkers: s.h.numWorkers, Handle: func(ctx context.Context, filename string) error { return handleFile(filename) }, }) de.FilenamesWithPostPrefix.ForEeach(func(filename string, _ bool) bool { g.Enqueue(filename) return true }) return g.Wait() } // printPathWarningsOnce prints path warnings if enabled. func (h *HugoSites) printPathWarningsOnce() error { h.printPathWarningsInit.Do(func() { conf := h.Configs.Base if conf.PrintPathWarnings { // We need to do this before any post processing, as that may write to the same files twice // and create false positives. hugofs.WalkFilesystems(h.Fs.PublishDir, func(fs afero.Fs) bool { if dfs, ok := fs.(hugofs.DuplicatesReporter); ok { dupes := dfs.ReportDuplicates() if dupes != "" { h.Log.Warnln("Duplicate target paths:", dupes) } } return false }) } }) return nil } // / printUnusedTemplatesOnce prints unused templates if enabled. func (h *HugoSites) printUnusedTemplatesOnce() error { h.printUnusedTemplatesInit.Do(func() { conf := h.Configs.Base if conf.PrintUnusedTemplates { unusedTemplates := h.GetTemplateStore().UnusedTemplates() for _, unusedTemplate := range unusedTemplates { if unusedTemplate.Fi != nil { h.Log.Warnf("Template %s is unused, source %q", unusedTemplate.PathInfo.Path(), unusedTemplate.Fi.Meta().Filename) } else { h.Log.Warnf("Template %s is unused", unusedTemplate.PathInfo.Path()) } } } }) return nil } // postProcess runs the post processors, e.g. writing the hugo_stats.json file. func (h *HugoSites) postProcess(l logg.LevelLogger) error { l = l.WithField("step", "postProcess") defer loggers.TimeTrackf(l, time.Now(), nil, "") // This will only be set when js.Build have been triggered with // imports that resolves to the project or a module. // Write a jsconfig.json file to the project's /asset directory // to help JS IntelliSense in VS Code etc. if !h.ResourceSpec.BuildConfig().NoJSConfigInAssets { handleJSConfig := func(fi os.FileInfo) { m := fi.(hugofs.FileMetaInfo).Meta() if !m.IsProject { return } if jsConfig := h.ResourceSpec.JSConfigBuilder.Build(m.SourceRoot); jsConfig != nil { b, err := json.MarshalIndent(jsConfig, "", " ") if err != nil { h.Log.Warnf("Failed to create jsconfig.json: %s", err) } else { filename := filepath.Join(m.SourceRoot, "jsconfig.json") if h.Configs.Base.Internal.Running { h.skipRebuildForFilenamesMu.Lock() h.skipRebuildForFilenames[filename] = true h.skipRebuildForFilenamesMu.Unlock() } // Make sure it's written to the OS fs as this is used by // editors. if err := afero.WriteFile(hugofs.Os, filename, b, 0o666); err != nil { h.Log.Warnf("Failed to write jsconfig.json: %s", err) } } } } fi, err := h.BaseFs.Assets.Fs.Stat("") if err != nil { if !herrors.IsNotExist(err) { h.Log.Warnf("Failed to resolve jsconfig.json dir: %s", err) } } else { handleJSConfig(fi) } } var toPostProcess []postpub.PostPublishedResource for _, r := range h.ResourceSpec.PostProcessResources { toPostProcess = append(toPostProcess, r) } if len(toPostProcess) == 0 { // Nothing more to do. return nil } workers := para.New(config.GetNumWorkerMultiplier()) g, _ := workers.Start(context.Background()) handleFile := func(filename string) error { content, err := afero.ReadFile(h.BaseFs.PublishFs, filename) if err != nil { return err } k := 0 changed := false for { l := bytes.Index(content[k:], []byte(postpub.PostProcessPrefix)) if l == -1 { break } m := bytes.Index(content[k+l:], []byte(postpub.PostProcessSuffix)) + len(postpub.PostProcessSuffix) low, high := k+l, k+l+m field := content[low:high] forward := l + m for i, r := range toPostProcess { if r == nil { panic(fmt.Sprintf("resource %d to post process is nil", i+1)) } v, ok := r.GetFieldString(string(field)) if ok { content = append(content[:low], append([]byte(v), content[high:]...)...) changed = true forward = len(v) break } } k += forward } if changed { return afero.WriteFile(h.BaseFs.PublishFs, filename, content, 0o666) } return nil } filenames := h.Deps.BuildState.GetFilenamesWithPostPrefix() for _, filename := range filenames { g.Run(func() error { return handleFile(filename) }) } // Prepare for a new build. for _, s := range h.Sites { s.ResourceSpec.PostProcessResources = make(map[string]postpub.PostPublishedResource) } return g.Wait() } func (h *HugoSites) writeBuildStats() error { if h.ResourceSpec == nil { panic("h.ResourceSpec is nil") } if !h.ResourceSpec.BuildConfig().BuildStats.Enabled() { return nil } htmlElements := &publisher.HTMLElements{} for _, s := range h.Sites { stats := s.publisher.PublishStats() htmlElements.Merge(stats.HTMLElements) } htmlElements.Sort() stats := publisher.PublishStats{ HTMLElements: *htmlElements, } var buf bytes.Buffer enc := json.NewEncoder(&buf) enc.SetEscapeHTML(false) enc.SetIndent("", " ") err := enc.Encode(stats) if err != nil { return err } js := buf.Bytes() filename := filepath.Join(h.Configs.LoadingInfo.BaseConfig.WorkingDir, files.FilenameHugoStatsJSON) if existingContent, err := afero.ReadFile(hugofs.Os, filename); err == nil { // Check if the content has changed. if bytes.Equal(existingContent, js) { return nil } } // Make sure it's always written to the OS fs. if err := afero.WriteFile(hugofs.Os, filename, js, 0o666); err != nil { return err } // Write to the destination as well if it's a in-memory fs. if !hugofs.IsOsFs(h.Fs.Source) { if err := afero.WriteFile(h.Fs.WorkingDirWritable, filename, js, 0o666); err != nil { return err } } // This step may be followed by a post process step that may // rebuild e.g. CSS, so clear any cache that's defined for the hugo_stats.json. h.dynacacheGCFilenameIfNotWatchedAndDrainMatching(filename) return nil } type pathChange struct { // The path to the changed file. p *paths.Path // If true, this is a structural change (e.g. a delete or a rename). structural bool // If true, this is a directory. isDir bool } func (p pathChange) isStructuralChange() bool { return p.structural || p.isDir } func (h *HugoSites) processPartialRebuildChanges(ctx context.Context, l logg.LevelLogger, config *BuildCfg) error { if err := h.resolveAndClearStateForIdentities(ctx, l, nil, config.WhatChanged.Drain()); err != nil { return err } if err := h.processContentAdaptersOnRebuild(ctx, config); err != nil { return err } return nil } // processPartialFileEvents prepares the Sites' sources for a partial rebuild. func (h *HugoSites) processPartialFileEvents(ctx context.Context, l logg.LevelLogger, config *BuildCfg, init func(config *BuildCfg) error, events []fsnotify.Event) error { h.Log.Trace(logg.StringFunc(func() string { var sb strings.Builder sb.WriteString("File events:\n") for _, ev := range events { sb.WriteString(ev.String()) sb.WriteString("\n") } return sb.String() })) // For a list of events for the different OSes, see the test output in https://github.com/bep/fsnotifyeventlister/. events = h.fileEventsFilter(events) events = h.fileEventsTrim(events) eventInfos := h.fileEventsApplyInfo(events) logger := h.Log var ( tmplAdded bool tmplChanged bool i18nChanged bool needsPagesAssemble bool ) changedPaths := struct { changedFiles []*paths.Path addedFiles []*paths.Path changedDirs []*paths.Path deleted []*paths.Path }{} removeDuplicatePaths := func(ps []*paths.Path) []*paths.Path { seen := make(map[string]bool) var filtered []*paths.Path for _, p := range ps { if !seen[p.Path()] { seen[p.Path()] = true filtered = append(filtered, p) } } return filtered } var ( cacheBusters []func(string) bool deletedDirs []string addedContentPaths []*paths.Path ) var ( addedOrChangedContent []pathChange changes []identity.Identity ) for _, ev := range eventInfos { cpss := h.BaseFs.ResolvePaths(ev.Name) pss := make([]*paths.Path, len(cpss)) for i, cps := range cpss { p := cps.Path if ev.removed && !paths.HasExt(p) { // Assume this is a renamed/removed directory. // For deletes, we walk up the tree to find the container (e.g. branch bundle), // so we will catch this even if it is a file without extension. // This avoids us walking up to the home page bundle for the common case // of renaming root sections. p = p + "/_index.md" deletedDirs = append(deletedDirs, cps.Path) } pss[i] = h.Configs.ContentPathParser.Parse(cps.Component, p) if ev.added && !ev.isChangedDir && cps.Component == files.ComponentFolderContent { addedContentPaths = append(addedContentPaths, pss[i]) } // Compile cache buster. np := hglob.NormalizePath(path.Join(cps.Component, cps.Path)) g, err := h.ResourceSpec.BuildConfig().MatchCacheBuster(h.Log, np) if err == nil && g != nil { cacheBusters = append(cacheBusters, g) } if ev.added { changes = append(changes, identity.StructuralChangeAdd) } if ev.removed { changes = append(changes, identity.StructuralChangeRemove) } } if ev.removed { changedPaths.deleted = append(changedPaths.deleted, pss...) } else if ev.isChangedDir { changedPaths.changedDirs = append(changedPaths.changedDirs, pss...) } else if ev.added { changedPaths.addedFiles = append(changedPaths.addedFiles, pss...) } else { changedPaths.changedFiles = append(changedPaths.changedFiles, pss...) } } // Find the most specific identity possible. handleChange := func(pathInfo *paths.Path, delete, add, isDir bool) { switch pathInfo.Component() { case files.ComponentFolderContent: logger.Println("Source changed", pathInfo.Path()) isContentDataFile := pathInfo.IsContentData() if !isContentDataFile { if ids := h.pageTrees.collectAndMarkStaleIdentities(pathInfo); len(ids) > 0 { changes = append(changes, ids...) } } else { h.pageTrees.treePagesFromTemplateAdapters.DeleteAllFunc(pathInfo.Base(), func(s string, n *pagesfromdata.PagesFromTemplate) bool { changes = append(changes, n.DependencyManager) // Try to open the file to see if has been deleted. f, err := n.GoTmplFi.Meta().Open() if err == nil { f.Close() } if err != nil { // Remove all pages and resources below. prefix := paths.AddTrailingSlash(pathInfo.Base()) h.pageTrees.treePages.DeletePrefixRaw(prefix) h.pageTrees.resourceTrees.DeletePrefixRaw(prefix) changes = append(changes, hglob.NewGlobIdentity(prefix+"**")) } return err != nil }) } needsPagesAssemble = true if config.RecentlyTouched != nil { // Fast render mode. Adding them to the visited queue // avoids rerendering them on navigation. for _, id := range changes { if p, ok := id.(page.Page); ok { config.RecentlyTouched.Add(p.RelPermalink()) } } } h.pageTrees.treeTaxonomyEntries.DeletePrefix("") if delete && !isContentDataFile { _, ok := h.pageTrees.treePages.LongestPrefixRaw(pathInfo.Base()) if ok { h.pageTrees.treePages.DeletePrefixRaw(pathInfo.Base()) h.pageTrees.resourceTrees.DeletePrefixRaw(pathInfo.Base()) if pathInfo.IsBundle() { // Assume directory removed. h.pageTrees.treePages.DeletePrefixRaw(pathInfo.Base() + "/") h.pageTrees.resourceTrees.DeletePrefixRaw(pathInfo.Base() + "/") } } else { h.pageTrees.resourceTrees.DeletePrefixRaw(pathInfo.Base()) } } structural := delete structural = structural || (add && pathInfo.IsLeafBundle()) addedOrChangedContent = append(addedOrChangedContent, pathChange{p: pathInfo, structural: structural, isDir: isDir}) case files.ComponentFolderLayouts: tmplChanged = true templatePath := pathInfo.Unnormalized().TrimLeadingSlash().PathNoLang() if !h.GetTemplateStore().HasTemplate(templatePath) { tmplAdded = true } if tmplAdded { logger.Println("Template added", pathInfo.Path()) // A new template may require a more coarse grained build. base := pathInfo.Base() if strings.Contains(base, "_markup") { // It's hard to determine the exact change set of this, // so be very coarse grained. changes = append(changes, identity.GenghisKhan) } if strings.Contains(base, "shortcodes") { changes = append(changes, hglob.NewGlobIdentity(fmt.Sprintf("shortcodes/%s*", pathInfo.BaseNameNoIdentifier()))) } else { changes = append(changes, pathInfo) } } else { logger.Println("Template changed", pathInfo.Path()) id := h.GetTemplateStore().GetIdentity(pathInfo.Path()) if id != nil { changes = append(changes, id) } else { changes = append(changes, pathInfo) } } case files.ComponentFolderAssets: logger.Println("Asset changed", pathInfo.Path()) changes = append(changes, pathInfo) case files.ComponentFolderData: logger.Println("Data changed", pathInfo.Path()) // This should cover all usage of site.Data. // Currently very coarse grained. changes = append(changes, siteidentities.Data) h.init.data.Reset() case files.ComponentFolderI18n: logger.Println("i18n changed", pathInfo.Path()) i18nChanged = true // It's hard to determine the exact change set of this, // so be very coarse grained for now. changes = append(changes, identity.GenghisKhan) case files.ComponentFolderArchetypes: // Ignore for now. default: panic(fmt.Sprintf("unknown component: %q", pathInfo.Component())) } } changedPaths.deleted = removeDuplicatePaths(changedPaths.deleted) changedPaths.addedFiles = removeDuplicatePaths(changedPaths.addedFiles) changedPaths.changedFiles = removeDuplicatePaths(changedPaths.changedFiles) h.Log.Trace(logg.StringFunc(func() string { var sb strings.Builder sb.WriteString("Resolved paths:\n") sb.WriteString("Deleted:\n") for _, p := range changedPaths.deleted { sb.WriteString("path: " + p.Path()) sb.WriteString("\n") } sb.WriteString("Added:\n") for _, p := range changedPaths.addedFiles { sb.WriteString("path: " + p.Path()) sb.WriteString("\n") } sb.WriteString("Changed:\n") for _, p := range changedPaths.changedFiles { sb.WriteString("path: " + p.Path()) sb.WriteString("\n") } return sb.String() })) for _, deletedDir := range deletedDirs { prefix := deletedDir + "/" predicate := func(id identity.Identity) bool { // This will effectively reset all pages below this dir. return strings.HasPrefix(paths.AddLeadingSlash(id.IdentifierBase()), prefix) } // Test in both directions. changes = append(changes, identity.NewPredicateIdentity( // Is dependent. predicate, // Is dependency. predicate, ), ) } if len(addedContentPaths) > 0 { // These content files are new and not in use anywhere. // To make sure that these gets listed in any site.RegularPages ranges or similar // we could invalidate everything, but first try to collect a sample set // from the surrounding pages. var surroundingIDs []identity.Identity for _, p := range addedContentPaths { if ids := h.pageTrees.collectIdentitiesSurrounding(p.Base(), 10); len(ids) > 0 { surroundingIDs = append(surroundingIDs, ids...) } } if len(surroundingIDs) > 0 { changes = append(changes, surroundingIDs...) } else { // No surrounding pages found, so invalidate everything. changes = append(changes, identity.GenghisKhan) } } for _, deleted := range changedPaths.deleted { handleChange(deleted, true, false, false) } for _, id := range changedPaths.addedFiles { handleChange(id, false, true, false) } for _, id := range changedPaths.changedFiles { handleChange(id, false, false, false) } for _, id := range changedPaths.changedDirs { handleChange(id, false, false, true) } for _, id := range changes { if id == identity.GenghisKhan { for i, cp := range addedOrChangedContent { cp.structural = true addedOrChangedContent[i] = cp } break } } resourceFiles := h.fileEventsContentPaths(addedOrChangedContent) changed := &WhatChanged{ needsPagesAssembly: needsPagesAssemble, } changed.Add(changes...) config.WhatChanged = changed if err := init(config); err != nil { return err } var cacheBusterOr func(string) bool if len(cacheBusters) > 0 { cacheBusterOr = func(s string) bool { for _, cb := range cacheBusters { if cb(s) { return true } } return false } } changes2 := changed.Changes() h.Deps.OnChangeListeners.Notify(changes2...) if err := h.resolveAndClearStateForIdentities(ctx, l, cacheBusterOr, changed.Drain()); err != nil { return err } if tmplChanged {
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/disableKinds_test.go
hugolib/disableKinds_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 hugolib import ( "fmt" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/resources/kinds" ) func TestDisableKinds(t *testing.T) { filesForDisabledKind := func(disableKind string) string { return fmt.Sprintf(` -- hugo.toml -- baseURL = "http://example.com/blog" enableRobotsTXT = true ignoreErrors = ["error-disable-taxonomy"] disableKinds = ["%s"] -- layouts/single.html -- single -- content/sect/page.md -- --- title: Page categories: ["mycat"] tags: ["mytag"] --- -- content/sect/no-list.md -- --- title: No List build: list: false --- -- content/sect/no-render.md -- --- title: No List build: render: false --- -- content/sect/no-render-link.md -- --- title: No Render Link aliases: ["/link-alias"] build: render: link --- -- content/sect/no-publishresources/index.md -- --- title: No Publish Resources build: publishResources: false --- -- content/sect/headlessbundle/index.md -- --- title: Headless headless: true --- -- content/headless-local/_index.md -- --- title: Headless Local Lists cascade: build: render: false list: local publishResources: false --- -- content/headless-local/headless-local-page.md -- --- title: Headless Local Page --- -- content/headless-local/sub/_index.md -- --- title: Headless Local Lists Sub --- -- content/headless-local/sub/headless-local-sub-page.md -- --- title: Headless Local Sub Page --- -- content/sect/headlessbundle/data.json -- DATA -- content/sect/no-publishresources/data.json -- DATA `, disableKind) } t.Run("Disable "+kinds.KindPage, func(t *testing.T) { files := filesForDisabledKind(kinds.KindPage) b := Test(t, files) s := b.H.Sites[0] b.AssertFileExists("public/sect/page/index.html", false) b.AssertFileExists("public/categories/mycat/index.html", false) b.Assert(len(s.Taxonomies()["categories"]), qt.Equals, 0) }) t.Run("Disable "+kinds.KindTerm, func(t *testing.T) { files := filesForDisabledKind(kinds.KindTerm) b := Test(t, files) s := b.H.Sites[0] b.AssertFileExists("public/categories/index.html", false) b.AssertFileExists("public/categories/mycat/index.html", false) b.Assert(len(s.Taxonomies()["categories"]), qt.Equals, 0) }) t.Run("Disable "+kinds.KindTaxonomy, func(t *testing.T) { files := filesForDisabledKind(kinds.KindTaxonomy) b := Test(t, files) s := b.H.Sites[0] b.AssertFileExists("public/categories/mycat/index.html", false) b.AssertFileExists("public/categories/index.html", false) b.Assert(len(s.Taxonomies()["categories"]), qt.Equals, 1) }) t.Run("Disable "+kinds.KindHome, func(t *testing.T) { files := filesForDisabledKind(kinds.KindHome) b := Test(t, files) b.AssertFileExists("public/index.html", false) }) t.Run("Disable "+kinds.KindSection, func(t *testing.T) { files := filesForDisabledKind(kinds.KindSection) b := Test(t, files) b.AssertFileExists("public/sect/index.html", false) b.AssertFileContent("public/sitemap.xml", "sitemap") b.AssertFileContent("public/index.xml", "rss") }) t.Run("Disable "+kinds.KindRSS, func(t *testing.T) { files := filesForDisabledKind(kinds.KindRSS) b := Test(t, files) b.AssertFileExists("public/index.xml", false) }) t.Run("Disable "+kinds.KindSitemap, func(t *testing.T) { files := filesForDisabledKind(kinds.KindSitemap) b := Test(t, files) b.AssertFileExists("public/sitemap.xml", false) }) t.Run("Disable "+kinds.KindStatus404, func(t *testing.T) { files := filesForDisabledKind(kinds.KindStatus404) b := Test(t, files) b.AssertFileExists("public/404.html", false) }) t.Run("Disable "+kinds.KindRobotsTXT, func(t *testing.T) { files := filesForDisabledKind(kinds.KindRobotsTXT) b := Test(t, files) b.AssertFileExists("public/robots.txt", false) }) t.Run("Headless bundle", func(t *testing.T) { files := filesForDisabledKind("") b := Test(t, files) b.AssertFileExists("public/sect/headlessbundle/index.html", false) b.AssertFileExists("public/sect/headlessbundle/data.json", true) }) t.Run("Build config, no list", func(t *testing.T) { files := filesForDisabledKind("") b := Test(t, files) b.AssertFileExists("public/sect/no-list/index.html", true) }) t.Run("Build config, local list", func(t *testing.T) { files := filesForDisabledKind("") b := Test(t, files) // Assert that the pages are not rendered to disk, as list:local implies. b.AssertFileExists("public/headless-local/index.html", false) b.AssertFileExists("public/headless-local/headless-local-page/index.html", false) b.AssertFileExists("public/headless-local/sub/index.html", false) b.AssertFileExists("public/headless-local/sub/headless-local-sub-page/index.html", false) }) t.Run("Build config, no render", func(t *testing.T) { files := filesForDisabledKind("") b := Test(t, files) b.AssertFileExists("public/sect/no-render/index.html", false) }) t.Run("Build config, no render link", func(t *testing.T) { files := filesForDisabledKind("") b := Test(t, files) b.AssertFileExists("public/sect/no-render/index.html", false) b.AssertFileContent("public/link-alias/index.html", "refresh") }) t.Run("Build config, no publish resources", func(t *testing.T) { files := filesForDisabledKind("") b := Test(t, files) b.AssertFileExists("public/sect/no-publishresources/index.html", true) b.AssertFileExists("public/sect/no-publishresources/data.json", false) }) } // https://github.com/gohugoio/hugo/issues/6897#issuecomment-587947078 func TestDisableRSSWithRSSInCustomOutputs(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["term", "taxonomy", "RSS"] [outputs] home = [ "HTML", "RSS" ] -- layouts/home.html -- Home ` b := Test(t, files) // The config above is a little conflicting, but it exists in the real world. // In Hugo 0.65 we consolidated the code paths and made RSS a pure output format, // but we should make sure to not break existing sites. b.AssertFileExists("public/index.xml", false) } func TestBundleNoPublishResources(t *testing.T) { files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/home.html -- {{ $bundle := site.GetPage "section/bundle-false" }} {{ $data1 := $bundle.Resources.GetMatch "data1*" }} Data1: {{ $data1.RelPermalink }} -- content/section/bundle-false/index.md -- --- title: BundleFalse build: publishResources: false --- -- content/section/bundle-false/data1.json -- Some data1 -- content/section/bundle-false/data2.json -- Some data2 -- content/section/bundle-true/index.md -- --- title: BundleTrue --- -- content/section/bundle-true/data3.json -- Some data 3 ` b := Test(t, files) b.AssertFileContent("public/index.html", `Data1: /section/bundle-false/data1.json`) b.AssertFileContent("public/section/bundle-false/data1.json", `Some data1`) b.AssertFileExists("public/section/bundle-false/data2.json", false) b.AssertFileContent("public/section/bundle-true/data3.json", `Some data 3`) } func TestNoRenderAndNoPublishResources(t *testing.T) { files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/home.html -- {{ $page := site.GetPage "sect/no-render" }} {{ $sect := site.GetPage "sect-no-render" }} Page: {{ $page.Title }}|RelPermalink: {{ $page.RelPermalink }}|Outputs: {{ len $page.OutputFormats }} Section: {{ $sect.Title }}|RelPermalink: {{ $sect.RelPermalink }}|Outputs: {{ len $sect.OutputFormats }} -- content/sect-no-render/_index.md -- --- title: MySection build: render: false publishResources: false --- -- content/sect/no-render.md -- --- title: MyPage build: render: false publishResources: false --- ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Page: MyPage|RelPermalink: |Outputs: 0 Section: MySection|RelPermalink: |Outputs: 0 `) b.AssertFileExists("public/sect/no-render/index.html", false) b.AssertFileExists("public/sect-no-render/index.html", false) } func TestDisableOneOfThreeLanguages(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 title = "English" [languages.nn] weight = 2 title = "Nynorsk" disabled = true [languages.nb] weight = 3 title = "Bokmål" -- content/p1.nn.md -- --- title: "Page 1 nn" --- -- content/p1.nb.md -- --- title: "Page 1 nb" --- -- content/p1.en.md -- --- title: "Page 1 en" --- -- content/p2.nn.md -- --- title: "Page 2 nn" --- -- layouts/single.html -- {{ .Title }} ` b := Test(t, files) b.Assert(len(b.H.Sites), qt.Equals, 2) b.AssertFileContent("public/en/p1/index.html", "Page 1 en") b.AssertFileContent("public/nb/p1/index.html", "Page 1 nb") b.AssertFileExists("public/en/p2/index.html", false) b.AssertFileExists("public/nn/p1/index.html", false) b.AssertFileExists("public/nn/p2/index.html", false) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__meta.go
hugolib/page__meta.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 hugolib import ( "fmt" "path/filepath" "regexp" "strings" "time" xmaps "maps" "github.com/bep/logg" "github.com/gobuffalo/flect" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/hiter" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/gohugoio/hugo/resources/resource" "github.com/spf13/cast" ) var cjkRe = regexp.MustCompile(`\p{Han}|\p{Hangul}|\p{Hiragana}|\p{Katakana}`) func (m *pageMetaSource) GetIdentity() identity.Identity { return m.pathInfo } func (m *pageMetaSource) Path() string { return m.pathInfo.Base() } func (m *pageMetaSource) PathInfo() *paths.Path { return m.pathInfo } func (m *pageMetaSource) forEeachContentNode(f func(v sitesmatrix.Vector, n contentNode) bool) bool { return f(sitesmatrix.Vector{}, m) } type pageMetaSource struct { pathInfo *paths.Path // Always set. This the canonical path to the Page. f *source.File pi *contentParseInfo contentAdapterSourceEntryHash uint64 sitesMatrixBase sitesmatrix.VectorIterator sitesMatrixBaseOnly bool // Set for standalone pages, e.g. robotsTXT. standaloneOutputFormat output.Format resources.AtomicStaler pageConfigSource *pagemeta.PageConfigEarly cascadeCompiled *page.PageMatcherParamsConfigs resourcePath string // Set for bundled pages; path relative to its bundle root. bundled bool // Set if this page is bundled inside another. noFrontMatter bool openSource func() (hugio.ReadSeekCloser, error) } func (m *pageMetaSource) String() string { if m.f != nil { return fmt.Sprintf("pageMetaSource(%s, %s)", m.f.FileInfo().Meta().PathInfo, m.f.FileInfo().Meta().Filename) } return fmt.Sprintf("pageMetaSource(%s)", m.pathInfo) } func (m *pageMetaSource) nodeCategoryPage() { // Marker method. } func (m *pageMetaSource) nodeCategorySingle() { // Marker method. } func (m *pageMetaSource) nodeSourceEntryID() any { if m.f != nil && !m.f.IsContentAdapter() { return m.f.FileInfo().Meta().Filename } return m.contentAdapterSourceEntryHash } func (m *pageMetaSource) setCascadeFromMap(frontmatter map[string]any, defaultSitesMatrix sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions, logger loggers.Logger) error { const ( pageMetaKeyCascade = "cascade" ) // Check for any cascade define on itself. if cv, found := frontmatter[pageMetaKeyCascade]; found { var err error cascade, err := page.DecodeCascadeConfig(cv) if err != nil { return err } if err := cascade.InitConfig(logger, defaultSitesMatrix, configuredDimensions); err != nil { return err } m.cascadeCompiled = cascade } return nil } var _ contentNodeCascadeProvider = (*pageState)(nil) type pageMeta struct { // Shared between all dimensions of this page. *pageMetaSource pageConfig *pagemeta.PageConfigLate term string // Set for kind == KindTerm. singular string // Set for kind == KindTerm and kind == KindTaxonomy. content *cachedContent // The source and the parsed page content. datesOriginal pagemeta.Dates // Original dates for rebuilds. } func (p *pageState) getCascade() *page.PageMatcherParamsConfigs { return p.m.cascadeCompiled } func (m *pageMetaSource) initEarly(h *HugoSites, cascades *page.PageMatcherParamsConfigs) error { if err := m.doInitEarly(h, cascades); err != nil { return m.wrapError(err, h.SourceFs) } return nil } func (m *pageMetaSource) doInitEarly(h *HugoSites, cascades *page.PageMatcherParamsConfigs) error { if err := m.initFrontMatter(h); err != nil { return err } if m.pageConfigSource.Kind == "" { // Resolve page kind. m.pageConfigSource.Kind = kinds.KindSection if m.pathInfo.Base() == "" { m.pageConfigSource.Kind = kinds.KindHome } else if m.pathInfo.IsBranchBundle() { // A section, taxonomy or term. tc := h.getFirstTaxonomyConfig(m.Path()) if !tc.IsZero() { // Either a taxonomy or a term. if tc.pluralTreeKey == m.Path() { m.pageConfigSource.Kind = kinds.KindTaxonomy } else { m.pageConfigSource.Kind = kinds.KindTerm } } } else if m.f != nil { m.pageConfigSource.Kind = kinds.KindPage } } sitesMatrixBase := m.sitesMatrixBase if sitesMatrixBase == nil && m.f != nil { sitesMatrixBase = m.f.FileInfo().Meta().SitesMatrix } if m.sitesMatrixBaseOnly && sitesMatrixBase == nil { panic("sitesMatrixBaseOnly set, but no base sites matrix") } var fim *hugofs.FileMeta if m.f != nil { fim = m.f.FileInfo().Meta() } if err := m.pageConfigSource.CompileEarly(m.pathInfo, cascades, h.Conf, fim, sitesMatrixBase, m.sitesMatrixBaseOnly); err != nil { return err } if cnh.isBranchNode(m) && m.pageConfigSource.Frontmatter != nil { if err := m.setCascadeFromMap(m.pageConfigSource.Frontmatter, m.pageConfigSource.SitesMatrix, h.Conf.ConfiguredDimensions(), h.Log); err != nil { return err } } return nil } func (m *pageMetaSource) initFrontMatter(h *HugoSites) error { if m.pathInfo == nil { if err := m.initPathInfo(h); err != nil { return err } } if m.pageConfigSource == nil { m.pageConfigSource = &pagemeta.PageConfigEarly{} } // Read front matter. if err := m.parseFrontMatter(h, pageSourceIDCounter.Add(1)); err != nil { return err } var ext string if m.f != nil { if !m.f.IsContentAdapter() { ext = m.f.Ext() } } if err := m.pageConfigSource.SetMetaPreFromMap(ext, m.pi.frontMatter, h.Log, h.Conf); err != nil { return err } return nil } func (m *pageMetaSource) initPathInfo(h *HugoSites) error { pcfg := m.pageConfigSource if pcfg.Path != "" { s := pcfg.Path // Paths from content adapters should never have any extension. if pcfg.IsFromContentAdapter || !paths.HasExt(s) { var ( isBranch bool isBranchSet bool ext string = pcfg.ContentMediaType.FirstSuffix.Suffix ) if pcfg.Kind != "" { isBranch = kinds.IsBranch(pcfg.Kind) isBranchSet = true } if !pcfg.IsFromContentAdapter { if m.pathInfo != nil { if !isBranchSet { isBranch = m.pathInfo.IsBranchBundle() } if m.pathInfo.Ext() != "" { ext = m.pathInfo.Ext() } } else if m.f != nil { pi := m.f.FileInfo().Meta().PathInfo if !isBranchSet { isBranch = pi.IsBranchBundle() } if pi.Ext() != "" { ext = pi.Ext() } } } if isBranch { s += "/_index." + ext } else { s += "/index." + ext } } m.pathInfo = h.Conf.PathParser().Parse(files.ComponentFolderContent, s) } else { if m.f != nil { m.pathInfo = m.f.FileInfo().Meta().PathInfo } if m.pathInfo == nil { panic(fmt.Sprintf("missing pathInfo in %v", m)) } } return nil } func (m *pageMeta) initLate(s *Site) error { var tc viewName if m.pageConfigSource.Kind == kinds.KindTerm || m.pageConfigSource.Kind == kinds.KindTaxonomy { if tc.IsZero() { tc = s.pageMap.cfg.getTaxonomyConfig(m.Path()) } if tc.IsZero() { return fmt.Errorf("no taxonomy configuration found for %q", m.Path()) } m.singular = tc.singular if m.pageConfigSource.Kind == kinds.KindTerm { m.term = paths.TrimLeading(strings.TrimPrefix(m.pathInfo.Unnormalized().Base(), tc.pluralTreeKey)) } } return nil } // bookmark1 func (h *HugoSites) newPageMetaSourceFromFile(fi hugofs.FileMetaInfo) (*pageMetaSource, error) { p, err := func() (*pageMetaSource, error) { meta := fi.Meta() openSource := func() (hugio.ReadSeekCloser, error) { r, err := meta.Open() if err != nil { return nil, fmt.Errorf("failed to open file %q: %w", meta.Filename, err) } return r, nil } p := &pageMetaSource{ f: source.NewFileInfo(fi), pathInfo: fi.Meta().PathInfo, openSource: openSource, } return p, nil }() if err != nil { return nil, hugofs.AddFileInfoToError(err, fi, h.SourceFs) } return p, err } func (h *HugoSites) newPageMetaSourceForContentAdapter(fi hugofs.FileMetaInfo, sitesMatrixBase sitesmatrix.VectorIterator, pc *pagemeta.PageConfigEarly) (*pageMetaSource, error) { p := &pageMetaSource{ f: source.NewFileInfo(fi), noFrontMatter: true, pageConfigSource: pc, contentAdapterSourceEntryHash: pc.SourceEntryHash, sitesMatrixBase: sitesMatrixBase, openSource: pc.Content.ValueAsOpenReadSeekCloser(), } return p, p.initPathInfo(h) } func (s *Site) newPageFromPageMetasource(ms *pageMetaSource, cascades *page.PageMatcherParamsConfigs) (*pageState, error) { m, err := s.newPageMetaFromPageMetasource(ms) if err != nil { return nil, err } p, err := s.newPageFromPageMeta(m, cascades) if err != nil { return nil, err } return p, nil } func (s *Site) newPageMetaFromPageMetasource(ms *pageMetaSource) (*pageMeta, error) { m := &pageMeta{ pageMetaSource: ms, pageConfig: &pagemeta.PageConfigLate{ Params: make(maps.Params), }, } return m, nil } // Prepare for a rebuild of the data passed in from front matter. func (m *pageMeta) prepareRebuild() { // Restore orignal date values so we can repeat aggregation. m.pageConfig.Dates = m.datesOriginal } func (m *pageMeta) Aliases() []string { return m.pageConfig.Aliases } func (m *pageMeta) BundleType() string { switch m.pathInfo.Type() { case paths.TypeLeaf: return "leaf" case paths.TypeBranch: return "branch" default: return "" } } func (m *pageMeta) Date() time.Time { return m.pageConfig.Dates.Date } func (m *pageMeta) PublishDate() time.Time { return m.pageConfig.Dates.PublishDate } func (m *pageMeta) Lastmod() time.Time { return m.pageConfig.Dates.Lastmod } func (m *pageMeta) ExpiryDate() time.Time { return m.pageConfig.Dates.ExpiryDate } func (m *pageMeta) Description() string { return m.pageConfig.Description } func (m *pageMeta) Draft() bool { return m.pageConfig.Draft } func (m *pageMeta) File() *source.File { return m.f } func (m *pageMeta) IsHome() bool { return m.Kind() == kinds.KindHome } func (m *pageMeta) Keywords() []string { return m.pageConfig.Keywords } func (m *pageMetaSource) Kind() string { return m.pageConfigSource.Kind } func (m *pageMeta) Layout() string { return m.pageConfig.Layout } func (m *pageMeta) LinkTitle() string { if m.pageConfig.LinkTitle != "" { return m.pageConfig.LinkTitle } return m.Title() } func (m *pageMeta) Name() string { if m.resourcePath != "" { return m.resourcePath } if m.Kind() == kinds.KindTerm { return m.pathInfo.Unnormalized().BaseNameNoIdentifier() } return m.Title() } func (m *pageMeta) IsNode() bool { return !m.IsPage() } func (m *pageMeta) IsPage() bool { return m.Kind() == kinds.KindPage } func (m *pageMeta) Params() maps.Params { return m.pageConfig.Params } func (m *pageMeta) Path() string { if m.IsHome() { // Base returns an empty string for the home page, // which is correct as the key to the page tree. return "/" } return m.pathInfo.Base() } func (m *pageMeta) PathInfo() *paths.Path { return m.pathInfo } func (m *pageMeta) IsSection() bool { return m.Kind() == kinds.KindSection } func (m *pageMeta) Section() string { return m.pathInfo.Section() } func (m *pageMeta) Sitemap() config.SitemapConfig { return m.pageConfig.Sitemap } func (m *pageMeta) Title() string { return m.pageConfig.Title } const defaultContentType = "page" func (m *pageMeta) Type() string { if m.pageConfig.Type != "" { return m.pageConfig.Type } if sect := m.Section(); sect != "" { return sect } return defaultContentType } func (m *pageMeta) Weight() int { return m.pageConfig.Weight } func (ps *pageState) setMetaPost(cascades *page.PageMatcherParamsConfigs) error { if ps.m.pageConfigSource.Frontmatter != nil { if ps.m.pageConfigSource.IsFromContentAdapter { ps.m.pageConfig.ContentAdapterData = xmaps.Clone(ps.m.pageConfigSource.Frontmatter) } else { ps.m.pageConfig.Params = xmaps.Clone(ps.m.pageConfigSource.Frontmatter) } } if ps.m.pageConfig.Params == nil { ps.m.pageConfig.Params = make(maps.Params) } if ps.m.pageConfigSource.IsFromContentAdapter && ps.m.pageConfig.ContentAdapterData == nil { ps.m.pageConfig.ContentAdapterData = make(maps.Params) } // Cascade defined on itself has higher priority than inherited ones. allCascades := hiter.Concat(ps.m.cascadeCompiled.All(), cascades.All()) for v := range allCascades { if !v.Target.Match(ps.Kind(), ps.Path(), ps.s.Conf.Environment(), ps.s.siteVector) { continue } for kk, vv := range v.Params { if _, found := ps.m.pageConfig.Params[kk]; !found { ps.m.pageConfig.Params[kk] = vv } } for kk, vv := range v.Fields { if ps.m.pageConfigSource.IsFromContentAdapter { if _, found := ps.m.pageConfig.ContentAdapterData[kk]; !found { ps.m.pageConfig.ContentAdapterData[kk] = vv } } else { if _, found := ps.m.pageConfig.Params[kk]; !found { ps.m.pageConfig.Params[kk] = vv } } } } if err := ps.setMetaPostParams(); err != nil { return err } if err := ps.m.applyDefaultValues(ps.s); err != nil { return err } // Store away any original values that may be changed from aggregation. ps.m.datesOriginal = ps.m.pageConfig.Dates return nil } func (ps *pageState) setMetaPostParams() error { pm := ps.m var mtime time.Time var contentBaseName string var isContentAdapter bool if ps.File() != nil { isContentAdapter = ps.File().IsContentAdapter() contentBaseName = ps.File().ContentBaseName() if ps.File().FileInfo() != nil { mtime = ps.File().FileInfo().ModTime() } } var gitAuthorDate time.Time if ps.gitInfo != nil { gitAuthorDate = ps.gitInfo.AuthorDate } descriptor := &pagemeta.FrontMatterDescriptor{ PageConfigEarly: pm.pageConfigSource, PageConfigLate: pm.pageConfig, BaseFilename: contentBaseName, ModTime: mtime, GitAuthorDate: gitAuthorDate, Location: langs.GetLocation(ps.s.Language()), PathOrTitle: ps.pathOrTitle(), } if isContentAdapter { if err := pm.pageConfig.Compile(pm.pageConfigSource, ps.s.Log, ps.s.conf.OutputFormats.Config); err != nil { return err } } pcfg := pm.pageConfig // Handle the date separately // TODO(bep) we need to "do more" in this area so this can be split up and // more easily tested without the Page, but the coupling is strong. err := ps.s.frontmatterHandler.HandleDates(descriptor) if err != nil { ps.s.Log.Errorf("Failed to handle dates for page %q: %s", ps.pathOrTitle(), err) } if isContentAdapter { // Done. return nil } var sitemapSet bool var buildConfig any var isNewBuildKeyword bool if v, ok := pcfg.Params["_build"]; ok { hugo.Deprecate("The \"_build\" front matter key", "Use \"build\" instead. See https://gohugo.io/content-management/build-options.", "0.145.0") buildConfig = v } else { buildConfig = pcfg.Params["build"] isNewBuildKeyword = true } pm.pageConfig.Build, err = pagemeta.DecodeBuildConfig(buildConfig) if err != nil { var msgDetail string if isNewBuildKeyword { msgDetail = `. We renamed the _build keyword to build in Hugo 0.123.0. We recommend putting user defined params in the params section, e.g.: --- title: "My Title" params: build: "My Build" --- ´ ` } return fmt.Errorf("failed to decode build config in front matter: %s%s", err, msgDetail) } var draft, published, isCJKLanguage *bool var userParams map[string]any for k, v := range pcfg.Params { loki := strings.ToLower(k) if loki == "params" { vv, err := maps.ToStringMapE(v) if err != nil { return err } userParams = vv delete(pcfg.Params, k) continue } if loki == "published" { // Intentionally undocumented vv, err := cast.ToBoolE(v) if err == nil { published = &vv } // published may also be a date continue } if ps.s.frontmatterHandler.IsDateKey(loki) { continue } if loki == "path" || loki == "kind" || loki == "lang" { // See issue 12484. hugo.DeprecateLevelMin(loki+" in front matter", "", "v0.144.0", logg.LevelWarn) } switch loki { case "title": pcfg.Title = cast.ToString(v) pcfg.Params[loki] = pcfg.Title case "linktitle": pcfg.LinkTitle = cast.ToString(v) pcfg.Params[loki] = pcfg.LinkTitle case "summary": pcfg.Summary = cast.ToString(v) pcfg.Params[loki] = pcfg.Summary case "description": pcfg.Description = cast.ToString(v) pcfg.Params[loki] = pcfg.Description case "slug": // Don't start or end with a - pcfg.Slug = strings.Trim(cast.ToString(v), "-") pcfg.Params[loki] = pm.Slug() case "url": url := cast.ToString(v) if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") { return fmt.Errorf("URLs with protocol (http*) not supported: %q. In page %q", url, ps.pathOrTitle()) } pcfg.URL = url pcfg.Params[loki] = url case "type": pcfg.Type = cast.ToString(v) pcfg.Params[loki] = pcfg.Type case "keywords": pcfg.Keywords = cast.ToStringSlice(v) pcfg.Params[loki] = pcfg.Keywords case "headless": // Legacy setting for leaf bundles. // This is since Hugo 0.63 handled in a more general way for all // pages. isHeadless := cast.ToBool(v) pcfg.Params[loki] = isHeadless if isHeadless { pm.pageConfig.Build.List = pagemeta.Never pm.pageConfig.Build.Render = pagemeta.Never } case "outputs": o := cast.ToStringSlice(v) // lower case names: for i, s := range o { o[i] = strings.ToLower(s) } pm.pageConfig.Outputs = o case "draft": draft = new(bool) *draft = cast.ToBool(v) case "layout": pcfg.Layout = cast.ToString(v) pcfg.Params[loki] = pcfg.Layout case "weight": pcfg.Weight = cast.ToInt(v) pcfg.Params[loki] = pcfg.Weight case "aliases": pcfg.Aliases = cast.ToStringSlice(v) for i, alias := range pcfg.Aliases { if strings.HasPrefix(alias, "http://") || strings.HasPrefix(alias, "https://") { return fmt.Errorf("http* aliases not supported: %q", alias) } pcfg.Aliases[i] = filepath.ToSlash(alias) } pcfg.Params[loki] = pcfg.Aliases case "sitemap": pcfg.Sitemap, err = config.DecodeSitemap(ps.s.conf.Sitemap, maps.ToStringMap(v)) if err != nil { return fmt.Errorf("failed to decode sitemap config in front matter: %s", err) } sitemapSet = true case "iscjklanguage": isCJKLanguage = new(bool) *isCJKLanguage = cast.ToBool(v) case "translationkey": pcfg.TranslationKey = cast.ToString(v) pcfg.Params[loki] = pcfg.TranslationKey case "resources": var resources []map[string]any handled := true switch vv := v.(type) { case []map[any]any: for _, vvv := range vv { resources = append(resources, maps.ToStringMap(vvv)) } case []map[string]any: resources = append(resources, vv...) case []any: for _, vvv := range vv { switch vvvv := vvv.(type) { case map[any]any: resources = append(resources, maps.ToStringMap(vvvv)) case map[string]any: resources = append(resources, vvvv) } } default: handled = false } if handled { pcfg.ResourcesMeta = resources break } fallthrough default: // If not one of the explicit values, store in Params switch vv := v.(type) { case []any: if len(vv) > 0 { allStrings := true for _, vvv := range vv { if _, ok := vvv.(string); !ok { allStrings = false break } } if allStrings { // We need tags, keywords etc. to be []string, not []interface{}. a := make([]string, len(vv)) for i, u := range vv { a[i] = cast.ToString(u) } pcfg.Params[loki] = a } else { pcfg.Params[loki] = vv } } else { pcfg.Params[loki] = []string{} } default: pcfg.Params[loki] = vv } } } for k, v := range userParams { pcfg.Params[strings.ToLower(k)] = v } if !sitemapSet { pcfg.Sitemap = ps.s.conf.Sitemap } if draft != nil && published != nil { pcfg.Draft = *draft ps.s.Log.Warnf("page %q has both draft and published settings in its frontmatter. Using draft.", ps.File().Filename()) } else if draft != nil { pcfg.Draft = *draft } else if published != nil { pcfg.Draft = !*published } pcfg.Params["draft"] = pcfg.Draft if isCJKLanguage != nil { pcfg.IsCJKLanguage = *isCJKLanguage } else if ps.s.conf.HasCJKLanguage && ps.m.content.pi.openSource != nil { if cjkRe.Match(ps.m.content.mustSource()) { pcfg.IsCJKLanguage = true } else { pcfg.IsCJKLanguage = false } } pcfg.Params["iscjklanguage"] = pcfg.IsCJKLanguage if err := pm.pageConfigSource.Init(false); err != nil { return err } if err := pcfg.Init(); err != nil { return err } if err := pcfg.Compile(pm.pageConfigSource, ps.s.Log, ps.s.conf.OutputFormats.Config); err != nil { return err } return nil } // shouldList returns whether this page should be included in the list of pages. // global indicates site.Pages etc. func (m *pageMeta) shouldList(global bool) bool { if m.isStandalone() { // Never list 404, sitemap and similar. return false } switch m.pageConfig.Build.List { case pagemeta.Always: return true case pagemeta.Never: return false case pagemeta.ListLocally: return !global } return false } func (m *pageMeta) shouldListAny() bool { return m.shouldList(true) || m.shouldList(false) } func (m *pageMeta) isStandalone() bool { return !m.standaloneOutputFormat.IsZero() } func (m *pageMeta) shouldBeCheckedForMenuDefinitions() bool { if !m.shouldList(false) { return false } return m.Kind() == kinds.KindHome || m.Kind() == kinds.KindSection || m.Kind() == kinds.KindPage } func (m *pageMeta) noRender() bool { return m.pageConfig.Build.Render != pagemeta.Always } func (m *pageMeta) noLink() bool { return m.pageConfig.Build.Render == pagemeta.Never } func (m *pageMeta) applyDefaultValues(s *Site) error { if m.pageConfig.Build.IsZero() { m.pageConfig.Build, _ = pagemeta.DecodeBuildConfig(nil) } if !s.conf.IsKindEnabled(m.Kind()) { (&m.pageConfig.Build).Disable() } if m.pageConfigSource.Content.Markup == "" { if m.File() != nil { // Fall back to file extension m.pageConfigSource.Content.Markup = s.ContentSpec.ResolveMarkup(m.File().Ext()) } if m.pageConfigSource.Content.Markup == "" { m.pageConfigSource.Content.Markup = "markdown" } } if m.pageConfig.Title == "" && m.f == nil { switch m.Kind() { case kinds.KindHome: m.pageConfig.Title = s.Title() case kinds.KindSection: sectionName := m.pathInfo.Unnormalized().BaseNameNoIdentifier() if s.conf.PluralizeListTitles { sectionName = flect.Pluralize(sectionName) } if s.conf.CapitalizeListTitles { sectionName = s.conf.C.CreateTitle(sectionName) } m.pageConfig.Title = sectionName case kinds.KindTerm: if m.term != "" { if s.conf.CapitalizeListTitles { m.pageConfig.Title = s.conf.C.CreateTitle(m.term) } else { m.pageConfig.Title = m.term } } else { panic("term not set") } case kinds.KindTaxonomy: if s.conf.CapitalizeListTitles { m.pageConfig.Title = strings.Replace(s.conf.C.CreateTitle(m.pathInfo.Unnormalized().BaseNameNoIdentifier()), "-", " ", -1) } else { m.pageConfig.Title = strings.Replace(m.pathInfo.Unnormalized().BaseNameNoIdentifier(), "-", " ", -1) } case kinds.KindStatus404: m.pageConfig.Title = "404 Page not found" } } return nil } func (m *pageMeta) newContentConverter(ps *pageState, markup string) (converter.Converter, error) { if ps == nil { panic("no Page provided") } cp := ps.s.ContentSpec.Converters.Get(markup) if cp == nil { return converter.NopConverter, fmt.Errorf("no content renderer found for markup %q, page: %s", markup, ps.getPageInfoForError()) } var filename string var path string if m.f != nil { filename = m.f.Filename() path = m.f.Path() } else { path = m.Path() } doc := newPageForRenderHook(ps) documentLookup := func(id uint64) any { if id == ps.pid { // This prevents infinite recursion in some cases. return doc } if v, ok := ps.pageOutput.pco.otherOutputs.Get(id); ok { return v.po.p } return nil } cpp, err := cp.New( converter.DocumentContext{ Document: doc, DocumentLookup: documentLookup, DocumentID: hashing.XxHashFromStringHexEncoded(ps.Path()), DocumentName: path, Filename: filename, }, ) if err != nil { return converter.NopConverter, err } return cpp, nil } // The output formats this page will be rendered to. func (ps *pageState) outputFormats() output.Formats { if len(ps.m.pageConfig.ConfiguredOutputFormats) > 0 { return ps.m.pageConfig.ConfiguredOutputFormats } return ps.s.conf.C.KindOutputFormats[ps.Kind()] } func (m *pageMeta) Slug() string { return m.pageConfig.Slug } func getParam(m resource.ResourceParamsProvider, key string, stringToLower bool) any { v := m.Params()[strings.ToLower(key)] if v == nil { return nil } switch val := v.(type) { case bool: return val case string: if stringToLower { return strings.ToLower(val) } return val case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return val case []string: if stringToLower { return helpers.SliceToLower(val) } return v default: return v } } func getParamToLower(m resource.ResourceParamsProvider, key string) any { return getParam(m, key, true) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/site_sections.go
hugolib/site_sections.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "github.com/gohugoio/hugo/resources/page" ) // Sections returns the top level sections. func (s *Site) Sections() page.Pages { s.CheckReady() return s.Home().Sections() } // Home is a shortcut to the home page, equivalent to .Site.GetPage "home". func (s *Site) Home() page.Page { s.CheckReady() return s.home }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/shortcode.go
hugolib/shortcode.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 hugolib import ( "bytes" "context" "errors" "fmt" "html/template" "path" "reflect" "regexp" "sort" "strconv" "strings" "sync" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hstore" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl/tplimpl" "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/common/urls" bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/tpl" ) var ( _ urls.RefLinker = (*ShortcodeWithPage)(nil) _ types.Unwrapper = (*ShortcodeWithPage)(nil) _ text.Positioner = (*ShortcodeWithPage)(nil) _ hstore.StoreProvider = (*ShortcodeWithPage)(nil) ) // ShortcodeWithPage is the "." context in a shortcode template. type ShortcodeWithPage struct { Params any Inner template.HTML Page page.Page Parent *ShortcodeWithPage Name string IsNamedParams bool // Zero-based ordinal in relation to its parent. If the parent is the page itself, // this ordinal will represent the position of this shortcode in the page content. Ordinal int // Indentation before the opening shortcode in the source. indentation string innerDeindentInit sync.Once innerDeindent template.HTML // pos is the position in bytes in the source file. Used for error logging. posInit sync.Once posOffset int pos text.Position store *hstore.Scratch } // InnerDeindent returns the (potentially de-indented) inner content of the shortcode. func (scp *ShortcodeWithPage) InnerDeindent() template.HTML { if scp.indentation == "" { return scp.Inner } scp.innerDeindentInit.Do(func() { b := bp.GetBuffer() text.VisitLinesAfter(string(scp.Inner), func(s string) { if after, ok := strings.CutPrefix(s, scp.indentation); ok { b.WriteString(after) } else { b.WriteString(s) } }) scp.innerDeindent = template.HTML(b.String()) bp.PutBuffer(b) }) return scp.innerDeindent } // Position returns this shortcode's detailed position. Note that this information // may be expensive to calculate, so only use this in error situations. func (scp *ShortcodeWithPage) Position() text.Position { scp.posInit.Do(func() { if p, ok := mustUnwrapPage(scp.Page).(pageContext); ok { scp.pos = p.posOffset(scp.posOffset) } }) return scp.pos } // Site returns information about the current site. func (scp *ShortcodeWithPage) Site() page.Site { return scp.Page.Site() } // Ref is a shortcut to the Ref method on Page. It passes itself as a context // to get better error messages. func (scp *ShortcodeWithPage) Ref(args map[string]any) (string, error) { return scp.Page.RefFrom(args, scp) } // RelRef is a shortcut to the RelRef method on Page. It passes itself as a context // to get better error messages. func (scp *ShortcodeWithPage) RelRef(args map[string]any) (string, error) { return scp.Page.RelRefFrom(args, scp) } // Store returns this shortcode's Store. func (scp *ShortcodeWithPage) Store() *hstore.Scratch { if scp.store == nil { scp.store = hstore.NewScratch() } return scp.store } // Scratch returns a scratch-pad scoped for this shortcode. This can be used // as a temporary storage for variables, counters etc. // Deprecated: Use Store instead. Note that from the templates this should be considered a "soft deprecation". func (scp *ShortcodeWithPage) Scratch() *hstore.Scratch { return scp.Store() } // Get is a convenience method to look up shortcode parameters by its key. func (scp *ShortcodeWithPage) Get(key any) any { if scp.Params == nil { return nil } if reflect.ValueOf(scp.Params).Len() == 0 { return nil } var x reflect.Value switch key.(type) { case int64, int32, int16, int8, int: if reflect.TypeOf(scp.Params).Kind() == reflect.Map { // We treat this as a non error, so people can do similar to // {{ $myParam := .Get "myParam" | default .Get 0 }} // Without having to do additional checks. return nil } else if reflect.TypeOf(scp.Params).Kind() == reflect.Slice { idx := int(reflect.ValueOf(key).Int()) ln := reflect.ValueOf(scp.Params).Len() if idx > ln-1 { return "" } x = reflect.ValueOf(scp.Params).Index(idx) } case string: if reflect.TypeOf(scp.Params).Kind() == reflect.Map { x = reflect.ValueOf(scp.Params).MapIndex(reflect.ValueOf(key)) if !x.IsValid() { return "" } } else if reflect.TypeOf(scp.Params).Kind() == reflect.Slice { // We treat this as a non error, so people can do similar to // {{ $myParam := .Get "myParam" | default .Get 0 }} // Without having to do additional checks. return nil } } return x.Interface() } // For internal use only. func (scp *ShortcodeWithPage) Unwrapv() any { return scp.Page } // Note - this value must not contain any markup syntax const shortcodePlaceholderPrefix = "HAHAHUGOSHORTCODE" func createShortcodePlaceholder(sid string, id, ordinal uint64) string { return shortcodePlaceholderPrefix + strconv.FormatUint(id, 10) + sid + strconv.FormatUint(ordinal, 10) + "HBHB" } type shortcode struct { name string isInline bool // inline shortcode. Any inner will be a Go template. isClosing bool // whether a closing tag was provided inner []any // string or nested shortcode params any // map or array ordinal int indentation string // indentation from source. templ *tplimpl.TemplInfo // If set, the rendered shortcode is sent as part of the surrounding content // to Goldmark and similar. // Before Hug0 0.55 we didn't send any shortcode output to the markup // renderer, and this flag told Hugo to process the {{ .Inner }} content // separately. // The old behavior can be had by starting your shortcode template with: // {{ $_hugo_config := `{ "version": 1 }`}} doMarkup bool // the placeholder in the source when passed to Goldmark etc. // This also identifies the rendered shortcode. placeholder string pos int // the position in bytes in the source file length int // the length in bytes in the source file } func (s shortcode) insertPlaceholder() bool { return !s.doMarkup || s.configVersion() == 1 } func (s shortcode) needsInner() bool { return s.templ != nil && s.templ.ParseInfo.IsInner } func (s shortcode) configVersion() int { if s.templ == nil { // Not set for inline shortcodes. return 2 } return s.templ.ParseInfo.Config.Version } func (s shortcode) innerString() string { var sb strings.Builder for _, inner := range s.inner { sb.WriteString(inner.(string)) } return sb.String() } func (sc shortcode) String() string { // for testing (mostly), so any change here will break tests! var params any switch v := sc.params.(type) { case map[string]any: // sort the keys so test assertions won't fail var keys []string for k := range v { keys = append(keys, k) } sort.Strings(keys) tmp := make(map[string]any) for _, k := range keys { tmp[k] = v[k] } params = tmp default: // use it as is params = sc.params } return fmt.Sprintf("%s(%q, %t){%s}", sc.name, params, sc.doMarkup, sc.inner) } // shared between all pages from the same source file. type shortcodeParseInfo struct { filename string firstTemplateStore *tplimpl.TemplateStore // This represents the first site and must not be used for execution. // Ordered list of shortcodes. shortcodes []*shortcode // All the shortcode names in this set. nameSetMu sync.RWMutex nameSet map[string]bool // Configuration enableInlineShortcodes bool } func (s *shortcodeParseInfo) addName(name string) { s.nameSetMu.Lock() defer s.nameSetMu.Unlock() s.nameSet[name] = true } func (s *shortcodeParseInfo) hasName(name string) bool { s.nameSetMu.RLock() defer s.nameSetMu.RUnlock() _, ok := s.nameSet[name] return ok } func newShortcodeHandler(filename string, d *deps.Deps) *shortcodeParseInfo { sh := &shortcodeParseInfo{ filename: filename, firstTemplateStore: d.TemplateStore, enableInlineShortcodes: d.ExecHelper.Sec().EnableInlineShortcodes, shortcodes: make([]*shortcode, 0, 4), nameSet: make(map[string]bool), } return sh } const ( innerNewlineRegexp = "\n" innerCleanupRegexp = `\A<p>(.*)</p>\n\z` innerCleanupExpand = "$1" ) func prepareShortcode( level int, sc *shortcode, parent *ShortcodeWithPage, po *pageOutput, isRenderString bool, ) (shortcodeRenderer, error) { p := po.p toParseErr := func(err error) error { source := p.m.content.mustSource() return p.parseError(fmt.Errorf("failed to render shortcode %q: %w", sc.name, err), source, sc.pos) } // Allow the caller to delay the rendering of the shortcode if needed. var fn shortcodeRenderFunc = func(ctx context.Context) ([]byte, bool, error) { if p.m.pageConfigSource.ContentMediaType.IsMarkdown() && sc.doMarkup { // Signal downwards that the content rendered will be // parsed and rendered by Goldmark. ctx = tpl.Context.IsInGoldmark.Set(ctx, true) } r, err := doRenderShortcode(ctx, level, po.p.s.TemplateStore, sc, parent, po, isRenderString) if err != nil { return nil, false, toParseErr(err) } b, hasVariants, err := r.renderShortcode(ctx) if err != nil { return nil, false, toParseErr(err) } return b, hasVariants, nil } return fn, nil } func doRenderShortcode( ctx context.Context, level int, ts *tplimpl.TemplateStore, sc *shortcode, parent *ShortcodeWithPage, po *pageOutput, isRenderString bool, ) (shortcodeRenderer, error) { var tmpl *tplimpl.TemplInfo p := po.p // Tracks whether this shortcode or any of its children has template variations // in other languages or output formats. We are currently only interested in // the output formats. var hasVariants bool if sc.isInline { if !p.s.ExecHelper.Sec().EnableInlineShortcodes { return zeroShortcode, nil } templatePath := path.Join("_inline_shortcode", p.Path(), sc.name) if sc.isClosing { templStr := sc.innerString() var err error tmpl, err = ts.TextParse(templatePath, templStr) if err != nil { if isRenderString { return zeroShortcode, p.wrapError(err) } fe := herrors.NewFileErrorFromName(err, p.File().Filename()) pos := fe.Position() pos.LineNumber += p.posOffset(sc.pos).LineNumber fe = fe.UpdatePosition(pos) return zeroShortcode, p.wrapError(fe) } } else { // Re-use of shortcode defined earlier in the same page. tmpl = ts.TextLookup(templatePath) if tmpl == nil { return zeroShortcode, fmt.Errorf("no earlier definition of shortcode %q found", sc.name) } } } else { ofCount := map[string]int{} include := func(match *tplimpl.TemplInfo) bool { ofCount[match.D.OutputFormat]++ return true } base, layoutDescriptor := po.GetInternalTemplateBasePathAndDescriptor() // With shortcodes/mymarkdown.md (only), this allows {{% mymarkdown %}} when rendering HTML, // but will not resolve any template when doing {{< mymarkdown >}}. layoutDescriptor.AlwaysAllowPlainText = sc.doMarkup q := tplimpl.TemplateQuery{ Path: base, Name: sc.name, Category: tplimpl.CategoryShortcode, Desc: layoutDescriptor, Sites: p.s.siteVector, Consider: include, } v, err := ts.LookupShortcode(q) if v == nil { return zeroShortcode, err } tmpl = v hasVariants = hasVariants || len(ofCount) > 1 } data := &ShortcodeWithPage{ Ordinal: sc.ordinal, posOffset: sc.pos, indentation: sc.indentation, Params: sc.params, Page: newPageForShortcode(p), Parent: parent, Name: sc.name, } if sc.params != nil { data.IsNamedParams = reflect.TypeOf(sc.params).Kind() == reflect.Map } if len(sc.inner) > 0 { var inner string for _, innerData := range sc.inner { switch innerData := innerData.(type) { case string: inner += innerData case *shortcode: s, err := prepareShortcode(level+1, innerData, data, po, isRenderString) if err != nil { return zeroShortcode, err } ss, more, err := s.renderShortcodeString(ctx) hasVariants = hasVariants || more if err != nil { return zeroShortcode, err } inner += ss default: po.p.s.Log.Errorf("Illegal state on shortcode rendering of %q in page %q. Illegal type in inner data: %s ", sc.name, p.File().Path(), reflect.TypeOf(innerData)) return zeroShortcode, nil } } // Pre Hugo 0.55 this was the behavior even for the outer-most // shortcode. if sc.doMarkup && (level > 0 || sc.configVersion() == 1) { var err error b, err := p.pageOutput.contentRenderer.ParseAndRenderContent(ctx, []byte(inner), false) if err != nil { return zeroShortcode, err } newInner := b.Bytes() // If the type is “” (unknown) or “markdown”, we assume the markdown // generation has been performed. Given the input: `a line`, markdown // specifies the HTML `<p>a line</p>\n`. When dealing with documents as a // whole, this is OK. When dealing with an `{{ .Inner }}` block in Hugo, // this is not so good. This code does two things: // // 1. Check to see if inner has a newline in it. If so, the Inner data is // unchanged. // 2 If inner does not have a newline, strip the wrapping <p> block and // the newline. switch p.m.pageConfigSource.Content.Markup { case "", "markdown": if match, _ := regexp.MatchString(innerNewlineRegexp, inner); !match { cleaner, err := regexp.Compile(innerCleanupRegexp) if err == nil { newInner = cleaner.ReplaceAll(newInner, []byte(innerCleanupExpand)) } } } // TODO(bep) we may have plain text inner templates. data.Inner = template.HTML(newInner) } else { data.Inner = template.HTML(inner) } } result, err := renderShortcodeWithPage(ctx, ts, tmpl, data) if err != nil && sc.isInline { fe := herrors.NewFileErrorFromName(err, p.File().Filename()) pos := fe.Position() pos.LineNumber += p.posOffset(sc.pos).LineNumber fe = fe.UpdatePosition(pos) return zeroShortcode, fe } if len(sc.inner) == 0 && len(sc.indentation) > 0 { b := bp.GetBuffer() i := 0 text.VisitLinesAfter(result, func(line string) { // The first line is correctly indented. if i > 0 { b.WriteString(sc.indentation) } i++ b.WriteString(line) }) result = b.String() bp.PutBuffer(b) } return prerenderedShortcode{s: result, hasVariants: hasVariants}, err } func (s *shortcodeParseInfo) prepareShortcodesForPage(po *pageOutput, isRenderString bool) (map[string]shortcodeRenderer, error) { rendered := make(map[string]shortcodeRenderer) for _, v := range s.shortcodes { s, err := prepareShortcode(0, v, nil, po, isRenderString) if err != nil { return nil, err } rendered[v.placeholder] = s } return rendered, nil } func posFromInput(filename string, input []byte, offset int) text.Position { if offset < 0 { return text.Position{ Filename: filename, } } lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: filename, LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } // pageTokens state: // - before: positioned just before the shortcode start // - after: shortcode(s) consumed (plural when they are nested) func (s *shortcodeParseInfo) extractShortcode(ordinal, level int, source []byte, pt *pageparser.Iterator) (*shortcode, error) { if s == nil { panic("handler nil") } sc := &shortcode{ordinal: ordinal} // Back up one to identify any indentation. if pt.Pos() > 0 { pt.Backup() item := pt.Next() if item.IsIndentation() { sc.indentation = item.ValStr(source) } } cnt := 0 nestedOrdinal := 0 nextLevel := level + 1 closed := false const errorPrefix = "failed to extract shortcode" Loop: for { currItem := pt.Next() switch { case currItem.IsLeftShortcodeDelim(): next := pt.Peek() if next.IsRightShortcodeDelim() { // no name: {{< >}} or {{% %}} return sc, errors.New("shortcode has no name") } if next.IsShortcodeClose() { continue } if cnt > 0 { // nested shortcode; append it to inner content pt.Backup() nested, err := s.extractShortcode(nestedOrdinal, nextLevel, source, pt) nestedOrdinal++ if nested != nil && nested.name != "" { s.addName(nested.name) } if err == nil { sc.inner = append(sc.inner, nested) } else { return sc, err } } else { sc.doMarkup = currItem.IsShortcodeMarkupDelimiter() } cnt++ case currItem.IsRightShortcodeDelim(): // we trust the template on this: // if there's no inner, we're done if !sc.isInline { if !sc.templ.ParseInfo.IsInner { return sc, nil } } case currItem.IsShortcodeClose(): closed = true next := pt.Peek() if !sc.isInline { if !sc.needsInner() { if next.IsError() { // return that error, more specific continue } name := sc.name if name == "" { name = next.ValStr(source) } return nil, fmt.Errorf("%s: shortcode %q does not evaluate .Inner or .InnerDeindent, yet a closing tag was provided", errorPrefix, name) } } if next.IsRightShortcodeDelim() { // self-closing pt.Consume(1) } else { sc.isClosing = true pt.Consume(2) } return sc, nil case currItem.IsText(): sc.inner = append(sc.inner, currItem.ValStr(source)) case currItem.IsShortcodeName(): sc.name = currItem.ValStr(source) // Used to check if the template expects inner content, // so just pick one arbitrarily with the same name. templ := s.firstTemplateStore.LookupShortcodeByName(sc.name) if templ == nil { return nil, fmt.Errorf("%s: template for shortcode %q not found", errorPrefix, sc.name) } sc.templ = templ case currItem.IsInlineShortcodeName(): sc.name = currItem.ValStr(source) sc.isInline = true case currItem.IsShortcodeParam(): if !pt.IsValueNext() { continue } else if pt.Peek().IsShortcodeParamVal() { // named params if sc.params == nil { params := make(map[string]any) params[currItem.ValStr(source)] = pt.Next().ValTyped(source) sc.params = params } else { if params, ok := sc.params.(map[string]any); ok { params[currItem.ValStr(source)] = pt.Next().ValTyped(source) } else { return sc, fmt.Errorf("%s: invalid state: invalid param type %T for shortcode %q, expected a map", errorPrefix, params, sc.name) } } } else { // positional params if sc.params == nil { var params []any params = append(params, currItem.ValTyped(source)) sc.params = params } else { if params, ok := sc.params.([]any); ok { params = append(params, currItem.ValTyped(source)) sc.params = params } else { return sc, fmt.Errorf("%s: invalid state: invalid param type %T for shortcode %q, expected a slice", errorPrefix, params, sc.name) } } } case currItem.IsDone(): if !currItem.IsError() { if !closed && sc.needsInner() { return sc, fmt.Errorf("%s: shortcode %q must be closed or self-closed", errorPrefix, sc.name) } } // handled by caller pt.Backup() break Loop } } return sc, nil } // Replace prefixed shortcode tokens with the real content. // Note: This function will rewrite the input slice. func expandShortcodeTokens( ctx context.Context, source []byte, tokenHandler func(ctx context.Context, token string) ([]byte, error), ) ([]byte, error) { start := 0 pre := []byte(shortcodePlaceholderPrefix) post := []byte("HBHB") pStart := []byte("<p>") pEnd := []byte("</p>") k := bytes.Index(source[start:], pre) for k != -1 { j := start + k postIdx := bytes.Index(source[j:], post) if postIdx < 0 { // this should never happen, but let the caller decide to panic or not return nil, errors.New("illegal state in content; shortcode token missing end delim") } end := j + postIdx + 4 key := string(source[j:end]) newVal, err := tokenHandler(ctx, key) if err != nil { return nil, err } // Issue #1148: Check for wrapping p-tags <p> if j >= 3 && bytes.Equal(source[j-3:j], pStart) { if (k+4) < len(source) && bytes.Equal(source[end:end+4], pEnd) { j -= 3 end += 4 } } // This and other cool slice tricks: https://github.com/golang/go/wiki/SliceTricks source = append(source[:j], append(newVal, source[end:]...)...) start = j k = bytes.Index(source[start:], pre) } return source, nil } func renderShortcodeWithPage(ctx context.Context, h *tplimpl.TemplateStore, tmpl *tplimpl.TemplInfo, data *ShortcodeWithPage) (string, error) { buffer := bp.GetBuffer() defer bp.PutBuffer(buffer) err := h.ExecuteWithContext(ctx, tmpl, buffer, data) if err != nil { return "", fmt.Errorf("failed to process shortcode: %w", err) } return buffer.String(), nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/content_map_page_assembler.go
hugolib/content_map_page_assembler.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 hugolib import ( "cmp" "context" "fmt" "path" "strings" "time" "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugolib/doctree" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/spf13/cast" "golang.org/x/sync/errgroup" ) // Handles the flow of creating all the pages and resources for all sites. // This includes applying any cascade configuration passed down the tree. type allPagesAssembler struct { // Dependencies. ctx context.Context h *HugoSites m *pageMap g errgroup.Group assembleChanges *WhatChanged assembleSectionsInParallel bool pwRoot *doctree.NodeShiftTreeWalker[contentNode] // walks pages. rwRoot *doctree.NodeShiftTreeWalker[contentNode] // walks resources. // Walking state. seenTerms *maps.Map[term, sitesmatrix.Vectors] droppedPages *maps.Map[*Site, []string] // e.g. drafts, expired, future. seenRootSections *maps.Map[string, bool] seenHome bool // set before we fan out to multiple goroutines. } func newAllPagesAssembler( ctx context.Context, h *HugoSites, m *pageMap, assembleChanges *WhatChanged, ) *allPagesAssembler { rw := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: m.treeResources, LockType: doctree.LockTypeNone, NoShift: true, WalkContext: &doctree.WalkContext[contentNode]{}, } pw := rw.Extend() pw.Tree = m.treePages seenRootSections := maps.NewMap[string, bool]() seenRootSections.Set("", true) // home. return &allPagesAssembler{ ctx: ctx, h: h, m: m, assembleChanges: assembleChanges, seenTerms: maps.NewMap[term, sitesmatrix.Vectors](), droppedPages: maps.NewMap[*Site, []string](), seenRootSections: seenRootSections, assembleSectionsInParallel: true, pwRoot: pw, rwRoot: rw, } } type sitePagesAssembler struct { s *Site assembleChanges *WhatChanged a *allPagesAssembler ctx context.Context } func (a *allPagesAssembler) createAllPages() error { defer func() { for site, dropped := range a.droppedPages.All() { for _, s := range dropped { site.pageMap.treePages.Delete(s) site.pageMap.resourceTrees.DeletePrefix(paths.AddTrailingSlash(s)) } } }() if a.h.Conf.Watching() { defer func() { if a.h.isRebuild() && a.h.previousSeenTerms != nil { // Find removed terms. for t := range a.h.previousSeenTerms.All() { if _, found := a.seenTerms.Lookup(t); !found { // This term has been removed. a.pwRoot.Tree.Delete(t.view.pluralTreeKey) a.rwRoot.Tree.DeletePrefix(t.view.pluralTreeKey + "/") } } // Find new terms. for t := range a.seenTerms.All() { if _, found := a.h.previousSeenTerms.Lookup(t); !found { // This term is new. if n, ok := a.pwRoot.Tree.GetRaw(t.view.pluralTreeKey); ok { a.assembleChanges.Add(cnh.GetIdentity(n)) } } } } a.h.previousSeenTerms = a.seenTerms }() } if err := cmp.Or(a.doCreatePages("", 0), a.g.Wait()); err != nil { return err } if err := a.pwRoot.WalkContext.HandleEventsAndHooks(); err != nil { return err } return nil } func (a *allPagesAssembler) doCreatePages(prefix string, depth int) error { var ( sites = a.h.sitesVersionsRolesMap h = a.h treePages = a.m.treePages getViews = func(vec sitesmatrix.Vector) []viewName { return h.languageSiteForSiteVector(vec).pageMap.cfg.taxonomyConfig.views } pw *doctree.NodeShiftTreeWalker[contentNode] // walks pages. rw *doctree.NodeShiftTreeWalker[contentNode] // walks resources. isRootWalk = depth == 0 ) if isRootWalk { pw = a.pwRoot rw = a.rwRoot } else { // Sub-walkers for a specific prefix. pw = a.pwRoot.Extend() pw.Prefix = prefix + "/" rw = a.rwRoot.Extend() // rw will get its prefix(es) set later. } resourceOwnerInfo := struct { n contentNode s string }{} newHomePageMetaSource := func() *pageMetaSource { pi := a.h.Conf.PathParser().Parse(files.ComponentFolderContent, "/_index.md") return &pageMetaSource{ pathInfo: pi, sitesMatrixBase: a.h.Conf.AllSitesMatrix(), sitesMatrixBaseOnly: true, pageConfigSource: &pagemeta.PageConfigEarly{ Kind: kinds.KindHome, }, } } if isRootWalk { if err := a.createMissingPages(); err != nil { return err } if treePages.Len() == 0 { // No pages, insert a home page to get something to walk on. p := newHomePageMetaSource() treePages.InsertRaw(p.pathInfo.Base(), p) } } getCascades := func(wctx *doctree.WalkContext[contentNode], s string) *page.PageMatcherParamsConfigs { if wctx == nil { panic("nil walk context") } var cascades *page.PageMatcherParamsConfigs data := wctx.Data() if s != "" { _, data := data.LongestPrefix(s) if data != nil { cascades = data.(*page.PageMatcherParamsConfigs) } } if cascades == nil { for s := range a.h.allSiteLanguages(nil) { cascades = cascades.Append(s.conf.Cascade) } } return cascades } doTransformPages := func(s string, n contentNode, cascades *page.PageMatcherParamsConfigs) (n2 contentNode, ns doctree.NodeTransformState, err error) { defer func() { cascadesLen := cascades.Len() if n2 == nil { if ns < doctree.NodeTransformStateSkip { ns = doctree.NodeTransformStateSkip } } else { n2.forEeachContentNode( func(vec sitesmatrix.Vector, nn contentNode) bool { if pms, ok := nn.(contentNodeCascadeProvider); ok { cascades = cascades.Prepend(pms.getCascade()) } return true }, ) } if s == "" || cascades.Len() > cascadesLen { // New cascade values added, pass them downwards. rw.WalkContext.Data().Insert(paths.AddTrailingSlash(s), cascades) } }() var handlePageMetaSource func(v contentNode, n contentNodesMap, replaceVector bool) (n2 contentNode, err error) handlePageMetaSource = func(v contentNode, n contentNodesMap, replaceVector bool) (n2 contentNode, err error) { if n != nil { n2 = n } switch ms := v.(type) { case *pageMetaSource: if err := ms.initEarly(a.h, cascades); err != nil { return nil, err } sitesMatrix := ms.pageConfigSource.SitesMatrix sitesMatrix.ForEachVector(func(vec sitesmatrix.Vector) bool { site, found := sites[vec] if !found { panic(fmt.Sprintf("site not found for %v", vec)) } var p *pageState p, err = site.newPageFromPageMetasource(ms, cascades) if err != nil { return false } var drop bool if !site.shouldBuild(p) { switch p.Kind() { case kinds.KindHome, kinds.KindSection, kinds.KindTaxonomy: // We need to keep these for the structure, but disable // them so they don't get listed/rendered. (&p.m.pageConfig.Build).Disable() default: // Skip this page. a.droppedPages.WithWriteLock( func(m map[*Site][]string) error { m[site] = append(m[site], s) return nil }, ) drop = true } } if !drop && n == nil { if n2 == nil { // Avoid creating a map for one node. n2 = p } else { // Upgrade to a map. n = make(contentNodesMap) ps := n2.(*pageState) n[ps.s.siteVector] = ps n2 = n } } if n == nil { return true } pp, found := n[vec] var w1, w2 int if wp, ok := pp.(contentNodeContentWeightProvider); ok { w1 = wp.contentWeight() } w2 = p.contentWeight() if found && !replaceVector && w1 > w2 { return true } n[vec] = p return true }) case *pageState: if n == nil { n2 = ms return } n[ms.s.siteVector] = ms case contentNodesMap: for _, vv := range ms { var err error n2, err = handlePageMetaSource(vv, n, replaceVector) if err != nil { return nil, err } if m, ok := n2.(contentNodesMap); ok { n = m } } default: panic(fmt.Sprintf("unexpected type %T", v)) } return } // The common case. ns = doctree.NodeTransformStateReplaced handleContentNodeSeq := func(v contentNodeSeq) (contentNode, doctree.NodeTransformState, error) { is := make(contentNodesMap) for ms := range v { _, err := handlePageMetaSource(ms, is, false) if err != nil { return nil, 0, fmt.Errorf("failed to create page from pageMetaSource %s: %w", s, err) } } return is, ns, nil } switch v := n.(type) { case contentNodeSeq, contentNodes: return handleContentNodeSeq(contentNodeToSeq(v)) case *pageMetaSource: n2, err = handlePageMetaSource(v, nil, false) if err != nil { return nil, 0, fmt.Errorf("failed to create page from pageMetaSource %s: %w", s, err) } return case *pageState: // Nothing to do. ns = doctree.NodeTransformStateNone return v, ns, nil case contentNodesMap: ns = doctree.NodeTransformStateNone for _, vv := range v { switch m := vv.(type) { case *pageMetaSource: ns = doctree.NodeTransformStateUpdated _, err := handlePageMetaSource(m, v, true) if err != nil { return nil, 0, fmt.Errorf("failed to create page from pageMetaSource %s: %w", s, err) } default: // Nothing to do. } } return v, ns, nil default: panic(fmt.Sprintf("unexpected type %T", n)) } } var unpackPageMetaSources func(n contentNode) contentNode unpackPageMetaSources = func(n contentNode) contentNode { switch nn := n.(type) { case *pageState: return nn.m.pageMetaSource case contentNodesMap: if len(nn) == 0 { return nil } var iter contentNodeSeq = func(yield func(contentNode) bool) { seen := map[*pageMetaSource]struct{}{} for _, v := range nn { vv := unpackPageMetaSources(v) pms := vv.(*pageMetaSource) if _, found := seen[pms]; !found { if !yield(pms) { return } seen[pms] = struct{}{} } } } return iter case contentNodes: if len(nn) == 0 { return nil } var iter contentNodeSeq = func(yield func(contentNode) bool) { seen := map[*pageMetaSource]struct{}{} for _, v := range nn { vv := unpackPageMetaSources(v) pms := vv.(*pageMetaSource) if _, found := seen[pms]; !found { if !yield(pms) { return } seen[pms] = struct{}{} } } } return iter case *pageMetaSource: return nn default: panic(fmt.Sprintf("unexpected type %T", n)) } } transformPages := func(s string, n contentNode, cascades *page.PageMatcherParamsConfigs) (n2 contentNode, ns doctree.NodeTransformState, err error) { if a.h.isRebuild() { cascadesPrevious := getCascades(h.previousPageTreesWalkContext, s) h1, h2 := cascadesPrevious.SourceHash(), cascades.SourceHash() if h1 != h2 { // Force rebuild from the source. n = unpackPageMetaSources(n) } } if n == nil { panic("nil node") } n2, ns, err = doTransformPages(s, n, cascades) return } transformPagesAndCreateMissingHome := func(s string, n contentNode, isResource bool, cascades *page.PageMatcherParamsConfigs) (n2 contentNode, ns doctree.NodeTransformState, err error) { if n == nil { panic("nil node " + s) } level := strings.Count(s, "/") if s == "" { a.seenHome = true } if !isResource && s != "" && !a.seenHome { a.seenHome = true var homePages contentNode homePages, ns, err = transformPages("", newHomePageMetaSource(), cascades) if err != nil { return } treePages.InsertRaw("", homePages) } n2, ns, err = transformPages(s, n, cascades) if err != nil || ns >= doctree.NodeTransformStateSkip { return } if n2 == nil { ns = doctree.NodeTransformStateSkip return } if isResource { // Done. return } isTaxonomy := !a.h.getFirstTaxonomyConfig(s).IsZero() isRootSection := !isTaxonomy && level == 1 && cnh.isBranchNode(n) if isRootSection { // This is a root section. a.seenRootSections.SetIfAbsent(cnh.PathInfo(n).Section(), true) } else if !isTaxonomy { p := cnh.PathInfo(n) rootSection := p.Section() _, err := a.seenRootSections.GetOrCreate(rootSection, func() (bool, error) { // Try to preserve the original casing if possible. sectionUnnormalized := p.Unnormalized().Section() rootSectionPath := a.h.Conf.PathParser().Parse(files.ComponentFolderContent, "/"+sectionUnnormalized+"/_index.md") var rootSectionPages contentNode rootSectionPages, _, err = transformPages(rootSectionPath.Base(), &pageMetaSource{ pathInfo: rootSectionPath, sitesMatrixBase: n2.(contentNodeForSites).siteVectors(), pageConfigSource: &pagemeta.PageConfigEarly{ Kind: kinds.KindSection, }, }, cascades) if err != nil { return true, err } treePages.InsertRaw(rootSectionPath.Base(), rootSectionPages) return true, nil }) if err != nil { return nil, 0, err } } const eventNameSitesMatrix = "sitesmatrix" if s == "" || isRootSection { // Every page needs a home and a root section (.FirstSection). // We don't know yet what language, version, role combination that will // be created below, so collect that information and create the missing pages // on demand. nm, replaced := contentNodeToContentNodesPage(n2) missingVectorsForHomeOrRootSection := sitesmatrix.Vectors{} if s == "" { // We need a complete set of home pages. a.h.Conf.AllSitesMatrix().ForEachVector(func(vec sitesmatrix.Vector) bool { if _, found := nm[vec]; !found { missingVectorsForHomeOrRootSection[vec] = struct{}{} } return true }) } else { pw.WalkContext.AddEventListener(eventNameSitesMatrix, s, func(e *doctree.Event[contentNode]) { n := e.Source e.StopPropagation() n.forEeachContentNode( func(vec sitesmatrix.Vector, nn contentNode) bool { if _, found := nm[vec]; !found { missingVectorsForHomeOrRootSection[vec] = struct{}{} } return true }) }, ) } // We need to wait until after the walk to have a complete set. pw.WalkContext.HooksPost().Push( func() error { if i := len(missingVectorsForHomeOrRootSection); i > 0 { // Pick one, the rest will be created later. vec := missingVectorsForHomeOrRootSection.VectorSample() kind := kinds.KindSection if s == "" { kind = kinds.KindHome } pms := &pageMetaSource{ pathInfo: cnh.PathInfo(n), sitesMatrixBase: missingVectorsForHomeOrRootSection, sitesMatrixBaseOnly: true, pageConfigSource: &pagemeta.PageConfigEarly{ Kind: kind, }, } nm[vec] = pms _, ns, err := transformPages(s, nm, cascades) if err != nil { return err } if ns == doctree.NodeTransformStateReplaced { // Should not happen. panic(fmt.Sprintf("expected no replacement for %q", s)) } if replaced { pw.Tree.InsertRaw(s, nm) } } return nil }, ) } if s != "" { rw.WalkContext.SendEvent(&doctree.Event[contentNode]{Source: n2, Path: s, Name: eventNameSitesMatrix}) } return } transformPagesAndCreateMissingStructuralNodes := func(s string, n contentNode, isResource bool) (n2 contentNode, ns doctree.NodeTransformState, err error) { cascades := getCascades(pw.WalkContext, s) n2, ns, err = transformPagesAndCreateMissingHome(s, n, isResource, cascades) if err != nil || ns >= doctree.NodeTransformStateSkip { return } n2.forEeachContentNode( func(vec sitesmatrix.Vector, nn contentNode) bool { if ps, ok := nn.(*pageState); ok { if ps.m.noLink() { return true } for _, viewName := range getViews(vec) { vals := types.ToStringSlicePreserveString(getParam(ps, viewName.plural, false)) if vals == nil { continue } for _, v := range vals { if v == "" { continue } t := term{view: viewName, term: v} a.seenTerms.WithWriteLock(func(m map[term]sitesmatrix.Vectors) error { vectors, found := m[t] if !found { m[t] = sitesmatrix.Vectors{ vec: struct{}{}, } return nil } vectors[vec] = struct{}{} return nil }) } } } return true }, ) return } shouldSkipOrTerminate := func(s string) (ns doctree.NodeTransformState) { owner := resourceOwnerInfo.n if owner == nil { return doctree.NodeTransformStateTerminate } if !cnh.isBranchNode(owner) { return } // A resourceKey always represents a filename with extension. // A page key points to the logical path of a page, which when sourced from the filesystem // may represent a directory (bundles) or a single content file (e.g. p1.md). // So, to avoid any overlapping ambiguity, we start looking from the owning directory. for { s = path.Dir(s) ownerKey, found := treePages.LongestPrefixRaw(s) if !found { return doctree.NodeTransformStateTerminate } if ownerKey == resourceOwnerInfo.s { break } if s != ownerKey && strings.HasPrefix(s, ownerKey) { // Keep looking continue } // Stop walking downwards, someone else owns this resource. rw.SkipPrefix(ownerKey + "/") return doctree.NodeTransformStateSkip } return } forEeachResourceOwnerPage := func(fn func(p *pageState) bool) bool { switch nn := resourceOwnerInfo.n.(type) { case *pageState: return fn(nn) case contentNodesMap: for _, p := range nn { if !fn(p.(*pageState)) { return false } } default: panic(fmt.Sprintf("unknown type %T", nn)) } return true } rw.Transform = func(s string, n contentNode) (n2 contentNode, ns doctree.NodeTransformState, err error) { if ns = shouldSkipOrTerminate(s); ns >= doctree.NodeTransformStateSkip { return } if cnh.isPageNode(n) { return transformPagesAndCreateMissingStructuralNodes(s, n, true) } nodes := make(contentNodesMap) ns = doctree.NodeTransformStateReplaced n2 = nodes forEeachResourceOwnerPage( func(p *pageState) bool { duplicateResourceFiles := a.h.Cfg.IsMultihost() if !duplicateResourceFiles && p.m.pageConfigSource.ContentMediaType.IsMarkdown() { duplicateResourceFiles = p.s.ContentSpec.Converters.GetMarkupConfig().Goldmark.DuplicateResourceFiles } if _, found := nodes[p.s.siteVector]; !found { var rs *resourceSource match := cnh.findContentNodeForSiteVector(p.s.siteVector, duplicateResourceFiles, contentNodeToSeq(n)) if match == nil { return true } rs = match.(*resourceSource) if rs != nil { if rs.state == resourceStateNew { nodes[p.s.siteVector] = rs.assignSiteVector(p.s.siteVector) } else { nodes[p.s.siteVector] = rs.clone().assignSiteVector(p.s.siteVector) } } } return true }, ) return } // Create missing term pages. pw.WalkContext.HooksPost().Push( func() error { for k, v := range a.seenTerms.All() { viewTermKey := "/" + k.view.plural + "/" + k.term pi := a.h.Conf.PathParser().Parse(files.ComponentFolderContent, viewTermKey+"/_index.md") termKey := pi.Base() n, found := pw.Tree.GetRaw(termKey) if found { // Merge. n.forEeachContentNode( func(vec sitesmatrix.Vector, nn contentNode) bool { delete(v, vec) return true }, ) } if len(v) > 0 { p := &pageMetaSource{ pathInfo: pi, sitesMatrixBase: v, pageConfigSource: &pagemeta.PageConfigEarly{ Kind: kinds.KindTerm, }, } var n2 contentNode = p if found { n2 = contentNodes{n, p} } n2, ns, err := transformPages(termKey, n2, getCascades(pw.WalkContext, termKey)) if err != nil { return fmt.Errorf("failed to create term page %q: %w", termKey, err) } switch ns { case doctree.NodeTransformStateReplaced: pw.Tree.InsertRaw(termKey, n2) } } } return nil }, ) pw.Transform = func(s string, n contentNode) (n2 contentNode, ns doctree.NodeTransformState, err error) { n2, ns, err = transformPagesAndCreateMissingStructuralNodes(s, n, false) if err != nil || ns >= doctree.NodeTransformStateSkip { return } if iep, ok := n2.(contentNodeIsEmptyProvider); ok && iep.isEmpty() { ns = doctree.NodeTransformStateDeleted } if ns == doctree.NodeTransformStateDeleted { return } // Walk nested resources. resourceOwnerInfo.s = s resourceOwnerInfo.n = n2 rw = rw.WithPrefix(s + "/") if err := rw.Walk(a.ctx); err != nil { return nil, 0, err } const maxDepth = 3 if a.assembleSectionsInParallel && s != "" && depth < maxDepth && cnh.isBranchNode(n) && a.h.getFirstTaxonomyConfig(s).IsZero() { // Handle this branch in its own goroutine. pw.SkipPrefix(s + "/") a.g.Go(func() error { return a.doCreatePages(s, depth+1) }) } return } pw.Handle = nil if err := pw.Walk(a.ctx); err != nil { return err } return nil } // Calculate and apply aggregate values to the page tree (e.g. dates). func (sa *sitePagesAssembler) applyAggregates() error { sectionPageCount := map[string]int{} pw := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: sa.s.pageMap.treePages, LockType: doctree.LockTypeRead, WalkContext: &doctree.WalkContext[contentNode]{}, } rw := pw.Extend() rw.Tree = sa.s.pageMap.treeResources sa.s.lastmod = time.Time{} rebuild := sa.s.h.isRebuild() pw.Handle = func(keyPage string, n contentNode) (radix.WalkFlag, error) { pageBundle := n.(*pageState) if pageBundle.Kind() == kinds.KindTerm { // Delay this until they're created. return radix.WalkContinue, nil } if pageBundle.IsPage() { rootSection := pageBundle.Section() sectionPageCount[rootSection]++ } if rebuild { if pageBundle.IsHome() || pageBundle.IsSection() { oldDates := pageBundle.m.pageConfig.Dates // We need to wait until after the walk to determine if any of the dates have changed. pw.WalkContext.HooksPost().Push( func() error { if oldDates != pageBundle.m.pageConfig.Dates { sa.assembleChanges.Add(pageBundle) } return nil }, ) } } const eventName = "dates" if cnh.isBranchNode(n) { wasZeroDates := pageBundle.m.pageConfig.Dates.IsAllDatesZero() if wasZeroDates || pageBundle.IsHome() { pw.WalkContext.AddEventListener(eventName, keyPage, func(e *doctree.Event[contentNode]) { sp, ok := e.Source.(*pageState) if !ok { return } if wasZeroDates { pageBundle.m.pageConfig.Dates.UpdateDateAndLastmodAndPublishDateIfAfter(sp.m.pageConfig.Dates) } if pageBundle.IsHome() { if pageBundle.m.pageConfig.Dates.Lastmod.After(pageBundle.s.lastmod) { pageBundle.s.lastmod = pageBundle.m.pageConfig.Dates.Lastmod } if sp.m.pageConfig.Dates.Lastmod.After(pageBundle.s.lastmod) { pageBundle.s.lastmod = sp.m.pageConfig.Dates.Lastmod } } }) } } // Send the date info up the tree. pw.WalkContext.SendEvent(&doctree.Event[contentNode]{Source: n, Path: keyPage, Name: eventName}) isBranch := cnh.isBranchNode(n) rw.Prefix = keyPage + "/" rw.IncludeRawFilter = func(s string, n contentNode) bool { // Only page nodes. return cnh.isPageNode(n) } rw.IncludeFilter = func(s string, n contentNode) bool { switch n.(type) { case *pageState: return true default: // We only want to handle page nodes here. return false } } rw.Handle = func(resourceKey string, n contentNode) (radix.WalkFlag, error) { if isBranch { ownerKey, _ := pw.Tree.LongestPrefix(resourceKey, false, nil) if ownerKey != keyPage { // Stop walking downwards, someone else owns this resource. rw.SkipPrefix(ownerKey + "/") return radix.WalkContinue, nil } } switch rs := n.(type) { case *pageState: relPath := rs.m.pathInfo.BaseRel(pageBundle.m.pathInfo) rs.m.resourcePath = relPath } return radix.WalkContinue, nil } if err := rw.Walk(sa.ctx); err != nil { return radix.WalkStop, err } return radix.WalkContinue, nil } if err := pw.Walk(sa.ctx); err != nil { return err } if err := pw.WalkContext.HandleEventsAndHooks(); err != nil { return err } if !sa.s.conf.C.IsMainSectionsSet() { var mainSection string var maxcount int for section, counter := range sectionPageCount { if section != "" && counter > maxcount { mainSection = section maxcount = counter } } sa.s.conf.C.SetMainSections([]string{mainSection}) } return nil } func (sa *sitePagesAssembler) applyAggregatesToTaxonomiesAndTerms() error { walkContext := &doctree.WalkContext[contentNode]{} handlePlural := func(key string) error { var pw *doctree.NodeShiftTreeWalker[contentNode] pw = &doctree.NodeShiftTreeWalker[contentNode]{ Tree: sa.s.pageMap.treePages, Prefix: key, // We also want to include the root taxonomy nodes, so no trailing slash. LockType: doctree.LockTypeRead, WalkContext: walkContext, Handle: func(s string, n contentNode) (radix.WalkFlag, error) { p := n.(*pageState) if p.Kind() != kinds.KindTerm && p.Kind() != kinds.KindTaxonomy { // Already handled. return radix.WalkContinue, nil } const eventName = "dates" if p.Kind() == kinds.KindTerm { if !p.s.shouldBuild(p) { sa.s.pageMap.treePages.Delete(s) sa.s.pageMap.treeTaxonomyEntries.DeletePrefix(paths.AddTrailingSlash(s)) } else if err := sa.s.pageMap.treeTaxonomyEntries.WalkPrefix( doctree.LockTypeRead, paths.AddTrailingSlash(s), func(ss string, wn *weightedContentNode) (bool, error) { // Send the date info up the tree. pw.WalkContext.SendEvent(&doctree.Event[contentNode]{Source: wn.n, Path: ss, Name: eventName}) return false, nil }, ); err != nil { return radix.WalkStop, err } } // Send the date info up the tree. pw.WalkContext.SendEvent(&doctree.Event[contentNode]{Source: n, Path: s, Name: eventName}) if p.m.pageConfig.Dates.IsAllDatesZero() { pw.WalkContext.AddEventListener(eventName, s, func(e *doctree.Event[contentNode]) { sp, ok := e.Source.(*pageState) if !ok { return } p.m.pageConfig.Dates.UpdateDateAndLastmodAndPublishDateIfAfter(sp.m.pageConfig.Dates) }) } return radix.WalkContinue, nil }, } if err := pw.Walk(sa.ctx); err != nil { return err } return nil } for _, viewName := range sa.s.pageMap.cfg.taxonomyConfig.views { if err := handlePlural(viewName.pluralTreeKey); err != nil { return err } } if err := walkContext.HandleEventsAndHooks(); err != nil { return err } return nil } func (sa *sitePagesAssembler) assembleTerms() error { if sa.s.pageMap.cfg.taxonomyTermDisabled { return nil } var ( pages = sa.s.pageMap.treePages entries = sa.s.pageMap.treeTaxonomyEntries views = sa.s.pageMap.cfg.taxonomyConfig.views ) lockType := doctree.LockTypeWrite w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: pages, LockType: lockType, Handle: func(s string, n contentNode) (radix.WalkFlag, error) { ps := n.(*pageState) if ps.m.noLink() { return radix.WalkContinue, nil } for _, viewName := range views { vals := types.ToStringSlicePreserveString(getParam(ps, viewName.plural, false)) if vals == nil { continue } w := getParamToLower(ps, viewName.plural+"_weight") weight, err := cast.ToIntE(w) if err != nil { sa.s.Log.Warnf("Unable to convert taxonomy weight %#v to int for %q", w, n.Path()) // weight will equal zero, so let the flow continue } for i, v := range vals { if v == "" { continue } viewTermKey := "/" + viewName.plural + "/" + v pi := sa.s.Conf.PathParser().Parse(files.ComponentFolderContent, viewTermKey+"/_index.md") termNode := pages.Get(pi.Base()) if termNode == nil { // This means that the term page has been disabled (e.g. a draft). continue } m := termNode.(*pageState).m m.term = v m.singular = viewName.singular if s == "" { s = "/" } key := pi.Base() + s entries.Insert(key, &weightedContentNode{ weight: weight, n: n, term: &pageWithOrdinal{pageState: termNode.(*pageState), ordinal: i}, }) } } return radix.WalkContinue, nil }, } if err := w.Walk(sa.ctx); err != nil { return err } return nil } func (sa *sitePagesAssembler) assemblePagesStepFinal() error { if err := sa.assembleResourcesAndSetHome(); err != nil { return err } return nil } func (sa *sitePagesAssembler) assembleResourcesAndSetHome() error { pagesTree := sa.s.pageMap.treePages lockType := doctree.LockTypeWrite w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: pagesTree, LockType: lockType, Handle: func(s string, n contentNode) (radix.WalkFlag, error) { ps := n.(*pageState) if s == "" { sa.s.home = ps } else if ps.s.home == nil { panic(fmt.Sprintf("[%v] expected home page to be set for %q", sa.s.siteVector, s)) } // This is a little out of place, but is conveniently put here. // Check if translationKey is set by user. // This is to support the manual way of setting the translationKey in front matter. if ps.m.pageConfig.TranslationKey != "" { sa.s.h.translationKeyPages.Append(ps.m.pageConfig.TranslationKey, ps) } if !sa.s.h.isRebuild() { if ps.hasRenderableOutput() { // For multi output pages this will not be complete, but will have to do for now. sa.s.h.progressReporter.numPagesToRender.Add(1) } } // Prepare resources for this page. ps.shiftToOutputFormat(true, 0) targetPaths := ps.targetPaths() baseTarget := targetPaths.SubResourceBaseTarget err := sa.s.pageMap.forEachResourceInPage( ps, lockType, false, nil, func(resourceKey string, n contentNode) (bool, error) { if _, ok := n.(*pageState); ok { return false, nil } rs := n.(*resourceSource) relPathOriginal := rs.path.Unnormalized().PathRel(ps.m.pathInfo.Unnormalized()) relPath := rs.path.BaseRel(ps.m.pathInfo) var targetBasePaths []string if ps.s.Conf.IsMultihost() { baseTarget = targetPaths.SubResourceBaseLink // In multihost we need to publish to the lang sub folder. targetBasePaths = []string{ps.s.GetTargetLanguageBasePath()} // TODO(bep) we don't need this as a slice anymore. } if rs.rc != nil && rs.rc.Content.IsResourceValue() { if rs.rc.Name == "" { rs.rc.Name = relPathOriginal } r, err := ps.s.ResourceSpec.NewResourceWrapperFromResourceConfig(rs.rc) if err != nil { return false, err } rs.r = r return false, nil } var mt media.Type if rs.rc != nil { mt = rs.rc.ContentMediaType } var filename string if rs.fi != nil { filename = rs.fi.Meta().Filename } rd := resources.ResourceSourceDescriptor{ OpenReadSeekCloser: rs.opener, Path: rs.path, GroupIdentity: rs.path, TargetPath: relPathOriginal, // Use the original path for the target path, so the links can be guessed.
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page_permalink_test.go
hugolib/page_permalink_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 hugolib import ( "fmt" "html/template" "testing" qt "github.com/frankban/quicktest" ) func TestPermalink(t *testing.T) { t.Parallel() tests := []struct { file string base template.URL slug string url string uglyURLs bool canonifyURLs bool expectedAbs string expectedRel string }{ {"x/y/z/boofar.md", "", "", "", false, false, "/x/y/z/boofar/", "/x/y/z/boofar/"}, {"x/y/z/boofar.md", "", "", "", false, false, "/x/y/z/boofar/", "/x/y/z/boofar/"}, // Issue #1174 {"x/y/z/boofar.md", "http://gopher.com/", "", "", false, true, "http://gopher.com/x/y/z/boofar/", "/x/y/z/boofar/"}, {"x/y/z/boofar.md", "http://gopher.com/", "", "", true, true, "http://gopher.com/x/y/z/boofar.html", "/x/y/z/boofar.html"}, {"x/y/z/boofar.md", "", "boofar", "", false, false, "/x/y/z/boofar/", "/x/y/z/boofar/"}, {"x/y/z/boofar.md", "http://barnew/", "", "", false, false, "http://barnew/x/y/z/boofar/", "/x/y/z/boofar/"}, {"x/y/z/boofar.md", "http://barnew/", "boofar", "", false, false, "http://barnew/x/y/z/boofar/", "/x/y/z/boofar/"}, {"x/y/z/boofar.md", "", "", "", true, false, "/x/y/z/boofar.html", "/x/y/z/boofar.html"}, {"x/y/z/boofar.md", "", "", "", true, false, "/x/y/z/boofar.html", "/x/y/z/boofar.html"}, {"x/y/z/boofar.md", "", "boofar", "", true, false, "/x/y/z/boofar.html", "/x/y/z/boofar.html"}, {"x/y/z/boofar.md", "http://barnew/", "", "", true, false, "http://barnew/x/y/z/boofar.html", "/x/y/z/boofar.html"}, {"x/y/z/boofar.md", "http://barnew/", "boofar", "", true, false, "http://barnew/x/y/z/boofar.html", "/x/y/z/boofar.html"}, {"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", true, false, "http://barnew/boo/x/y/z/booslug.html", "/boo/x/y/z/booslug.html"}, {"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", false, true, "http://barnew/boo/x/y/z/booslug/", "/x/y/z/booslug/"}, {"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", false, false, "http://barnew/boo/x/y/z/booslug/", "/boo/x/y/z/booslug/"}, {"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", true, true, "http://barnew/boo/x/y/z/booslug.html", "/x/y/z/booslug.html"}, {"x/y/z/boofar.md", "http://barnew/boo", "booslug", "", true, true, "http://barnew/boo/x/y/z/booslug.html", "/x/y/z/booslug.html"}, // Issue #4666 {"x/y/z/boo-makeindex.md", "http://barnew/boo", "", "", true, true, "http://barnew/boo/x/y/z/boo-makeindex.html", "/x/y/z/boo-makeindex.html"}, // test URL overrides {"x/y/z/boofar.md", "", "", "/z/y/q/", false, false, "/z/y/q/", "/z/y/q/"}, // test URL override with expands {"x/y/z/boofar.md", "", "test", "/z/:slug/", false, false, "/z/test/", "/z/test/"}, } for i, test := range tests { t.Run(fmt.Sprintf("%s-%d", test.file, i), func(t *testing.T) { t.Parallel() c := qt.New(t) files := fmt.Sprintf(` -- hugo.toml -- baseURL = %q uglyURLs = %t canonifyURLs = %t -- content/%s -- --- title: Page slug: %q url: %q output: ["HTML"] --- `, test.base, test.uglyURLs, test.canonifyURLs, test.file, test.slug, test.url) b := Test(t, files) s := b.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) p := s.RegularPages()[0] u := p.Permalink() expected := test.expectedAbs if u != expected { t.Fatalf("[%d] Expected abs url: %s, got: %s", i, expected, u) } u = p.RelPermalink() expected = test.expectedRel if u != expected { t.Errorf("[%d] Expected rel url: %s, got: %s", i, expected, u) } }) } } func TestRelativeURLInFrontMatter(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = false [Languages] [Languages.en] weight = 10 contentDir = "content/en" [Languages.nn] weight = 20 contentDir = "content/nn" -- layouts/single.html -- Single: {{ .Title }}|Hello|{{ .Lang }}|RelPermalink: {{ .RelPermalink }}|Permalink: {{ .Permalink }}| -- layouts/list.html -- List Page 1|{{ .Title }}|Hello|{{ .Permalink }}| -- content/en/blog/page1.md -- --- title: "A page" url: "myblog/p1/" --- Some content. -- content/en/blog/page2.md -- --- title: "A page" url: "../../../../../myblog/p2/" --- Some content. -- content/en/blog/page3.md -- --- title: "A page" url: "../myblog/../myblog/p3/" --- Some content. -- content/en/blog/_index.md -- --- title: "A page" url: "this-is-my-english-blog" --- Some content. -- content/nn/blog/page1.md -- --- title: "A page" url: "myblog/p1/" --- Some content. -- content/nn/blog/_index.md -- --- title: "A page" url: "this-is-my-blog" --- Some content. ` b := Test(t, files) b.AssertFileContent("public/nn/myblog/p1/index.html", "Single: A page|Hello|nn|RelPermalink: /nn/myblog/p1/|") b.AssertFileContent("public/nn/this-is-my-blog/index.html", "List Page 1|A page|Hello|https://example.com/nn/this-is-my-blog/|") b.AssertFileContent("public/this-is-my-english-blog/index.html", "List Page 1|A page|Hello|https://example.com/this-is-my-english-blog/|") b.AssertFileContent("public/myblog/p1/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p1/|Permalink: https://example.com/myblog/p1/|") b.AssertFileContent("public/myblog/p2/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p2/|Permalink: https://example.com/myblog/p2/|") b.AssertFileContent("public/myblog/p3/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p3/|Permalink: https://example.com/myblog/p3/|") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/site_test.go
hugolib/site_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 hugolib import ( "fmt" "os" "testing" qt "github.com/frankban/quicktest" ) func TestDraftAndFutureRender(t *testing.T) { t.Parallel() basefiles := ` -- content/sect/doc1.md -- --- title: doc1 draft: true publishdate: "2414-05-29" --- # doc1 *some content* -- content/sect/doc2.md -- --- title: doc2 draft: true publishdate: "2012-05-29" --- # doc2 *some content* -- content/sect/doc3.md -- --- title: doc3 draft: false publishdate: "2414-05-29" --- # doc3 *some content* -- content/sect/doc4.md -- --- title: doc4 draft: false publishdate: "2012-05-29" --- # doc4 *some content* ` t.Run("defaults", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://auth/bub" ` + basefiles b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 1) }) t.Run("buildDrafts", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://auth/bub" buildDrafts = true ` + basefiles b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 2) }) t.Run("buildFuture", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://auth/bub" buildFuture = true ` + basefiles b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 2) }) t.Run("buildDrafts and buildFuture", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://auth/bub" buildDrafts = true buildFuture = true ` + basefiles b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 4) }) } func TestFutureExpirationRender(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://auth/bub" -- content/sect/doc3.md -- --- title: doc1 expirydate: "2400-05-29" --- # doc1 *some content* -- content/sect/doc4.md -- --- title: doc2 expirydate: "2000-05-29" --- # doc2 *some content* ` b := Test(t, files) b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 1) b.Assert(b.H.Sites[0].RegularPages()[0].Title(), qt.Equals, "doc1") } func TestLastChange(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/sect/doc1.md -- --- title: doc1 weight: 1 date: 2014-05-29 --- # doc1 *some content* -- content/sect/doc2.md -- --- title: doc2 weight: 2 date: 2015-05-29 --- # doc2 *some content* -- content/sect/doc3.md -- --- title: doc3 weight: 3 date: 2017-05-29 --- # doc3 *some content* -- content/sect/doc4.md -- --- title: doc4 weight: 4 date: 2016-05-29 --- # doc4 *some content* -- content/sect/doc5.md -- --- title: doc5 weight: 3 --- # doc5 *some content* ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{SkipRender: true}, }, ).Build() b.Assert(b.H.Sites[0].Lastmod().IsZero(), qt.Equals, false) b.Assert(b.H.Sites[0].Lastmod().Year(), qt.Equals, 2017) } // Issue #_index func TestPageWithUnderScoreIndexInFilename(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/sect/my_index_file.md -- --- title: doc1 weight: 1 date: 2014-05-29 --- # doc1 *some content* ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{SkipRender: true}, }, ).Build() b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 1) } // Issue #939 // Issue #1923 func TestShouldAlwaysHaveUglyURLs(t *testing.T) { t.Parallel() basefiles := ` -- layouts/home.html -- Home Sweet {{ if.IsHome }}Home{{ end }}. -- layouts/single.html -- {{.Content}}{{ if.IsHome }}This is not home!{{ end }} -- layouts/404.html -- Page Not Found.{{ if.IsHome }}This is not home!{{ end }} -- layouts/rss.xml -- <root>RSS</root> -- layouts/sitemap.xml -- <root>SITEMAP</root> -- content/sect/doc1.md -- --- markup: markdown --- # title some *content* -- content/sect/doc2.md -- --- url: /ugly.html markup: markdown --- # title doc2 *content* ` t.Run("uglyURLs=true", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://auth/bub" uglyURLs = true ` + basefiles b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/index.html", "Home Sweet Home.") b.AssertFileContent("public/sect/doc1.html", "<h1 id=\"title\">title</h1>\n<p>some <em>content</em></p>\n") b.AssertFileContent("public/404.html", "Page Not Found.") b.AssertFileContent("public/index.xml", "<root>RSS</root>") b.AssertFileContent("public/sitemap.xml", "<root>SITEMAP</root>") b.AssertFileContent("public/ugly.html", "<h1 id=\"title\">title</h1>\n<p>doc2 <em>content</em></p>\n") for _, p := range b.H.Sites[0].RegularPages() { b.Assert(p.IsHome(), qt.Equals, false) } }) t.Run("uglyURLs=false", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://auth/bub" uglyURLs = false ` + basefiles b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/index.html", "Home Sweet Home.") b.AssertFileContent("public/sect/doc1/index.html", "<h1 id=\"title\">title</h1>\n<p>some <em>content</em></p>\n") b.AssertFileContent("public/404.html", "Page Not Found.") b.AssertFileContent("public/index.xml", "<root>RSS</root>") b.AssertFileContent("public/sitemap.xml", "<root>SITEMAP</root>") b.AssertFileContent("public/ugly.html", "<h1 id=\"title\">title</h1>\n<p>doc2 <em>content</em></p>\n") for _, p := range b.H.Sites[0].RegularPages() { b.Assert(p.IsHome(), qt.Equals, false) } }) } func TestMainSectionsMoveToSite(t *testing.T) { t.Run("defined in params", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['RSS','sitemap','taxonomy','term'] [params] mainSections=["a", "b"] -- content/mysect/page1.md -- -- layouts/home.html -- {{/* Behaviour before Hugo 0.112.0. */}} MainSections Params: {{ site.Params.mainSections }}| MainSections Site method: {{ site.MainSections }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", ` MainSections Params: [a b]| MainSections Site method: [a b]| `) }) t.Run("defined in top level config", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['RSS','sitemap','taxonomy','term'] mainSections=["a", "b"] [params] [params.sub] mainSections=["c", "d"] -- content/mysect/page1.md -- -- layouts/home.html -- {{/* Behaviour before Hugo 0.112.0. */}} MainSections Params: {{ site.Params.mainSections }}| MainSections Param sub: {{ site.Params.sub.mainSections }}| MainSections Site method: {{ site.MainSections }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", ` MainSections Params: [a b]| MainSections Param sub: [c d]| MainSections Site method: [a b]| `) }) t.Run("guessed from pages", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['RSS','sitemap','taxonomy','term'] -- content/mysect/page1.md -- -- layouts/home.html -- MainSections Params: {{ site.Params.mainSections }}| MainSections Site method: {{ site.MainSections }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", ` MainSections Params: [mysect]| MainSections Site method: [mysect]| `) }) } func TestRelRefWithTrailingSlash(t *testing.T) { files := ` -- hugo.toml -- -- content/docs/5.3/examples/_index.md -- --- title: "Examples" --- -- content/_index.md -- --- title: "Home" --- Examples: {{< relref "/docs/5.3/examples/" >}} -- layouts/home.html -- Content: {{ .Content }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "Examples: /docs/5.3/examples/") } // https://github.com/gohugoio/hugo/issues/6952 func TestRefIssues(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com" -- content/post/b1/index.md -- --- title: pb1 --- Ref: {{< ref "b2" >}} -- content/post/b2/index.md -- --- title: pb2 --- -- content/post/nested-a/content-a.md -- --- title: ca --- {{< ref "content-b" >}} -- content/post/nested-b/content-b.md -- --- title: ca --- -- layouts/home.html -- Home -- layouts/single.html -- Content: {{ .Content }} ` b := Test(t, files) b.AssertFileContent("public/post/b1/index.html", `Content: <p>Ref: http://example.com/post/b2/</p>`) b.AssertFileContent("public/post/nested-a/content-a/index.html", `Content: http://example.com/post/nested-b/content-b/`) } func TestClassCollector(t *testing.T) { for _, minify := range []bool{false, true} { t.Run(fmt.Sprintf("minify-%t", minify), func(t *testing.T) { statsFilename := "hugo_stats.json" defer os.Remove(statsFilename) files := fmt.Sprintf(` -- hugo.toml -- minify = %t [build] writeStats = true -- layouts/home.html -- <div id="el1" class="a b c">Foo</div> Some text. <div class="c d e [&>p]:text-red-600" id="el2">Foo</div> <span class=z>FOO</span> <a class="text-base hover:text-gradient inline-block px-3 pb-1 rounded lowercase" href="{{ .RelPermalink }}">{{ .Title }}</a> -- content/p1.md -- `, minify) b := Test(t, files, TestOptOsFs()) b.AssertFileContent("hugo_stats.json", ` { "htmlElements": { "tags": [ "a", "div", "span" ], "classes": [ "a", "b", "c", "d", "e", "hover:text-gradient", "[&>p]:text-red-600", "inline-block", "lowercase", "pb-1", "px-3", "rounded", "text-base", "z" ], "ids": [ "el1", "el2" ] } } `) }) } } func TestClassCollectorConfigWriteStats(t *testing.T) { r := func(writeStatsConfig string) *IntegrationTestBuilder { files := ` -- hugo.toml -- ` + writeStatsConfig + ` -- layouts/list.html -- <div id="myid" class="myclass">Foo</div> ` b := Test(t, files, TestOptOsFs()) return b } // Legacy config. var b *IntegrationTestBuilder // Declare 'b' once b = r(` [build] writeStats = true `) b.AssertFileContent("hugo_stats.json", "myclass", "div", "myid") b = r(` [build] writeStats = false `) b.AssertFileExists("public/hugo_stats.json", false) b = r(` [build.buildStats] enable = true `) b.AssertFileContent("hugo_stats.json", "myclass", "div", "myid") b = r(` [build.buildStats] enable = true disableids = true `) b.AssertFileContent("hugo_stats.json", "myclass", "div", "! myid") b = r(` [build.buildStats] enable = true disableclasses = true `) b.AssertFileContent("hugo_stats.json", "! myclass", "div", "myid") b = r(` [build.buildStats] enable = true disabletags = true `) b.AssertFileContent("hugo_stats.json", "myclass", "! div", "myid") b = r(` [build.buildStats] enable = true disabletags = true disableclasses = true `) b.AssertFileContent("hugo_stats.json", "! myclass", "! div", "myid") b = r(` [build.buildStats] enable = false `) b.AssertFileExists("public/hugo_stats.json", false) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/siteJSONEncode_test.go
hugolib/siteJSONEncode_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 hugolib import ( "testing" ) // Issue #1123 // Testing prevention of cyclic refs in JSON encoding // May be smart to run with: -timeout 4000ms func TestEncodePage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" -- layouts/home.html -- Page: |{{ index .Site.RegularPages 0 | jsonify }}| Site: {{ site | jsonify }} -- content/page.md -- --- title: "Page" date: 2019-02-28 --- Content. ` b := Test(t, files) b.AssertFileContent("public/index.html", `"Date":"2019-02-28T00:00:00Z"`) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__paginator.go
hugolib/page__paginator.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "sync" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" ) func newPagePaginator(source *pageState) *pagePaginator { return &pagePaginator{ source: source, pagePaginatorInit: &pagePaginatorInit{}, } } type pagePaginator struct { *pagePaginatorInit source *pageState } type pagePaginatorInit struct { init sync.Once current *page.Pager } // reset resets the paginator to allow for a rebuild. func (p *pagePaginator) reset() { p.pagePaginatorInit = &pagePaginatorInit{} } func (p *pagePaginator) Paginate(seq any, options ...any) (*page.Pager, error) { var initErr error p.init.Do(func() { pagerSize, err := page.ResolvePagerSize(p.source.s.Conf, options...) if err != nil { initErr = err return } pd := p.source.targetPathDescriptor pd.Type = p.source.outputFormat() paginator, err := page.Paginate(pd, seq, pagerSize) if err != nil { initErr = err return } p.current = paginator.Pagers()[0] }) if initErr != nil { return nil, initErr } return p.current, nil } func (p *pagePaginator) Paginator(options ...any) (*page.Pager, error) { var initErr error p.init.Do(func() { pagerSize, err := page.ResolvePagerSize(p.source.s.Conf, options...) if err != nil { initErr = err return } pd := p.source.targetPathDescriptor pd.Type = p.source.outputFormat() var pages page.Pages switch p.source.Kind() { case kinds.KindHome: // From Hugo 0.57 we made home.Pages() work like any other // section. To avoid the default paginators for the home page // changing in the wild, we make this a special case. pages = p.source.s.RegularPages() case kinds.KindTerm, kinds.KindTaxonomy: pages = p.source.Pages() default: pages = p.source.RegularPages() } paginator, err := page.Paginate(pd, pages, pagerSize) if err != nil { initErr = err return } p.current = paginator.Pagers()[0] }) if initErr != nil { return nil, initErr } return p.current, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/hugo_sites_test.go
hugolib/hugo_sites_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 hugolib import "testing" func TestSitesAndLanguageOrder(t *testing.T) { files := ` -- hugo.toml -- defaultContentLanguage = "fr" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 [languages.fr] weight = 2 [languages.de] weight = 3 -- layouts/home.html -- {{ $bundle := site.GetPage "bundle" }} Bundle all translations: {{ range $bundle.AllTranslations }}{{ .Lang }}|{{ end }}$ Bundle translations: {{ range $bundle.Translations }}{{ .Lang }}|{{ end }}$ Site languages: {{ range site.Languages }}{{ .Lang }}|{{ end }}$ Sites: {{ range site.Sites }}{{ .Language.Lang }}|{{ end }}$ -- content/bundle/index.fr.md -- --- title: "Bundle Fr" --- -- content/bundle/index.en.md -- --- title: "Bundle En" --- -- content/bundle/index.de.md -- --- title: "Bundle De" --- ` b := Test(t, files) b.AssertFileContent("public/en/index.html", "Bundle all translations: en|fr|de|$", "Bundle translations: fr|de|$", "Site languages: en|fr|de|$", "Sites: en|fr|de|$", ) } func TestSitesOrder(t *testing.T) { files := ` -- hugo.toml -- defaultContentLanguage = "fr" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 [languages.fr] weight = 2 [languages.de] weight = 3 [roles] [roles.guest] weight = 1 [roles.member] weight = 2 -- layouts/home.html -- Sites: {{ range site.Sites }}{{ .Language.Lang }}|{{ end }}$ Languages: {{ range site.Languages }}{{ .Lang }}|{{ end }} ` b := Test(t, files) // Note that before v0.152.0 the order of these slices where different .Sites pulled the defaultContentLanguage first. b.AssertFileContent("public/en/index.html", "Sites: en|fr|de|$", "Languages: en|fr|de|") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/alias.go
hugolib/alias.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "bytes" "context" "errors" "fmt" "io" "path" "path/filepath" "runtime" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/publisher" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/tpl/tplimpl" ) type aliasHandler struct { ts *tplimpl.TemplateStore log loggers.Logger allowRoot bool } func newAliasHandler(ts *tplimpl.TemplateStore, l loggers.Logger, allowRoot bool) aliasHandler { return aliasHandler{ts, l, allowRoot} } type aliasPage struct { Permalink string page.Page } func (a aliasHandler) renderAlias(permalink string, p page.Page, matrix sitesmatrix.VectorProvider) (io.Reader, error) { var templateDesc tplimpl.TemplateDescriptor var base string = "" if ps, ok := p.(*pageState); ok { base, templateDesc = ps.GetInternalTemplateBasePathAndDescriptor() } templateDesc.LayoutFromUser = "" templateDesc.Kind = "" templateDesc.OutputFormat = output.AliasHTMLFormat.Name templateDesc.MediaType = output.AliasHTMLFormat.MediaType.Type q := tplimpl.TemplateQuery{ Path: base, Category: tplimpl.CategoryLayout, Desc: templateDesc, Sites: matrix, } t := a.ts.LookupPagesLayout(q) if t == nil { return nil, errors.New("no alias template found") } data := aliasPage{ permalink, p, } ctx := a.ts.PrepareTopLevelRenderCtx(context.Background(), p) buffer := new(bytes.Buffer) err := a.ts.ExecuteWithContext(ctx, t, buffer, data) if err != nil { return nil, err } return buffer, nil } func (s *Site) writeDestAlias(path, permalink string, outputFormat output.Format, p page.Page) (err error) { return s.publishDestAlias(false, path, permalink, outputFormat, p) } func (s *Site) publishDestAlias(allowRoot bool, path, permalink string, outputFormat output.Format, p page.Page) (err error) { handler := newAliasHandler(s.GetTemplateStore(), s.Log, allowRoot) targetPath, err := handler.targetPathAlias(path) if err != nil { return err } aliasContent, err := handler.renderAlias(permalink, p, s.siteVector) if err != nil { return err } pd := publisher.Descriptor{ Src: aliasContent, TargetPath: targetPath, StatCounter: &s.PathSpec.ProcessingStats.Aliases, OutputFormat: outputFormat, } if s.conf.RelativeURLs || s.conf.CanonifyURLs { pd.AbsURLPath = s.absURLPath(targetPath) } return s.publisher.Publish(pd) } func (a aliasHandler) targetPathAlias(src string) (string, error) { originalAlias := src if len(src) <= 0 { return "", fmt.Errorf("alias \"\" is an empty string") } alias := path.Clean(filepath.ToSlash(src)) if !a.allowRoot && alias == "/" { return "", fmt.Errorf("alias \"%s\" resolves to website root directory", originalAlias) } components := strings.Split(alias, "/") // Validate against directory traversal if components[0] == ".." { return "", fmt.Errorf("alias \"%s\" traverses outside the website root directory", originalAlias) } // Handle Windows file and directory naming restrictions // See "Naming Files, Paths, and Namespaces" on MSDN // https://msdn.microsoft.com/en-us/library/aa365247%28v=VS.85%29.aspx?f=255&MSPPError=-2147217396 msgs := []string{} reservedNames := []string{"CON", "PRN", "AUX", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"} if strings.ContainsAny(alias, ":*?\"<>|") { msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains invalid characters on Windows: : * ? \" < > |", originalAlias)) } for _, ch := range alias { if ch < ' ' { msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains ASCII control code (0x00 to 0x1F), invalid on Windows: : * ? \" < > |", originalAlias)) continue } } for _, comp := range components { if strings.HasSuffix(comp, " ") || strings.HasSuffix(comp, ".") { msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains component with a trailing space or period, problematic on Windows", originalAlias)) } for _, r := range reservedNames { if comp == r { msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains component with reserved name \"%s\" on Windows", originalAlias, r)) } } } if len(msgs) > 0 { if runtime.GOOS == "windows" { for _, m := range msgs { a.log.Errorln(m) } return "", fmt.Errorf("cannot create \"%s\": Windows filename restriction", originalAlias) } for _, m := range msgs { a.log.Infoln(m) } } // Add the final touch alias = strings.TrimPrefix(alias, "/") if strings.HasSuffix(alias, "/") { alias = alias + "index.html" } else if !strings.HasSuffix(alias, ".html") { alias = alias + "/" + "index.html" } return filepath.FromSlash(alias), nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__meta_test.go
hugolib/page__meta_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 hugolib import ( "strings" "testing" ) // Issue 9793 // Issue 12115 func TestListTitles(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','sitemap'] capitalizeListTitles = true pluralizeListTitles = true [taxonomies] tag = 'tags' -- content/section-1/page-1.md -- --- title: page-1 tags: 'tag-a' --- -- layouts/list.html -- {{ .Title }} -- layouts/single.html -- {{ .Title }} ` b := Test(t, files) b.AssertFileContent("public/section-1/index.html", "Section-1s") b.AssertFileContent("public/tags/index.html", "Tags") b.AssertFileContent("public/tags/tag-a/index.html", "Tag-A") files = strings.Replace(files, "true", "false", -1) b = Test(t, files) b.AssertFileContent("public/section-1/index.html", "section-1") b.AssertFileContent("public/tags/index.html", "tags") b.AssertFileContent("public/tags/tag-a/index.html", "tag-a") } func TestDraftNonDefaultContentLanguage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- defaultContentLanguage = "en" [languages] [languages.en] weight = 1 [languages.nn] weight = 2 -- content/p1.md -- -- content/p2.nn.md -- --- title: "p2" draft: true --- -- layouts/single.html -- {{ .Title }} ` b := Test(t, files) b.AssertFileExists("public/nn/p2/index.html", false) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/frontmatter_test.go
hugolib/frontmatter_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 hugolib import "testing" // Issue 10624 func TestFrontmatterPreserveDatatypesForSlices(t *testing.T) { t.Parallel() files := ` -- content/post/one.md -- --- ints: [1, 2, 3] mixed: ["1", 2, 3] strings: ["1", "2","3"] --- -- layouts/single.html -- Ints: {{ printf "%T" .Params.ints }} {{ range .Params.ints }}Int: {{ fmt.Printf "%[1]v (%[1]T)" . }}|{{ end }} Mixed: {{ printf "%T" .Params.mixed }} {{ range .Params.mixed }}Mixed: {{ fmt.Printf "%[1]v (%[1]T)" . }}|{{ end }} Strings: {{ printf "%T" .Params.strings }} {{ range .Params.strings }}Strings: {{ fmt.Printf "%[1]v (%[1]T)" . }}|{{ end }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ) b.Build() b.AssertFileContent("public/post/one/index.html", "Ints: []interface {} Int: 1 (uint64)|Int: 2 (uint64)|Int: 3 (uint64)|") b.AssertFileContent("public/post/one/index.html", "Mixed: []interface {} Mixed: 1 (string)|Mixed: 2 (uint64)|Mixed: 3 (uint64)|") b.AssertFileContent("public/post/one/index.html", "Strings: []string Strings: 1 (string)|Strings: 2 (string)|Strings: 3 (string)|") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/content_map_test.go
hugolib/content_map_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 hugolib import ( "fmt" "strings" "sync" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib/sitesmatrix" ) func TestContentMapSite(t *testing.T) { t.Parallel() pageTempl := ` --- title: "Page %d" date: "2019-06-%02d" lastMod: "2019-06-%02d" categories: [%q] --- Page content. ` createPage := func(i int) string { return fmt.Sprintf(pageTempl, i, i, i+1, "funny") } createPageInCategory := func(i int, category string) string { return fmt.Sprintf(pageTempl, i, i, i+1, category) } draftTemplate := `--- title: "Draft" draft: true --- ` files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/home.html -- Num Regular: {{ len .Site.RegularPages }}|{{ range .Site.RegularPages }}{{ .RelPermalink }}|{{ end }}$ Main Sections: {{ .Site.Params.mainSections }} Pag Num Pages: {{ len .Paginator.Pages }} {{ $home := .Site.Home }} {{ $blog := .Site.GetPage "blog" }} {{ $categories := .Site.GetPage "categories" }} {{ $funny := .Site.GetPage "categories/funny" }} {{ $blogSub := .Site.GetPage "blog/subsection" }} {{ $page := .Site.GetPage "blog/page1" }} {{ $page2 := .Site.GetPage "blog/page2" }} {{ $page4 := .Site.GetPage "blog/subsection/page4" }} {{ $bundle := .Site.GetPage "blog/bundle" }} {{ $overlap1 := .Site.GetPage "overlap" }} {{ $overlap2 := .Site.GetPage "overlap2" }} Home: {{ template "print-page" $home }} Blog Section: {{ template "print-page" $blog }} Blog Sub Section: {{ template "print-page" $blogSub }} Page: {{ template "print-page" $page }} Bundle: {{ template "print-page" $bundle }} IsDescendant: true: {{ $page.IsDescendant $blog }} true: {{ $blogSub.IsDescendant $blog }} true: {{ $bundle.IsDescendant $blog }} true: {{ $page4.IsDescendant $blog }} true: {{ $blog.IsDescendant $home }} false: {{ $blog.IsDescendant $blog }} false: {{ $home.IsDescendant $blog }} IsAncestor: true: {{ $blog.IsAncestor $page }} true: {{ $home.IsAncestor $blog }} true: {{ $blog.IsAncestor $blogSub }} true: {{ $blog.IsAncestor $bundle }} true: {{ $blog.IsAncestor $page4 }} true: {{ $home.IsAncestor $page }} false: {{ $blog.IsAncestor $blog }} false: {{ $page.IsAncestor $blog }} false: {{ $blog.IsAncestor $home }} false: {{ $blogSub.IsAncestor $blog }} IsDescendant overlap1: false: {{ $overlap1.IsDescendant $overlap2 }} IsDescendant overlap2: false: {{ $overlap2.IsDescendant $overlap1 }} IsAncestor overlap1: false: {{ $overlap1.IsAncestor $overlap2 }} IsAncestor overlap2: false: {{ $overlap2.IsAncestor $overlap1 }} FirstSection: {{ $blogSub.FirstSection.RelPermalink }} {{ $blog.FirstSection.RelPermalink }} {{ $home.FirstSection.RelPermalink }} {{ $page.FirstSection.RelPermalink }} InSection: true: {{ $page.InSection $blog }} false: {{ $page.InSection $blogSub }} Next: {{ $page2.Next.RelPermalink }} NextInSection: {{ $page2.NextInSection.RelPermalink }} Pages: {{ range $blog.Pages }}{{ .RelPermalink }}|{{ end }} Sections: {{ range $home.Sections }}{{ .RelPermalink }}|{{ end }}:END Categories: {{ range .Site.Taxonomies.categories }}{{ .Page.RelPermalink }}; {{ .Page.Title }}; {{ .Count }}|{{ end }}:END Category Terms: {{ $categories.Kind}}: {{ range $categories.Data.Terms.Alphabetical }}{{ .Page.RelPermalink }}; {{ .Page.Title }}; {{ .Count }}|{{ end }}:END Category Funny: {{ $funny.Kind}}; {{ $funny.Data.Term }}: {{ range $funny.Pages }}{{ .RelPermalink }}|{{ end }}:END Pag Num Pages: {{ len .Paginator.Pages }} Pag Blog Num Pages: {{ len $blog.Paginator.Pages }} Blog Num RegularPages: {{ len $blog.RegularPages }}|{{ range $blog.RegularPages }}P: {{ .RelPermalink }}|{{ end }} Blog Num Pages: {{ len $blog.Pages }} Draft1: {{ if (.Site.GetPage "blog/subsection/draft") }}FOUND{{ end }}| Draft2: {{ if (.Site.GetPage "blog/draftsection") }}FOUND{{ end }}| Draft3: {{ if (.Site.GetPage "blog/draftsection/page") }}FOUND{{ end }}| Draft4: {{ if (.Site.GetPage "blog/draftsection/sub") }}FOUND{{ end }}| Draft5: {{ if (.Site.GetPage "blog/draftsection/sub/page") }}FOUND{{ end }}| {{ define "print-page" }}{{ .Title }}|{{ .RelPermalink }}|{{ .Date.Format "2006-01-02" }}|Current Section: {{ with .CurrentSection }}{{ .Path }}{{ else }}NIL{{ end }}|Resources: {{ range .Resources }}{{ .ResourceType }}: {{ .RelPermalink }}|{{ end }}{{ end }} -- content/_index.md -- --- title: "Hugo Home" cascade: description: "Common Description" --- Home Content. -- content/blog/page1.md -- ` + createPage(1) + ` -- content/blog/page2.md -- ` + createPage(2) + ` -- content/blog/page3.md -- ` + createPage(3) + ` -- content/blog/bundle/index.md -- ` + createPage(4) + ` -- content/blog/bundle/data.json -- data -- content/blog/bundle/page.md -- ` + createPage(5) + ` -- content/blog/subsection/_index.md -- ` + createPage(6) + ` -- content/blog/subsection/subdata.json -- data -- content/blog/subsection/page4.md -- ` + createPage(7) + ` -- content/blog/subsection/page5.md -- ` + createPage(8) + ` -- content/blog/subsection/draft/index.md -- ` + draftTemplate + ` -- content/blog/subsection/draft/data.json -- data -- content/blog/draftsection/_index.md -- ` + draftTemplate + ` -- content/blog/draftsection/page/index.md -- ` + createPage(9) + ` -- content/blog/draftsection/page/folder/data.json -- data -- content/blog/draftsection/sub/_index.md -- ` + createPage(10) + ` -- content/blog/draftsection/sub/page.md -- ` + createPage(11) + ` -- content/docs/page6.md -- ` + createPage(12) + ` -- content/tags/_index.md -- ` + createPageInCategory(13, "sad") + ` -- content/overlap/_index.md -- ` + createPageInCategory(14, "sad") + ` -- content/overlap2/_index.md -- ` + createPage(15) + ` ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Num Regular: 9 Main Sections: [blog] Pag Num Pages: 9 Home: Hugo Home|/|2019-06-15|Current Section: /|Resources: Blog Section: Blogs|/blog/|2019-06-11|Current Section: /blog|Resources: Blog Sub Section: Page 6|/blog/subsection/|2019-06-06|Current Section: /blog/subsection|Resources: application: /blog/subsection/subdata.json| Page: Page 1|/blog/page1/|2019-06-01|Current Section: /blog|Resources: Bundle: Page 4|/blog/bundle/|2019-06-04|Current Section: /blog|Resources: application: /blog/bundle/data.json|page: | IsDescendant: true: true true: true true: true true: true true: true false: false false: false IsAncestor: true: true true: true true: true true: true true: true true: true false: false false: false false: false false: false IsDescendant overlap1: false: false IsDescendant overlap2: false: false IsAncestor overlap1: false: false IsAncestor overlap2: false: false FirstSection: /blog/ /blog/ / /blog/ InSection: true: true false: false Next: /blog/page3/ NextInSection: /blog/page3/ Pages: /blog/subsection/|/blog/bundle/|/blog/page3/|/blog/page2/|/blog/page1/| Sections: /overlap2/|/overlap/|/docs/|/blog/|:END Categories: /categories/funny/; Funny; 12|/categories/sad/; Sad; 2|:END Category Terms: taxonomy: /categories/funny/; Funny; 12|/categories/sad/; Sad; 2|:END Category Funny: term; funny: /overlap2/|/docs/page6/|/blog/draftsection/sub/page/|/blog/draftsection/sub/|/blog/draftsection/page/|/blog/subsection/page5/|/blog/subsection/page4/|/blog/subsection/|/blog/bundle/|/blog/page3/|/blog/page2/|/blog/page1/|:END Pag Num Pages: 9 Pag Blog Num Pages: 4 Blog Num RegularPages: 4 Blog Num Pages: 5 Draft1: | Draft2: FOUND| Draft3: FOUND| Draft4: FOUND| Draft5: FOUND| `) } func TestIntegrationTestTemplate(t *testing.T) { t.Parallel() c := qt.New(t) files := ` -- hugo.toml -- title = "Integration Test" disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT", "RSS"] -- layouts/home.html -- Home: {{ .Title }}| ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: c, TxtarString: files, }).Build() b.AssertFileContent("public/index.html", "Home: Integration Test|") } // Issue #11840 // Resource language fallback should be the closest language going up. func TestBundleResourceLanguageBestMatch(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- defaultContentLanguage = "fr" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 [languages.fr] weight = 2 [languages.de] weight = 3 -- layouts/home.html -- {{ $bundle := site.GetPage "bundle" }} {{ $r := $bundle.Resources.GetMatch "*.txt" }} {{ .Language.Lang }}: {{ with $r }}{{ .RelPermalink }}|{{ .Content }}{{ end}} -- content/bundle/index.fr.md -- --- title: "Bundle Fr" --- -- content/bundle/index.en.md -- --- title: "Bundle En" --- -- content/bundle/index.de.md -- --- title: "Bundle De" --- -- content/bundle/data.fr.txt -- Data fr -- content/bundle/data.en.txt -- Data en ` for range 5 { b := Test(t, files) b.AssertFileContent("public/fr/index.html", "fr: /fr/bundle/data.fr.txt|Data fr") b.AssertFileContent("public/en/index.html", "en: /en/bundle/data.en.txt|Data en") b.AssertFileContent("public/de/index.html", "de: /fr/bundle/data.fr.txt|Data fr") } } // Issue #11944 func TestBundleResourcesGetWithSpacesInFilename(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] -- content/bundle/index.md -- -- content/bundle/data with Spaces.txt -- Data. -- layouts/home.html -- {{ $bundle := site.GetPage "bundle" }} {{ $r := $bundle.Resources.Get "data with Spaces.txt" }} R: {{ with $r }}{{ .Content }}{{ end }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "R: Data.") } // Issue #11946. func TestBundleResourcesGetDuplicateSortOrder(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" -- content/bundle/index.md -- -- content/bundle/data-1.txt -- data-1.txt -- content/bundle/data 1.txt -- data 1.txt -- content/bundle/Data 1.txt -- Data 1.txt -- content/bundle/Data-1.txt -- Data-1.txt -- layouts/home.html -- {{ $bundle := site.GetPage "bundle" }} {{ $r := $bundle.Resources.Get "data-1.txt" }} R: {{ with $r }}{{ .Content }}{{ end }}|Len: {{ len $bundle.Resources }}|$ ` for range 3 { b := Test(t, files) b.AssertFileContent("public/index.html", "R: Data 1.txt|", "Len: 1|") } } func TestBundleResourcesNoPublishedIssue12198(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','sitemap','taxonomy','term'] -- content/s1/p1.md -- --- title: p1 --- -- content/s1/foo.txt -- foo.txt -- content/s1/p1.txt -- p1.txt -- content/s1/p1-foo.txt -- p1-foo.txt -- layouts/list.html -- {{.Title }}| -- layouts/single.html -- {{.Title }}| ` b := Test(t, files) b.AssertFileExists("public/s1/index.html", true) b.AssertFileExists("public/s1/foo.txt", true) b.AssertFileExists("public/s1/p1.txt", true) // failing test b.AssertFileExists("public/s1/p1-foo.txt", true) // failing test b.AssertFileExists("public/s1/p1/index.html", true) } // Issue 13228. func TestBranchResourceOverlap(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- content/_index.md -- --- title: home --- -- content/s1/_index.md -- --- title: s1 --- -- content/s1x/a.txt -- a.txt -- layouts/home.html -- Home. {{ range .Resources.Match "**" }} {{ .Name }}| {{ end }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "s1x/a.txt|") } func TestSitemapOverrideFilename(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'https://example.org/' disableKinds = ['page','rss','section','taxonomy','term'] defaultContentLanguage = 'de' defaultContentLanguageInSubdir = true [languages.de] [languages.en] [sitemap] filename = 'foo.xml' -- layouts/home.html -- irrelevant ` b := Test(t, files) b.AssertFileExists("public/de/foo.xml", true) b.AssertFileExists("public/en/foo.xml", true) b.AssertFileContent("public/foo.xml", "<loc>https://example.org/de/foo.xml</loc>", "<loc>https://example.org/en/foo.xml</loc>", ) files = strings.ReplaceAll(files, "filename = 'foo.xml'", "") b = Test(t, files) b.AssertFileExists("public/de/sitemap.xml", true) b.AssertFileExists("public/en/sitemap.xml", true) b.AssertFileContent("public/sitemap.xml", "<loc>https://example.org/de/sitemap.xml</loc>", "<loc>https://example.org/en/sitemap.xml</loc>", ) } func TestContentTreeReverseIndex(t *testing.T) { t.Parallel() c := qt.New(t) pageReverseIndex := newContentTreeTreverseIndex( func(get func(key any) (contentNode, bool), set func(key any, val contentNode)) { for i := range 10 { key := fmt.Sprint(i) set(key, &testContentNode{key: key}) } }, ) for i := range 10 { key := fmt.Sprint(i) v := pageReverseIndex.Get(key) c.Assert(v, qt.Not(qt.IsNil)) c.Assert(v.Path(), qt.Equals, key) } } // Issue 13019. func TestContentTreeReverseIndexPara(t *testing.T) { t.Parallel() var wg sync.WaitGroup for range 10 { pageReverseIndex := newContentTreeTreverseIndex( func(get func(key any) (contentNode, bool), set func(key any, val contentNode)) { for i := range 10 { key := fmt.Sprint(i) set(key, &testContentNode{key: key}) } }, ) for j := range 10 { wg.Add(1) go func(i int) { defer wg.Done() pageReverseIndex.Get(fmt.Sprint(i)) }(j) } } } type testContentNode struct { key string } func (n *testContentNode) Path() string { return n.key } func (n *testContentNode) forEeachContentNode(f func(v sitesmatrix.Vector, n contentNode) bool) bool { panic("not supported") } // Issue 12274. func TestHTMLNotContent(t *testing.T) { filesTemplate := ` -- hugo.toml.temp -- [contentTypes] [contentTypes."text/markdown"] # Empty for now. -- hugo.yaml.temp -- contentTypes: text/markdown: {} -- hugo.json.temp -- { "contentTypes": { "text/markdown": {} } } -- content/p1/index.md -- --- title: p1 --- -- content/p1/a.html -- <p>a</p> -- content/p1/b.html -- <p>b</p> -- content/p1/c.html -- <p>c</p> -- layouts/single.html -- Path: {{ .Path }}|{{.Kind }} |{{ (.Resources.Get "a.html").RelPermalink -}} |{{ (.Resources.Get "b.html").RelPermalink -}} |{{ (.Resources.Get "c.html").Publish }} ` for _, format := range []string{"toml", "yaml", "json"} { t.Run(format, func(t *testing.T) { t.Parallel() files := strings.Replace(filesTemplate, format+".temp", format, 1) b := Test(t, files) b.AssertFileContent("public/p1/index.html", "|/p1/a.html|/p1/b.html|") b.AssertFileContent("public/p1/a.html", "<p>a</p>") b.AssertFileContent("public/p1/b.html", "<p>b</p>") b.AssertFileContent("public/p1/c.html", "<p>c</p>") }) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/menu_test.go
hugolib/menu_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 hugolib import ( "testing" qt "github.com/frankban/quicktest" ) func TestMenusSectionPagesMenu(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseurl = "http://example.com/" title = "Section Menu" sectionPagesMenu = "sect" -- layouts/_partials/menu.html -- {{- $p := .page -}} {{- $m := .menu -}} {{ range (index $p.Site.Menus $m) -}} {{- .URL }}|{{ .Name }}|{{ .Title }}|{{ .Weight -}}| {{- if $p.IsMenuCurrent $m . }}IsMenuCurrent{{ else }}-{{ end -}}| {{- if $p.HasMenuCurrent $m . }}HasMenuCurrent{{ else }}-{{ end -}}| {{- end -}} -- layouts/single.html -- Single|{{ .Title }} Menu Sect: {{ partial "menu.html" (dict "page" . "menu" "sect") }} Menu Main: {{ partial "menu.html" (dict "page" . "menu" "main") }} -- layouts/list.html -- List|{{ .Title }}|{{ .Content }} -- content/sect1/p1.md -- --- title: "p1" weight: 1 menu: main: title: "atitle1" weight: 40 --- # Doc Menu -- content/sect1/p2.md -- --- title: "p2" weight: 2 menu: main: title: "atitle2" weight: 30 --- # Doc Menu -- content/sect2/p3.md -- --- title: "p3" weight: 3 menu: main: title: "atitle3" weight: 20 --- # Doc Menu -- content/sect2/p4.md -- --- title: "p4" weight: 4 menu: main: title: "atitle4" weight: 10 --- # Doc Menu -- content/sect3/p5.md -- --- title: "p5" weight: 5 menu: main: title: "atitle5" weight: 5 --- # Doc Menu -- content/sect1/_index.md -- --- title: "Section One" date: "2017-01-01" weight: 100 --- -- content/sect5/_index.md -- --- title: "Section Five" date: "2017-01-01" weight: 10 --- ` b := Test(t, files) h := b.H s := h.Sites[0] b.Assert(len(s.Menus()), qt.Equals, 2) p1 := s.RegularPages()[0].Menus() // There is only one menu in the page, but it is "member of" 2 b.Assert(len(p1), qt.Equals, 1) b.AssertFileContent("public/sect1/p1/index.html", "Single", "Menu Sect: "+ "/sect5/|Section Five|Section Five|10|-|-|"+ "/sect1/|Section One|Section One|100|-|HasMenuCurrent|"+ "/sect2/|Sect2s|Sect2s|0|-|-|"+ "/sect3/|Sect3s|Sect3s|0|-|-|", "Menu Main: "+ "/sect3/p5/|p5|atitle5|5|-|-|"+ "/sect2/p4/|p4|atitle4|10|-|-|"+ "/sect2/p3/|p3|atitle3|20|-|-|"+ "/sect1/p2/|p2|atitle2|30|-|-|"+ "/sect1/p1/|p1|atitle1|40|IsMenuCurrent|-|", ) b.AssertFileContent("public/sect2/p3/index.html", "Single", "Menu Sect: "+ "/sect5/|Section Five|Section Five|10|-|-|"+ "/sect1/|Section One|Section One|100|-|-|"+ "/sect2/|Sect2s|Sect2s|0|-|HasMenuCurrent|"+ "/sect3/|Sect3s|Sect3s|0|-|-|") } func TestMenusFrontMatter(t *testing.T) { files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/home.html -- Main: {{ len .Site.Menus.main }} Other: {{ len .Site.Menus.other }} {{ range .Site.Menus.main }} * Main|{{ .Name }}: {{ .URL }} {{ end }} {{ range .Site.Menus.other }} * Other|{{ .Name }}: {{ .URL }} {{ end }} -- content/blog/page1.md -- --- title: "P1" menu: main --- -- content/blog/page2.md -- --- title: "P2" menu: [main,other] --- -- content/blog/page3.md -- --- title: "P3" menu: main: weight: 30 --- ` b := Test(t, files) b.AssertFileContent("public/index.html", "Main: 3", "Other: 1", "Main|P1: /blog/page1/", "Other|P2: /blog/page2/", ) } // https://github.com/gohugoio/hugo/issues/5849 func TestMenusPageMultipleOutputFormats(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" # DAMP is similar to AMP, but not permalinkable. [outputFormats] [outputFormats.damp] mediaType = "text/html" path = "damp" -- layouts/home.html -- {{ range .Site.Menus.main }}{{ .Title }}|{{ .URL }}|{{ end }} -- content/_index.md -- --- Title: Home Sweet Home outputs: [ "html", "amp" ] menu: "main" --- -- content/blog/html-amp.md -- --- Title: AMP and HTML outputs: [ "html", "amp" ] menu: "main" --- -- content/blog/html.md -- --- Title: HTML only outputs: [ "html" ] menu: "main" --- -- content/blog/amp.md -- --- Title: AMP only outputs: [ "amp" ] menu: "main" --- ` b := Test(t, files) b.AssertFileContent("public/index.html", "AMP and HTML|/blog/html-amp/|AMP only|/amp/blog/amp/|Home Sweet Home|/|HTML only|/blog/html/|") b.AssertFileContent("public/amp/index.html", "AMP and HTML|/amp/blog/html-amp/|AMP only|/amp/blog/amp/|Home Sweet Home|/amp/|HTML only|/blog/html/|") } // https://github.com/gohugoio/hugo/issues/5989 func TestMenusPageSortByDate(t *testing.T) { files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/home.html -- {{ range .Site.Menus.main }}{{ .Title }}|Children: {{- $children := sort .Children ".Page.Date" "desc" }}{{ range $children }}{{ .Title }}|{{ end }}{{ end }} -- content/blog/a.md -- --- Title: A date: 2019-01-01 menu: main: identifier: "a" weight: 1 --- -- content/blog/b.md -- --- Title: B date: 2018-01-02 menu: main: parent: "a" weight: 100 --- -- content/blog/c.md -- --- Title: C date: 2019-01-03 menu: main: parent: "a" weight: 10 --- ` b := Test(t, files) b.AssertFileContent("public/index.html", "A|Children:C|B|") } func TestMenuParams(t *testing.T) { files := ` -- hugo.toml -- baseURL = "http://example.com/" [[menus.main]] identifier = "contact" title = "Contact Us" url = "mailto:noreply@example.com" weight = 300 [menus.main.params] foo = "foo_config" key2 = "key2_config" camelCase = "camelCase_config" -- layouts/home.html -- Main: {{ len .Site.Menus.main }} {{ range .Site.Menus.main }} foo: {{ .Params.foo }} key2: {{ .Params.KEy2 }} camelCase: {{ .Params.camelcase }} {{ end }} -- content/_index.md -- --- title: "Home" menu: main: weight: 10 params: foo: "foo_content" key2: "key2_content" camelCase: "camelCase_content" --- ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Main: 2 foo: foo_content key2: key2_content camelCase: camelCase_content foo: foo_config key2: key2_config camelCase: camelCase_config `) } func TestMenusShadowMembers(t *testing.T) { files := ` -- hugo.toml -- baseURL = "http://example.com/" [[menus.main]] identifier = "contact" pageRef = "contact" title = "Contact Us" url = "mailto:noreply@example.com" weight = 1 [[menus.main]] pageRef = "/blog/post3" title = "My Post 3" url = "/blog/post3" -- layouts/home.html -- Main: {{ len .Site.Menus.main }} {{ range .Site.Menus.main }} {{ .Title }}|HasMenuCurrent: {{ $.HasMenuCurrent "main" . }}|Page: {{ .Page.Path }} {{ .Title }}|IsMenuCurrent: {{ $.IsMenuCurrent "main" . }}|Page: {{ .Page.Path }} {{ end }} -- layouts/single.html -- Main: {{ len .Site.Menus.main }} {{ range .Site.Menus.main }} {{ .Title }}|HasMenuCurrent: {{ $.HasMenuCurrent "main" . }}|Page: {{ .Page.Path }} {{ .Title }}|IsMenuCurrent: {{ $.IsMenuCurrent "main" . }}|Page: {{ .Page.Path }} {{ end }} -- content/_index.md -- --- title: "Home" menu: main: weight: 10 --- -- content/blog/_index.md -- --- title: "Blog" menu: main: weight: 20 --- -- content/blog/post1.md -- --- title: "My Post 1: With No Menu Defined" --- -- content/blog/post2.md -- --- title: "My Post 2: With Menu Defined" menu: main: weight: 30 --- -- content/blog/post3.md -- --- title: "My Post 2: With No Menu Defined" --- -- content/contact.md -- --- title: "Contact: With No Menu Defined" --- ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Main: 5 Home|HasMenuCurrent: false|Page: / Blog|HasMenuCurrent: false|Page: /blog My Post 2: With Menu Defined|HasMenuCurrent: false|Page: /blog/post2 My Post 3|HasMenuCurrent: false|Page: /blog/post3 Contact Us|HasMenuCurrent: false|Page: /contact `) b.AssertFileContent("public/blog/post1/index.html", ` Home|HasMenuCurrent: false|Page: / Blog|HasMenuCurrent: true|Page: /blog `) b.AssertFileContent("public/blog/post2/index.html", ` Home|HasMenuCurrent: false|Page: / Blog|HasMenuCurrent: true|Page: /blog Blog|IsMenuCurrent: false|Page: /blog `) b.AssertFileContent("public/blog/post3/index.html", ` Home|HasMenuCurrent: false|Page: / Blog|HasMenuCurrent: true|Page: /blog `) b.AssertFileContent("public/contact/index.html", ` Contact Us|HasMenuCurrent: false|Page: /contact Contact Us|IsMenuCurrent: true|Page: /contact Blog|HasMenuCurrent: false|Page: /blog Blog|IsMenuCurrent: false|Page: /blog `) } // Issue 9846 func TestMenuHasMenuCurrentSection(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['RSS','sitemap','taxonomy','term'] [[menu.main]] name = 'Home' pageRef = '/' weight = 1 [[menu.main]] name = 'Tests' pageRef = '/tests' weight = 2 [[menu.main]] name = 'Test 1' pageRef = '/tests/test-1' parent = 'Tests' weight = 1 -- content/tests/test-1.md -- --- title: "Test 1" --- -- layouts/list.html -- {{ range site.Menus.main }} {{ .Name }}|{{ .URL }}|IsMenuCurrent = {{ $.IsMenuCurrent "main" . }}|HasMenuCurrent = {{ $.HasMenuCurrent "main" . }}| {{ range .Children }} {{ .Name }}|{{ .URL }}|IsMenuCurrent = {{ $.IsMenuCurrent "main" . }}|HasMenuCurrent = {{ $.HasMenuCurrent "main" . }}| {{ end }} {{ end }} {{/* Some tests for issue 9925 */}} {{ $page := .Site.GetPage "tests/test-1" }} {{ $section := site.GetPage "tests" }} Home IsAncestor Self: {{ site.Home.IsAncestor site.Home }} Home IsDescendant Self: {{ site.Home.IsDescendant site.Home }} Section IsAncestor Self: {{ $section.IsAncestor $section }} Section IsDescendant Self: {{ $section.IsDescendant $section}} Page IsAncestor Self: {{ $page.IsAncestor $page }} Page IsDescendant Self: {{ $page.IsDescendant $page}} ` b := Test(t, files) b.AssertFileContent("public/tests/index.html", ` Tests|/tests/|IsMenuCurrent = true|HasMenuCurrent = false Home IsAncestor Self: false Home IsDescendant Self: false Section IsAncestor Self: false Section IsDescendant Self: false Page IsAncestor Self: false Page IsDescendant Self: false `) } func TestMenusNewConfigSetup(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" title = "Hugo Menu Test" [menus] [[menus.main]] name = "Home" url = "/" pre = "<span>" post = "</span>" weight = 1 -- layouts/home.html -- {{ range $i, $e := site.Menus.main }} Menu Item: {{ $i }}: {{ .Pre }}{{ .Name }}{{ .Post }}|{{ .URL }}| {{ end }} ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Menu Item: 0: <span>Home</span>|/| `) } // Issue #11062 func TestMenusSubDirInBaseURL(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/foo/" title = "Hugo Menu Test" [menus] [[menus.main]] name = "Posts" url = "/posts" weight = 1 -- layouts/home.html -- {{ range $i, $e := site.Menus.main }} Menu Item: {{ $i }}|{{ .URL }}| {{ end }} ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Menu Item: 0|/foo/posts| `) } func TestSectionPagesMenuMultilingualWarningIssue12306(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['section','rss','sitemap','taxonomy','term'] defaultContentLanguageInSubdir = true sectionPagesMenu = "main" [languages.en] [languages.fr] -- layouts/home.html -- {{- range site.Menus.main -}} <a href="{{ .URL }}">{{ .Name }}</a> {{- end -}} -- layouts/single.html -- {{ .Title }} -- content/p1.en.md -- --- title: p1 menu: main --- -- content/p1.fr.md -- --- title: p1 menu: main --- -- content/p2.en.md -- --- title: p2 menu: main --- ` b := Test(t, files, TestOptWarn()) b.AssertFileContent("public/en/index.html", `<a href="/en/p1/">p1</a><a href="/en/p2/">p2</a>`) b.AssertFileContent("public/fr/index.html", `<a href="/fr/p1/">p1</a>`) b.AssertLogContains("! WARN") } func TestSectionPagesIssue12399(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','sitemap','taxonomy','term'] capitalizeListTitles = false pluralizeListTitles = false sectionPagesMenu = 'main' -- content/p1.md -- --- title: p1 --- -- content/s1/p2.md -- --- title: p2 menus: main --- -- content/s1/p3.md -- --- title: p3 --- -- layouts/list.html -- {{ range site.Menus.main }}<a href="{{ .URL }}">{{ .Name }}</a>{{ end }} -- layouts/single.html -- {{ .Title }} ` b := Test(t, files) b.AssertFileExists("public/index.html", true) b.AssertFileContent("public/index.html", `<a href="/s1/p2/">p2</a><a href="/s1/">s1</a>`) } // Issue 13161 func TestMenuNameAndTitleFallback(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','sitemap','taxonomy','term'] [[menus.main]] name = 'P1_ME_Name' title = 'P1_ME_Title' pageRef = '/p1' weight = 10 [[menus.main]] pageRef = '/p2' weight = 20 [[menus.main]] pageRef = '/p3' weight = 30 [[menus.main]] name = 'S1_ME_Name' title = 'S1_ME_Title' pageRef = '/s1' weight = 40 [[menus.main]] pageRef = '/s2' weight = 50 [[menus.main]] pageRef = '/s3' weight = 60 -- content/p1.md -- --- title: P1_Title --- -- content/p2.md -- --- title: P2_Title --- -- content/p3.md -- --- title: P3_Title linkTitle: P3_LinkTitle --- -- content/s1/_index.md -- --- title: S1_Title --- -- content/s2/_index.md -- --- title: S2_Title --- -- content/s3/_index.md -- --- title: S3_Title linkTitle: S3_LinkTitle --- -- layouts/single.html -- {{ .Content }} -- layouts/list.html -- {{ .Content }} -- layouts/home.html -- {{- range site.Menus.main }} URL: {{ .URL }}| Name: {{ .Name }}| Title: {{ .Title }}| PageRef: {{ .PageRef }}| Page.Title: {{ .Page.Title }}| Page.LinkTitle: {{ .Page.LinkTitle }}| {{- end }} ` b := Test(t, files) b.AssertFileContent("public/index.html", `URL: /p1/| Name: P1_ME_Name| Title: P1_ME_Title| PageRef: /p1| Page.Title: P1_Title| Page.LinkTitle: P1_Title|`, `URL: /p2/| Name: P2_Title| Title: P2_Title| PageRef: /p2| Page.Title: P2_Title| Page.LinkTitle: P2_Title|`, `URL: /p3/| Name: P3_LinkTitle| Title: P3_Title| PageRef: /p3| Page.Title: P3_Title| Page.LinkTitle: P3_LinkTitle|`, `URL: /s1/| Name: S1_ME_Name| Title: S1_ME_Title| PageRef: /s1| Page.Title: S1_Title| Page.LinkTitle: S1_Title|`, `URL: /s2/| Name: S2_Title| Title: S2_Title| PageRef: /s2| Page.Title: S2_Title| Page.LinkTitle: S2_Title|`, `URL: /s3/| Name: S3_LinkTitle| Title: S3_Title| PageRef: /s3| Page.Title: S3_Title| Page.LinkTitle: S3_LinkTitle|`, ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/config.go
hugolib/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 hugolib import ( "os" "path/filepath" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/allconfig" "github.com/spf13/afero" ) // DefaultConfig returns the default configuration. func DefaultConfig() *allconfig.Config { fs := afero.NewMemMapFs() all, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Fs: fs, Environ: []string{"none"}}) if err != nil { panic(err) } return all.Base } // ExampleConfig returns the some example configuration for documentation. func ExampleConfig() (*allconfig.Config, error) { // Apply some example settings for the settings that does not come with a sensible default. configToml := ` title = 'My Blog' baseURL = "https://example.com/" disableKinds = ["term", "taxonomy"] [outputs] home = ['html', 'html', 'rss'] page = ['html'] [imaging] bgcolor = '#ffffff' hint = 'photo' quality = 81 resamplefilter = 'CatmullRom' [imaging.exif] disableDate = true disableLatLong = true excludeFields = 'ColorSpace|Metering' [params] color = 'blue' style = 'dark' [languages] [languages.ar] languagedirection = 'rtl' title = 'مدونتي' weight = 2 [languages.en] weight = 1 [languages.fr] weight = 2 [languages.fr.params] linkedin = 'https://linkedin.com/fr/whoever' color = 'green' [[languages.fr.menus.main]] name = 'Des produits' pageRef = '/products' weight = 20 [menus] [[menus.main]] name = 'Home' pageRef = '/' weight = 10 [[menus.main]] name = 'Products' pageRef = '/products' weight = 20 [[menus.main]] name = 'Services' pageRef = '/services' weight = 30 [deployment] order = [".jpg$", ".gif$"] [[deployment.targets]] name = "mydeployment" url = "s3://mybucket?region=us-east-1" cloudFrontDistributionID = "mydistributionid" [[deployment.matchers]] pattern = "^.+\\.(js|css|svg|ttf)$" cacheControl = "max-age=31536000, no-transform, public" gzip = true [[deployment.matchers]] pattern = "^.+\\.(png|jpg)$" cacheControl = "max-age=31536000, no-transform, public" gzip = false [[deployment.matchers]] pattern = "^sitemap\\.xml$" contentType = "application/xml" gzip = true [[deployment.matchers]] pattern = "^.+\\.(html|xml|json)$" gzip = true [permalinks] posts = '/posts/:year/:month/:title/' [taxonomies] category = 'categories' series = 'series' tag = 'tags' [module] [module.hugoVersion] min = '0.80.0' [[module.imports]] path = "github.com/bep/hugo-mod-misc/dummy-content" ignoreconfig = true ignoreimports = true [[module.mounts]] source = "content/blog" target = "content" [minify] [minify.tdewolff] [minify.tdewolff.json] precision = 2 [[cascade]] background = 'yosemite.jpg' [cascade._target] kind = 'page' path = '/blog/**' [[cascade]] background = 'goldenbridge.jpg' [cascade._target] kind = 'section' ` goMod := ` module github.com/bep/mymod ` cfg := config.New() tempDir := os.TempDir() cacheDir := filepath.Join(tempDir, "hugocache") if err := os.MkdirAll(cacheDir, 0o777); err != nil { return nil, err } cfg.Set("cacheDir", cacheDir) cfg.Set("workingDir", tempDir) defer func() { os.RemoveAll(tempDir) }() fs := afero.NewOsFs() if err := afero.WriteFile(fs, filepath.Join(tempDir, "hugo.toml"), []byte(configToml), 0o644); err != nil { return nil, err } if err := afero.WriteFile(fs, filepath.Join(tempDir, "go.mod"), []byte(goMod), 0o644); err != nil { return nil, err } conf, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Fs: fs, Flags: cfg, Environ: []string{"none"}}) if err != nil { return nil, err } return conf.Base, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page_unwrap_test.go
hugolib/page_unwrap_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/resources/page" ) func TestUnwrapPage(t *testing.T) { c := qt.New(t) p := &pageState{} c.Assert(mustUnwrap(newPageForShortcode(p)), qt.Equals, p) c.Assert(mustUnwrap(newPageForRenderHook(p)), qt.Equals, p) } func mustUnwrap(v any) page.Page { p, err := unwrapPage(v) if err != nil { panic(err) } return p }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/renderstring_test.go
hugolib/renderstring_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 requiredF by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" qt "github.com/frankban/quicktest" ) func TestRenderString(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/home.html -- {{ $p := site.GetPage "p1.md" }} {{ $optBlock := dict "display" "block" }} {{ $optOrg := dict "markup" "org" }} RSTART:{{ "**Bold Markdown**" | $p.RenderString }}:REND RSTART:{{ "**Bold Block Markdown**" | $p.RenderString $optBlock }}:REND RSTART:{{ "/italic org mode/" | $p.RenderString $optOrg }}:REND RSTART:{{ "## Header2" | $p.RenderString }}:REND -- layouts/_markup/render-heading.html -- Hook Heading: {{ .Level }} -- content/p1.md -- --- title: "p1" --- ` b := Test(t, files) b.AssertFileContent("public/index.html", ` RSTART:<strong>Bold Markdown</strong>:REND RSTART:<p><strong>Bold Block Markdown</strong></p> RSTART:<em>italic org mode</em>:REND RSTART:Hook Heading: 2:REND `) } // https://github.com/gohugoio/hugo/issues/6882 func TestRenderStringOnListPage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/home.html -- {{ .RenderString "**Hello**" }} -- layouts/list.html -- {{ .RenderString "**Hello**" }} -- layouts/single.html -- {{ .RenderString "**Hello**" }} -- content/mysection/p1.md -- FOO ` b := Test(t, files) for _, filename := range []string{ "index.html", "mysection/index.html", "categories/index.html", "tags/index.html", "mysection/p1/index.html", } { b.AssertFileContent("public/"+filename, `<strong>Hello</strong>`) } } // Issue 9433 func TestRenderStringOnPageNotBackedByAFile(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["page", "section", "taxonomy", "term"] -- layouts/home.html -- {{ .RenderString "**Hello**" }} -- content/p1.md -- ` b, err := TestE(t, files) // Removed WithLogger(logger) b.Assert(err, qt.IsNil) } func TestRenderStringWithShortcode(t *testing.T) { t.Parallel() filesTemplate := ` -- hugo.toml -- title = "Hugo Rocks!" enableInlineShortcodes = true -- content/p1/index.md -- --- title: "P1" --- ## First -- layouts/_shortcodes/mark1.md -- {{ .Inner }} -- layouts/_shortcodes/mark2.md -- 1. Item Mark2 1 1. Item Mark2 2 1. Item Mark2 2-1 1. Item Mark2 3 -- layouts/_shortcodes/myhthml.html -- Title: {{ .Page.Title }} TableOfContents: {{ .Page.TableOfContents }} Page Type: {{ printf "%T" .Page }} -- layouts/single.html -- {{ .RenderString "Markdown: {{% mark2 %}}|HTML: {{< myhthml >}}|Inline: {{< foo.inline >}}{{ site.Title }}{{< /foo.inline >}}|" }} HasShortcode: mark2:{{ .HasShortcode "mark2" }}:true HasShortcode: foo:{{ .HasShortcode "foo" }}:false ` t.Run("Basic", func(t *testing.T) { b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: filesTemplate, }, ).Build() b.AssertFileContent("public/p1/index.html", "<p>Markdown: 1. Item Mark2 1</p>\n<ol>\n<li>Item Mark2 2\n<ol>\n<li>Item Mark2 2-1</li>\n</ol>\n</li>\n<li>Item Mark2 3|", "<a href=\"#first\">First</a>", // ToC ` HTML: Title: P1 Inline: Hugo Rocks! HasShortcode: mark2:true:true HasShortcode: foo:false:false Page Type: *hugolib.pageForShortcode`, ) }) t.Run("Edit shortcode", func(t *testing.T) { b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: filesTemplate, Running: true, }, ).Build() b.EditFiles("layouts/_shortcodes/myhthml.html", "Edit shortcode").Build() b.AssertFileContent("public/p1/index.html", `Edit shortcode`, ) }) } // Issue 9959 func TestRenderStringWithShortcodeInPageWithNoContentFile(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- layouts/_shortcodes/myshort.html -- Page Kind: {{ .Page.Kind }} -- layouts/home.html -- Short: {{ .RenderString "{{< myshort >}}" }} Has myshort: {{ .HasShortcode "myshort" }} Has other: {{ .HasShortcode "other" }} ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Page Kind: home Has myshort: true Has other: false `) } func TestRenderStringWithShortcodeIssue10654(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- timeout = '300ms' -- content/p1.md -- --- title: "P1" --- {{< toc >}} ## Heading 1 {{< noop >}} {{ not a shortcode {{< /noop >}} } -- layouts/_shortcodes/noop.html -- {{ .Inner | $.Page.RenderString }} -- layouts/_shortcodes/toc.html -- {{ .Page.TableOfContents }} -- layouts/single.html -- {{ .Content }} ` b := Test(t, files) b.AssertFileContent("public/p1/index.html", `TableOfContents`) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/codeowners.go
hugolib/codeowners.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "io" "path" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources/page" "github.com/hairyhenderson/go-codeowners" "github.com/spf13/afero" ) var afs = afero.NewOsFs() func findCodeOwnersFile(dir string) (io.Reader, error) { for _, p := range []string{".", "docs", ".github", ".gitlab"} { f := path.Join(dir, p, "CODEOWNERS") _, err := afs.Stat(f) if err != nil { if herrors.IsNotExist(err) { continue } return nil, err } return afs.Open(f) } return nil, nil } type codeownerInfo struct { owners *codeowners.Codeowners } func (c *codeownerInfo) forPage(p page.Page) []string { return c.owners.Owners(p.File().Filename()) } func newCodeOwners(workingDir string) (*codeownerInfo, error) { r, err := findCodeOwnersFile(workingDir) if err != nil || r == nil { return nil, err } owners, err := codeowners.FromReader(r, workingDir) if err != nil { return nil, err } return &codeownerInfo{owners: owners}, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/taxonomy_test.go
hugolib/taxonomy_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 hugolib import ( "fmt" "testing" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" qt "github.com/frankban/quicktest" ) func TestTaxonomiesCountOrder(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" titleCaseStyle = "none" [taxonomies] tag = "tags" category = "categories" -- content/page.md -- --- tags: ['a', 'B', 'c'] categories: 'd' --- YAML frontmatter with tags and categories taxonomy. ` b := Test(t, files) s := b.H.Sites[0] st := make([]string, 0) for _, t := range s.Taxonomies()["tags"].ByCount() { st = append(st, t.Page().Title()+":"+t.Name) } expect := []string{"a:a", "B:b", "c:c"} b.Assert(st, qt.DeepEquals, expect) } // https://github.com/gohugoio/hugo/issues/5513 // https://github.com/gohugoio/hugo/issues/5571 func TestTaxonomiesPathSeparation(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" titleCaseStyle = "none" [taxonomies] "news/tag" = "news/tags" "news/category" = "news/categories" "t1/t2/t3" = "t1/t2/t3s" "s1/s2/s3" = "s1/s2/s3s" -- content/page.md -- +++ title = "foo" "news/categories" = ["a", "b", "c", "d/e", "f/g/h"] "t1/t2/t3s" = ["t4/t5", "t4/t5/t6"] +++ Content. -- content/news/categories/b/_index.md -- --- title: "This is B" --- -- content/news/categories/f/g/h/_index.md -- --- title: "This is H" --- -- content/t1/t2/t3s/t4/t5/_index.md -- --- title: "This is T5" --- -- content/s1/s2/s3s/_index.md -- --- title: "This is S3s" --- -- layouts/list.html -- Taxonomy List Page 1|{{ .Title }}|Hello|{{ .Permalink }}| -- layouts/taxonomy.html -- Taxonomy Page 1|{{ .Title }}|Hello|{{ .Permalink }}| ` b := Test(t, files) s := b.H.Sites[0] filterbyKind := func(kind string) page.Pages { var pages page.Pages for _, p := range s.Pages() { if p.Kind() == kind { pages = append(pages, p) } } return pages } ta := filterbyKind(kinds.KindTerm) te := filterbyKind(kinds.KindTaxonomy) b.Assert(len(te), qt.Equals, 4) b.Assert(len(ta), qt.Equals, 7) b.AssertFileContent("public/news/categories/a/index.html", "Taxonomy List Page 1|a|Hello|https://example.com/news/categories/a/|") b.AssertFileContent("public/news/categories/b/index.html", "Taxonomy List Page 1|This is B|Hello|https://example.com/news/categories/b/|") b.AssertFileContent("public/news/categories/d/e/index.html", "Taxonomy List Page 1|d/e|Hello|https://example.com/news/categories/d/e/|") b.AssertFileContent("public/news/categories/f/g/h/index.html", "Taxonomy List Page 1|This is H|Hello|https://example.com/news/categories/f/g/h/|") b.AssertFileContent("public/t1/t2/t3s/t4/t5/index.html", "Taxonomy List Page 1|This is T5|Hello|https://example.com/t1/t2/t3s/t4/t5/|") b.AssertFileContent("public/t1/t2/t3s/t4/t5/t6/index.html", "Taxonomy List Page 1|t4/t5/t6|Hello|https://example.com/t1/t2/t3s/t4/t5/t6/|") b.AssertFileContent("public/news/categories/index.html", "Taxonomy Page 1|categories|Hello|https://example.com/news/categories/|") b.AssertFileContent("public/t1/t2/t3s/index.html", "Taxonomy Page 1|t3s|Hello|https://example.com/t1/t2/t3s/|") b.AssertFileContent("public/s1/s2/s3s/index.html", "Taxonomy Page 1|This is S3s|Hello|https://example.com/s1/s2/s3s/|") } // https://github.com/gohugoio/hugo/issues/5719 func TestTaxonomiesNextGenLoops(t *testing.T) { t.Parallel() pageContent := ` --- Title: "Taxonomy!" tags: ["Hugo Rocks!", "Rocks I say!" ] categories: ["This is Cool", "And new" ] --- Content. ` files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/home.html -- <h1>Tags</h1> <ul> {{ range .Site.Taxonomies.tags }} <li><a href="{{ .Page.Permalink }}">{{ .Page.Title }}</a> {{ .Count }}</li> {{ end }} </ul> -- layouts/taxonomy.html -- <h1>Terms</h1> <ul> {{ range .Data.Terms.Alphabetical }} <li><a href="{{ .Page.Permalink }}">{{ .Page.Title }}</a> {{ .Count }}</li> {{ end }} </ul> ` for i := range 10 { files += fmt.Sprintf("\n-- content/page%d.md --\n%s", i+1, pageContent) } b := Test(t, files) b.AssertFileContent("public/index.html", `<li><a href="http://example.com/tags/hugo-rocks/">Hugo Rocks!</a> 10</li>`) b.AssertFileContent("public/categories/index.html", `<li><a href="http://example.com/categories/this-is-cool/">This Is Cool</a> 10</li>`) b.AssertFileContent("public/tags/index.html", `<li><a href="http://example.com/tags/rocks-i-say/">Rocks I Say!</a> 10</li>`) } // Issue 6213 func TestTaxonomiesNotForDrafts(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/list.html -- List page. -- content/draft.md -- --- title: "Draft" draft: true categories: ["drafts"] --- -- content/regular.md -- --- title: "Not Draft" categories: ["regular"] --- ` b := Test(t, files) s := b.H.Sites[0] b.AssertFileExists("public/categories/regular/index.html", true) b.AssertFileExists("public/categories/drafts/index.html", false) reg, _ := s.getPage(nil, "categories/regular") dra, _ := s.getPage(nil, "categories/draft") b.Assert(reg, qt.Not(qt.IsNil)) b.Assert(dra, qt.IsNil) } func TestTaxonomiesIndexDraft(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com" -- content/categories/_index.md -- --- title: "The Categories" draft: true --- Content. -- content/page.md -- --- title: "The Page" categories: ["cool"] --- Content. -- layouts/home.html -- {{ range .Site.Pages }} {{ .RelPermalink }}|{{ .Title }}|{{ .WordCount }}|{{ .Content }}| {{ end }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "! /categories/|") } // https://github.com/gohugoio/hugo/issues/6927 func TestTaxonomiesHomeDraft(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com" -- content/_index.md -- --- title: "Home" draft: true --- Content. -- content/posts/_index.md -- --- title: "Posts" draft: true --- Content. -- content/posts/page.md -- --- title: "The Page" categories: ["cool"] --- Content. -- layouts/home.html -- NO HOME FOR YOU ` b := Test(t, files) b.AssertFileExists("public/index.html", false) b.AssertFileExists("public/categories/index.html", false) b.AssertFileExists("public/posts/index.html", false) } // https://github.com/gohugoio/hugo/issues/6173 func TestTaxonomiesWithBundledResources(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/list.html -- List {{ .Title }}: {{ range .Resources }} Resource: {{ .RelPermalink }}|{{ .MediaType }} {{ end }} -- content/p1.md -- --- title: Page categories: ["funny"] --- -- content/categories/_index.md -- --- title: Categories Page --- -- content/categories/data.json -- Category data -- content/categories/funny/_index.md -- --- title: Funny Category --- -- content/categories/funny/funnydata.json -- Category funny data ` b := Test(t, files) b.AssertFileContent("public/categories/index.html", `Resource: /categories/data.json|application/json`) b.AssertFileContent("public/categories/funny/index.html", `Resource: /categories/funny/funnydata.json|application/json`) } func TestTaxonomiesRemoveOne(t *testing.T) { files := ` -- hugo.toml -- disableLiveReload = true -- layouts/home.html -- {{ $cats := .Site.Taxonomies.categories.cats }} {{ if $cats }} Len cats: {{ len $cats }} {{ range $cats }} Cats:|{{ .Page.RelPermalink }}| {{ end }} {{ end }} {{ $funny := .Site.Taxonomies.categories.funny }} {{ if $funny }} Len funny: {{ len $funny }} {{ range $funny }} Funny:|{{ .Page.RelPermalink }}| {{ end }} {{ end }} -- content/p1.md -- --- title: Page categories: ["funny", "cats"] --- -- content/p2.md -- --- title: Page2 categories: ["funny", "cats"] --- ` b := TestRunning(t, files) b.AssertFileContent("public/index.html", ` Len cats: 2 Len funny: 2 Cats:|/p1/| Cats:|/p2/| Funny:|/p1/| Funny:|/p2/|`) // Remove one category from one of the pages. b.EditFiles("content/p1.md", `--- title: Page categories: ["funny"] --- `) b.Build() b.AssertFileContent("public/index.html", ` Len cats: 1 Len funny: 2 Cats:|/p2/| Funny:|/p1/| Funny:|/p2/|`) } // https://github.com/gohugoio/hugo/issues/6590 func TestTaxonomiesListPages(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/list.html -- {{ template "print-taxo" "categories.cats" }} {{ template "print-taxo" "categories.funny" }} {{ define "print-taxo" }} {{ $node := index site.Taxonomies (split $ ".") }} {{ if $node }} Len {{ $ }}: {{ len $node }} {{ range $node }} {{ $ }}:|{{ .Page.RelPermalink }}| {{ end }} {{ else }} {{ $ }} not found. {{ end }} {{ end }} -- content/_index.md -- --- title: Home categories: ["funny", "cats"] --- -- content/blog/p1.md -- --- title: Page1 categories: ["funny"] --- -- content/blog/_index.md -- --- title: Blog Section categories: ["cats"] --- ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Len categories.cats: 2 categories.cats:|/blog/| categories.cats:|/| Len categories.funny: 2 categories.funny:|/| categories.funny:|/blog/p1/| `) } func TestTaxonomiesPageCollections(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/home.html -- {{ $home := site.Home }} {{ $section := site.GetPage "section" }} {{ $categories := site.GetPage "categories" }} {{ $funny := site.GetPage "categories/funny" }} {{ $cats := site.GetPage "categories/cats" }} {{ $p1 := site.GetPage "section/p1" }} Categories Pages: {{ range $categories.Pages}}{{.RelPermalink }}|{{ end }}:END Funny Pages: {{ range $funny.Pages}}{{.RelPermalink }}|{{ end }}:END Cats Pages: {{ range $cats.Pages}}{{.RelPermalink }}|{{ end }}:END P1 Terms: {{ range $p1.GetTerms "categories" }}{{.RelPermalink }}|{{ end }}:END Section Terms: {{ range $section.GetTerms "categories" }}{{.RelPermalink }}|{{ end }}:END Home Terms: {{ range $home.GetTerms "categories" }}{{.RelPermalink }}|{{ end }}:END Category Paginator {{ range $categories.Paginator.Pages }}{{ .RelPermalink }}|{{ end }}:END Cats Paginator {{ range $cats.Paginator.Pages }}{{ .RelPermalink }}|{{ end }}:END -- layouts/404.html -- 404 Terms: {{ range .GetTerms "categories" }}{{.RelPermalink }}|{{ end }}:END -- content/_index.md -- --- title: "Home Sweet Home" categories: [ "dogs", "gorillas"] --- -- content/section/_index.md -- --- title: "Section" categories: [ "cats", "dogs", "birds"] --- -- content/section/p1.md -- --- title: "Page1" categories: ["funny", "cats"] --- -- content/section/p2.md -- --- title: "Page2" categories: ["funny"] --- ` b := Test(t, files) cat, _ := b.H.Sites[0].GetPage("categories") funny, _ := b.H.Sites[0].GetPage("categories/funny") b.Assert(cat, qt.Not(qt.IsNil)) b.Assert(funny, qt.Not(qt.IsNil)) b.Assert(cat.Parent().IsHome(), qt.Equals, true) b.Assert(funny.Kind(), qt.Equals, "term") b.Assert(funny.Parent(), qt.Equals, cat) b.AssertFileContent("public/index.html", ` Categories Pages: /categories/birds/|/categories/cats/|/categories/dogs/|/categories/funny/|/categories/gorillas/|:END Funny Pages: /section/p1/|/section/p2/|:END Cats Pages: /section/p1/|/section/|:END P1 Terms: /categories/funny/|/categories/cats/|:END Section Terms: /categories/cats/|/categories/dogs/|/categories/birds/|:END Home Terms: /categories/dogs/|/categories/gorillas/|:END Cats Paginator /section/p1/|/section/|:END Category Paginator /categories/birds/|/categories/cats/|/categories/dogs/|/categories/funny/|/categories/gorillas/|:END`, ) b.AssertFileContent("public/404.html", "\n404 Terms: :END\n\t") b.AssertFileContent("public/categories/funny/index.xml", `<link>http://example.com/section/p1/</link>`) b.AssertFileContent("public/categories/index.xml", `<link>http://example.com/categories/funny/</link>`) } func TestTaxonomiesDirectoryOverlaps(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" titleCaseStyle = "none" [taxonomies] abcdef = "abcdefs" abcdefg = "abcdefgs" abcdefghi = "abcdefghis" -- layouts/home.html -- {{ range site.Pages }}Page: {{ template "print-page" . }} {{ end }} {{ $abc := site.GetPage "abcdefgs/abc" }} {{ $abcdefgs := site.GetPage "abcdefgs" }} abc: {{ template "print-page" $abc }}|IsAncestor: {{ $abc.IsAncestor $abcdefgs }}|IsDescendant: {{ $abc.IsDescendant $abcdefgs }} abcdefgs: {{ template "print-page" $abcdefgs }}|IsAncestor: {{ $abcdefgs.IsAncestor $abc }}|IsDescendant: {{ $abcdefgs.IsDescendant $abc }} {{ define "print-page" }}{{ .RelPermalink }}|{{ .Title }}|{{.Kind }}|Parent: {{ with .Parent }}{{ .RelPermalink }}{{ end }}|CurrentSection: {{ .CurrentSection.RelPermalink}}|FirstSection: {{ .FirstSection.RelPermalink }}{{ end }} -- content/abc/_index.md -- --- title: "abc" abcdefgs: [abc] --- -- content/abc/p1.md -- --- title: "abc-p" --- -- content/abcdefgh/_index.md -- --- title: "abcdefgh" --- -- content/abcdefgh/p1.md -- --- title: "abcdefgh-p" --- -- content/abcdefghijk/index.md -- --- title: "abcdefghijk" --- ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Page: /||home|Parent: |CurrentSection: /| Page: /abc/|abc|section|Parent: /|CurrentSection: /abc/| Page: /abc/p1/|abc-p|page|Parent: /abc/|CurrentSection: /abc/| Page: /abcdefgh/|abcdefgh|section|Parent: /|CurrentSection: /abcdefgh/| Page: /abcdefgh/p1/|abcdefgh-p|page|Parent: /abcdefgh/|CurrentSection: /abcdefgh/| Page: /abcdefghijk/|abcdefghijk|page|Parent: /|CurrentSection: /| Page: /abcdefghis/|abcdefghis|taxonomy|Parent: /|CurrentSection: /abcdefghis/| Page: /abcdefgs/|abcdefgs|taxonomy|Parent: /|CurrentSection: /abcdefgs/| Page: /abcdefs/|abcdefs|taxonomy|Parent: /|CurrentSection: /abcdefs/| abc: /abcdefgs/abc/|abc|term|Parent: /abcdefgs/|CurrentSection: /abcdefgs/abc/| abcdefgs: /abcdefgs/|abcdefgs|taxonomy|Parent: /|CurrentSection: /abcdefgs/| abc: /abcdefgs/abc/|abc|term|Parent: /abcdefgs/|CurrentSection: /abcdefgs/abc/|FirstSection: /abcdefgs/|IsAncestor: false|IsDescendant: true abcdefgs: /abcdefgs/|abcdefgs|taxonomy|Parent: /|CurrentSection: /abcdefgs/|FirstSection: /abcdefgs/|IsAncestor: true|IsDescendant: false `) } func TestTaxonomiesWeightSort(t *testing.T) { files := ` -- layouts/home.html -- {{ $a := site.GetPage "tags/a"}} :{{ range $a.Pages }}{{ .RelPermalink }}|{{ end }}: -- content/p1.md -- --- title: P1 weight: 100 tags: ['a'] tags_weight: 20 --- -- content/p3.md -- --- title: P2 weight: 200 tags: ['a'] tags_weight: 30 --- -- content/p2.md -- --- title: P3 weight: 50 tags: ['a'] tags_weight: 40 --- ` b := Test(t, files) b.AssertFileContent("public/index.html", `:/p1/|/p3/|/p2/|:`) } func TestTaxonomiesEmptyTagsString(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [taxonomies] tag = 'tags' -- content/p1.md -- +++ title = "P1" tags = '' +++ -- layouts/single.html -- Single. ` Test(t, files) } func TestTaxonomiesSpaceInName(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [taxonomies] authors = 'book authors' -- content/p1.md -- --- title: Good Omens book authors: - Neil Gaiman - Terry Pratchett --- -- layouts/home.html -- {{- $taxonomy := "book authors" }} Len Book Authors: {{ len (index .Site.Taxonomies $taxonomy) }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "Len Book Authors: 2") } func TestTaxonomiesListTermsHome(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" [taxonomies] tag = "tags" -- content/_index.md -- --- title: "Home" tags: ["a", "b", "c", "hello world"] --- -- content/tags/a/_index.md -- --- title: "A" --- -- content/tags/b/_index.md -- --- title: "B" --- -- content/tags/c/_index.md -- --- title: "C" --- -- content/tags/d/_index.md -- --- title: "D" --- -- content/tags/hello-world/_index.md -- --- title: "Hello World!" --- -- layouts/home.html -- Terms: {{ range site.Taxonomies.tags }}{{ .Page.Title }}: {{ .Count }}|{{ end }}$ ` b := Test(t, files) b.AssertFileContent("public/index.html", "Terms: A: 1|B: 1|C: 1|Hello World!: 1|$") } func TestTaxonomiesTermTitleAndTerm(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" [taxonomies] tag = "tags" -- content/_index.md -- --- title: "Home" tags: ["hellO world"] --- -- layouts/term.html -- {{ .Title }}|{{ .Kind }}|{{ .Data.Singular }}|{{ .Data.Plural }}|{{ .Page.Data.Term }}| ` b := Test(t, files) b.AssertFileContent("public/tags/hello-world/index.html", "HellO World|term|tag|tags|hellO world|") } func TestTermDraft(t *testing.T) { t.Parallel() files := ` -- layouts/list.html -- |{{ .Title }}| -- content/p1.md -- --- title: p1 tags: [a] --- -- content/tags/a/_index.md -- --- title: tag-a-title-override draft: true --- ` b := Test(t, files) b.AssertFileExists("public/tags/a/index.html", false) } func TestTermBuildNeverRenderNorList(t *testing.T) { t.Parallel() files := ` -- layouts/home.html -- |{{ len site.Taxonomies.tags }}| -- content/p1.md -- --- title: p1 tags: [a] --- -- content/tags/a/_index.md -- --- title: tag-a-title-override build: render: never list: never --- ` b := Test(t, files) b.AssertFileExists("public/tags/a/index.html", false) b.AssertFileContent("public/index.html", "|0|") } func TestTaxonomiesTermLookup(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" [taxonomies] tag = "tags" -- content/_index.md -- --- title: "Home" tags: ["a", "b"] --- -- layouts/taxonomy/tag.html -- Tag: {{ .Title }}| -- content/tags/a/_index.md -- --- title: tag-a-title-override --- ` b := Test(t, files) b.AssertFileContent("public/tags/a/index.html", "Tag: tag-a-title-override|") } func TestTaxonomyLookupIssue12193(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap'] [taxonomies] author = 'authors' -- layouts/list.html -- list.html -- layouts/authors/taxonomy.html -- authors/taxonomy.html -- content/authors/_index.md -- --- title: Authors Page --- ` b := Test(t, files) b.AssertFileExists("public/index.html", true) b.AssertFileExists("public/authors/index.html", true) b.AssertFileContent("public/authors/index.html", "authors/taxonomy.html") } func TestTaxonomyNestedEmptySectionsIssue12188(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','sitemap'] defaultContentLanguage = 'en' defaultContentLanguageInSubdir = true [languages.en] weight = 1 [languages.ja] weight = 2 [taxonomies] 's1/category' = 's1/category' -- layouts/single.html -- {{ .Title }}| -- layouts/list.html -- {{ .Title }}| -- content/s1/p1.en.md -- --- title: p1 --- ` b := Test(t, files) b.AssertFileExists("public/en/s1/index.html", true) b.AssertFileExists("public/en/s1/p1/index.html", true) b.AssertFileExists("public/en/s1/category/index.html", true) b.AssertFileExists("public/ja/s1/index.html", false) // failing test b.AssertFileExists("public/ja/s1/category/index.html", true) } func BenchmarkTaxonomiesGetTerms(b *testing.B) { createBuilder := func(b *testing.B, numPages int) *IntegrationTestBuilder { b.StopTimer() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["RSS", "sitemap", "section"] [taxononomies] tag = "tags" -- layouts/list.html -- List. -- layouts/single.html -- GetTerms.tags: {{ range .GetTerms "tags" }}{{ .Title }}|{{ end }} -- content/_index.md -- ` tagsVariants := []string{ "tags: ['a']", "tags: ['a', 'b']", "tags: ['a', 'b', 'c']", "tags: ['a', 'b', 'c', 'd']", "tags: ['a', 'b', 'd', 'e']", "tags: ['a', 'b', 'c', 'd', 'e']", "tags: ['a', 'd']", "tags: ['a', 'f']", } for i := 1; i < numPages; i++ { tags := tagsVariants[i%len(tagsVariants)] files += fmt.Sprintf("\n-- content/posts/p%d.md --\n---\n%s\n---", i+1, tags) } cfg := IntegrationTestConfig{ T: b, TxtarString: files, } bb := NewIntegrationTestBuilder(cfg) b.StartTimer() return bb } for _, numPages := range []int{100, 1000, 10000, 20000} { b.Run(fmt.Sprintf("pages_%d", numPages), func(b *testing.B) { for i := 0; b.Loop(); i++ { createBuilder(b, numPages).Build() } }) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/securitypolicies_test.go
hugolib/securitypolicies_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 hugolib import ( "fmt" "net/http" "net/http/httptest" "runtime" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/markup/asciidocext" "github.com/gohugoio/hugo/markup/pandoc" "github.com/gohugoio/hugo/markup/rst" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" ) func TestSecurityPolicies(t *testing.T) { c := qt.New(t) c.Run("os.GetEnv, denied", func(c *qt.C) { c.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" -- layouts/home.html -- {{ os.Getenv "FOOBAR" }} ` _, err := TestE(c, files) c.Assert(err, qt.IsNotNil) c.Assert(err, qt.ErrorMatches, `(?s).*"FOOBAR" is not whitelisted in policy "security\.funcs\.getenv".*`) }) c.Run("os.GetEnv, OK", func(c *qt.C) { c.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" -- layouts/home.html -- {{ os.Getenv "HUGO_FOO" }} ` Test(c, files) }) c.Run("AsciiDoc, denied", func(c *qt.C) { c.Parallel() if ok, err := asciidocext.Supports(); !ok { c.Skip(err) } files := ` -- hugo.toml -- baseURL = "https://example.org" -- content/page.ad -- foo ` _, err := TestE(c, files) c.Assert(err, qt.IsNotNil) c.Assert(err, qt.ErrorMatches, `(?s).*"asciidoctor" is not whitelisted in policy "security\.exec\.allow".*`) }) c.Run("RST, denied", func(c *qt.C) { c.Parallel() if !rst.Supports() { c.Skip() } files := ` -- hugo.toml -- baseURL = "https://example.org" -- content/page.rst -- foo ` _, err := TestE(c, files) c.Assert(err, qt.IsNotNil) if runtime.GOOS == "windows" { c.Assert(err, qt.ErrorMatches, `(?s).*python(\.exe)?" is not whitelisted in policy "security\.exec\.allow".*`) } else { c.Assert(err, qt.ErrorMatches, `(?s).*"rst2html(\.py)?" is not whitelisted in policy "security\.exec\.allow".*`) } }) c.Run("Pandoc, denied", func(c *qt.C) { c.Parallel() if !pandoc.Supports() { c.Skip() } files := ` -- hugo.toml -- baseURL = "https://example.org" -- content/page.pdc -- foo ` _, err := TestE(c, files) c.Assert(err, qt.IsNotNil) c.Assert(err, qt.ErrorMatches, `(?s).*pandoc" is not whitelisted in policy "security\.exec\.allow".*`) }) c.Run("Dart SASS, OK", func(c *qt.C) { c.Parallel() if !dartsass.Supports() { c.Skip() } files := ` -- hugo.toml -- baseURL = "https://example.org" -- layouts/home.html -- {{ $scss := "body { color: #333; }" | resources.FromString "foo.scss" | css.Sass (dict "transpiler" "dartsass") }} ` Test(c, files) }) c.Run("Dart SASS, denied", func(c *qt.C) { c.Parallel() if !dartsass.Supports() { c.Skip() } files := ` -- hugo.toml -- baseURL = "https://example.org" [security] [security.exec] allow="none" -- layouts/home.html -- {{ $scss := "body { color: #333; }" | resources.FromString "foo.scss" | css.Sass (dict "transpiler" "dartsass") }} ` _, err := TestE(c, files) c.Assert(err, qt.IsNotNil) c.Assert(err, qt.ErrorMatches, `(?s).*sass(-embedded)?" is not whitelisted in policy "security\.exec\.allow".*`) }) c.Run("resources.GetRemote, OK", func(c *qt.C) { c.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) c.Cleanup(func() { ts.Close() }) files := fmt.Sprintf(` -- hugo.toml -- baseURL = "https://example.org" -- layouts/home.html -- {{ $json := resources.GetRemote "%s/fruits.json" }}{{ $json.Content }} `, ts.URL) Test(c, files) }) c.Run("resources.GetRemote, denied method", func(c *qt.C) { c.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) c.Cleanup(func() { ts.Close() }) files := fmt.Sprintf(` -- hugo.toml -- baseURL = "https://example.org" -- layouts/home.html -- {{ $json := resources.GetRemote "%s/fruits.json" (dict "method" "DELETE" ) }}{{ $json.Content }} `, ts.URL) _, err := TestE(c, files) c.Assert(err, qt.IsNotNil) c.Assert(err, qt.ErrorMatches, `(?s).*"DELETE" is not whitelisted in policy "security\.http\.method".*`) }) c.Run("resources.GetRemote, denied URL", func(c *qt.C) { c.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) c.Cleanup(func() { ts.Close() }) files := fmt.Sprintf(` -- hugo.toml -- baseURL = "https://example.org" [security] [security.http] urls="none" -- layouts/home.html -- {{ $json := resources.GetRemote "%s/fruits.json" }}{{ $json.Content }} `, ts.URL) _, err := TestE(c, files) c.Assert(err, qt.IsNotNil) c.Assert(err, qt.ErrorMatches, `(?s).*is not whitelisted in policy "security\.http\.urls".*`) }) c.Run("resources.GetRemote, fake JSON", func(c *qt.C) { c.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) c.Cleanup(func() { ts.Close() }) files := fmt.Sprintf(` -- hugo.toml -- baseURL = "https://example.org" [security] -- layouts/home.html -- {{ $json := resources.GetRemote "%s/fakejson.json" }}{{ $json.Content }} `, ts.URL) _, err := TestE(c, files) c.Assert(err, qt.IsNotNil) c.Assert(err, qt.ErrorMatches, `(?s).*failed to resolve media type.*`) }) c.Run("resources.GetRemote, fake JSON whitelisted", func(c *qt.C) { c.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) c.Cleanup(func() { ts.Close() }) files := fmt.Sprintf(` -- hugo.toml -- baseURL = "https://example.org" [security] [security.http] mediaTypes=["application/json"] -- layouts/home.html -- {{ $json := resources.GetRemote "%s/fakejson.json" }}{{ $json.Content }} `, ts.URL) Test(c, files) }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/datafiles_test.go
hugolib/datafiles_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) func TestData(t *testing.T) { t.Run("with theme", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] theme = "mytheme" -- data/a.toml -- v1 = "a_v1" -- data/b.yaml -- v1: b_v1 -- data/c/d.yaml -- v1: c_d_v1 -- themes/mytheme/data/a.toml -- v1 = "a_v1_theme" -- themes/mytheme/data/d.toml -- v1 = "d_v1_theme" -- layouts/home.html -- a: {{ site.Data.a.v1 }}| b: {{ site.Data.b.v1 }}| cd: {{ site.Data.c.d.v1 }}| d: {{ site.Data.d.v1 }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "a: a_v1|\nb: b_v1|\ncd: c_d_v1|\nd: d_v1_theme|") }) } func TestDataMixedCaseFolders(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" -- data/MyFolder/MyData.toml -- v1 = "my_v1" -- layouts/home.html -- {{ site.Data }} v1: {{ site.Data.MyFolder.MyData.v1 }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "v1: my_v1|") } // Issue #12133 func TestDataNoAssets(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- assets/data/foo.toml -- content = "I am assets/data/foo.toml" -- layouts/home.html -- |{{ site.Data.foo.content }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "||") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/permalinker.go
hugolib/permalinker.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib var _ Permalinker = (*pageState)(nil) // Permalinker provides permalinks of both the relative and absolute kind. type Permalinker interface { Permalink() string RelPermalink() string }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/hugolib_integration_test.go
hugolib/hugolib_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 hugolib_test import ( "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) // Issue 9073 func TestPageTranslationsMap(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'https://example.org/' title = 'Issue-9073' defaultContentLanguageInSubdir = true [taxonomies] tag = 'tags' [languages.en] contentDir = 'content/en' weight = 1 disableKinds = ['RSS','sitemap'] [languages.de] contentDir = 'content/de' weight = 2 disableKinds = ['home', 'page', 'section', 'taxonomy', 'term','RSS','sitemap'] -- content/de/posts/p1.md -- --- title: P1 tags: ['T1'] --- -- content/en/posts/p1.md -- --- title: P1 tags: ['T1'] --- -- layouts/single.html -- <ul>{{ range .AllTranslations }}<li>{{ .Title }}-{{ .Lang }}</li>{{ end }}</ul> -- layouts/list.html -- <ul>{{ range .AllTranslations }}<li>{{ .Title }}-{{ .Lang }}</li>{{ end }}</ul> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ) b.Build() // Kind home b.AssertFileContent("public/en/index.html", "<ul><li>Issue-9073-en</li></ul>", ) // Kind section b.AssertFileContent("public/en/posts/index.html", "<ul><li>Posts-en</li></ul>", ) // Kind page b.AssertFileContent("public/en/posts/p1/index.html", "<ul><li>P1-en</li></ul>", ) // Kind taxonomy b.AssertFileContent("public/en/tags/index.html", "<ul><li>Tags-en</li></ul>", ) // Kind term b.AssertFileContent("public/en/tags/t1/index.html", "<ul><li>T1-en</li></ul>", ) } // Issue #11538 func TestRenderStringBadMarkupOpt(t *testing.T) { t.Parallel() files := ` -- layouts/home.html -- {{ $opts := dict "markup" "foo" }} {{ "something" | .RenderString $opts }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ) _, err := b.BuildE() want := `no content renderer found for markup "foo"` if !strings.Contains(err.Error(), want) { t.Errorf("error msg must contain %q, error msg actually contains %q", want, err.Error()) } } // Issue #11547 func TestTitleCaseStyleWithAutomaticSectionPages(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- titleCaseStyle = 'none' -- content/books/book-1.md -- --- title: Book 1 tags: [fiction] --- -- content/films/_index.md -- --- title: Films --- -- layouts/home.html -- {{ (site.GetPage "/tags").Title }} {{ (site.GetPage "/tags/fiction").Title }} {{ (site.GetPage "/books").Title }} {{ (site.GetPage "/films").Title }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ) b.Build() b.AssertFileContent("public/index.html", "tags\nfiction\nbooks\nFilms") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/rebuild_test.go
hugolib/rebuild_test.go
package hugolib import ( "fmt" "path/filepath" "strings" "testing" "time" "github.com/bep/logg" "github.com/fortytw2/leaktest" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/markup/asciidocext" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) const rebuildFilesSimple = ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["term", "taxonomy", "sitemap", "robotstxt", "404"] disableLiveReload = true [outputFormats] [outputFormats.rss] weight = 10 [outputFormats.html] weight = 20 [outputs] home = ["rss", "html"] section = ["html"] page = ["html"] -- content/mysection/_index.md -- --- title: "My Section" --- -- content/mysection/mysectionbundle/index.md -- --- title: "My Section Bundle" --- My Section Bundle Content. -- content/mysection/mysectionbundle/mysectionbundletext.txt -- My Section Bundle Text 2 Content. -- content/mysection/mysectionbundle/mysectionbundlecontent.md -- --- title: "My Section Bundle Content" --- My Section Bundle Content Content. -- content/mysection/_index.md -- --- title: "My Section" --- -- content/mysection/mysectiontext.txt -- Content. -- content/_index.md -- --- title: "Home" --- Home Content. -- content/hometext.txt -- Home Text Content. -- content/myothersection/myothersectionpage.md -- --- title: "myothersectionpage" --- myothersectionpage Content. -- content/mythirdsection/mythirdsectionpage.md -- --- title: "mythirdsectionpage" --- mythirdsectionpage Content. {{< myshortcodetext >}} §§§ myothertext foo §§§ -- assets/mytext.txt -- Assets My Text. -- assets/myshortcodetext.txt -- Assets My Shortcode Text. -- assets/myothertext.txt -- Assets My Other Text. -- layouts/single.html -- Single: {{ .Title }}|{{ .Content }}$ Resources: {{ range $i, $e := .Resources }}{{ $i }}:{{ .RelPermalink }}|{{ .Content }}|{{ end }}$ Len Resources: {{ len .Resources }}| -- layouts/list.html -- List: {{ .Title }}|{{ .Content }}$ Len Resources: {{ len .Resources }}| Resources: {{ range $i, $e := .Resources }}{{ $i }}:{{ .RelPermalink }}|{{ .Content }}|{{ end }}$ -- layouts/_shortcodes/foo.html -- Foo. -- layouts/_shortcodes/myshortcodetext.html -- {{ warnf "mytext %s" now}} {{ $r := resources.Get "myshortcodetext.txt" }} My Shortcode Text: {{ $r.Content }}|{{ $r.Permalink }}| -- layouts/_markup/render-codeblock-myothertext.html -- {{ $r := resources.Get "myothertext.txt" }} My Other Text: {{ $r.Content }}|{{ $r.Permalink }}| ` func TestRebuildEditLeafBundleHeaderOnly(t *testing.T) { t.Parallel() for range 3 { b := TestRunning(t, rebuildFilesSimple) b.AssertFileContent("public/mysection/mysectionbundle/index.html", "My Section Bundle Content Content.") b.EditFileReplaceAll("content/mysection/mysectionbundle/index.md", "My Section Bundle Content.", "My Section Bundle Content Edited.").Build() b.AssertFileContent("public/mysection/mysectionbundle/index.html", "My Section Bundle Content Edited.") b.AssertRenderCountPage(2) // home (rss) + bundle. b.AssertRenderCountContent(1) } } func TestRebuildEditTextFileInLeafBundle(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) b.AssertFileContent("public/mysection/mysectionbundle/index.html", "Resources: 0:/mysection/mysectionbundle/mysectionbundletext.txt|My Section Bundle Text 2 Content.|1:|<p>My Section Bundle Content Content.</p>\n|$") b.EditFileReplaceAll("content/mysection/mysectionbundle/mysectionbundletext.txt", "Content.", "Content Edited.").Build() b.AssertFileContent("public/mysection/mysectionbundle/index.html", "Text 2 Content Edited") b.AssertRenderCountPage(1) b.AssertRenderCountContent(0) } func TestRebuildAddingALeaffBundleIssue13925(t *testing.T) { t.Parallel() b := TestRunning(t, rebuildFilesSimple) b.AddFiles( "content/mysection/mysectionbundle2/index.md", "", "content/mysection/mysectionbundle2/mysectionbundletext.txt", "mysectionbundletext.txt").Build() b.AssertFileContent("public/mysection/mysectionbundle2/index.html", "Len Resources: 1|") b.AddFiles( "content/mynewsection/_index.md", "", "content/mynewsection/mynewsectiontext.txt", "foo").Build() b.AssertFileContent("public/mynewsection/index.html", "Len Resources: 1|") } func TestRebuildEditTextFileInShortcode(t *testing.T) { t.Parallel() for range 3 { b := TestRunning(t, rebuildFilesSimple) b.AssertFileContent("public/mythirdsection/mythirdsectionpage/index.html", "Text: Assets My Shortcode Text.") b.EditFileReplaceAll("assets/myshortcodetext.txt", "My Shortcode Text", "My Shortcode Text Edited").Build() fmt.Println(b.LogString()) b.AssertFileContent("public/mythirdsection/mythirdsectionpage/index.html", "Text: Assets My Shortcode Text Edited.") } } func TestRebuildEditTextFileInHook(t *testing.T) { t.Parallel() for range 3 { b := TestRunning(t, rebuildFilesSimple) b.AssertFileContent("public/mythirdsection/mythirdsectionpage/index.html", "Text: Assets My Other Text.") b.AssertFileContent("public/myothertext.txt", "Assets My Other Text.") b.EditFileReplaceAll("assets/myothertext.txt", "My Other Text", "My Other Text Edited").Build() b.AssertFileContent("public/mythirdsection/mythirdsectionpage/index.html", "Text: Assets My Other Text Edited.") } } func TestRebuiEditUnmarshaledYamlFileInLeafBundle(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableLiveReload = true disableKinds = ["taxonomy", "term", "sitemap", "robotsTXT", "404", "rss"] -- content/mybundle/index.md -- -- content/mybundle/mydata.yml -- foo: bar -- layouts/single.html -- MyData: {{ .Resources.Get "mydata.yml" | transform.Unmarshal }}| ` b := TestRunning(t, files) b.AssertFileContent("public/mybundle/index.html", "MyData: map[foo:bar]") b.EditFileReplaceAll("content/mybundle/mydata.yml", "bar", "bar edited").Build() b.AssertFileContent("public/mybundle/index.html", "MyData: map[foo:bar edited]") } func TestRebuildEditTextFileInHomeBundle(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) b.AssertFileContent("public/index.html", "Home Content.") b.AssertFileContent("public/index.html", "Home Text Content.") b.EditFileReplaceAll("content/hometext.txt", "Content.", "Content Edited.").Build() b.AssertFileContent("public/index.html", "Home Content.") b.AssertFileContent("public/index.html", "Home Text Content Edited.") b.AssertRenderCountPage(1) b.AssertRenderCountContent(0) } func TestRebuildEditTextFileInBranchBundle(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) b.AssertFileContent("public/mysection/index.html", "My Section", "0:/mysection/mysectiontext.txt|Content.|") b.EditFileReplaceAll("content/mysection/mysectiontext.txt", "Content.", "Content Edited.").Build() b.AssertFileContent("public/mysection/index.html", "My Section", "0:/mysection/mysectiontext.txt|Content Edited.|") b.AssertRenderCountPage(1) b.AssertRenderCountContent(0) } func testRebuildBothWatchingAndRunning(t *testing.T, files string, withB func(b *IntegrationTestBuilder)) { t.Helper() for _, opt := range []TestOpt{TestOptWatching(), TestOptRunning()} { b := Test(t, files, opt) withB(b) } } func TestRebuildRenameTextFileInLeafBundle(t *testing.T) { testRebuildBothWatchingAndRunning(t, rebuildFilesSimple, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/mysection/mysectionbundle/index.html", "My Section Bundle Text 2 Content.", "Len Resources: 2|") b.RenameFile("content/mysection/mysectionbundle/mysectionbundletext.txt", "content/mysection/mysectionbundle/mysectionbundletext2.txt").Build() b.AssertFileContent("public/mysection/mysectionbundle/index.html", "mysectionbundletext2", "My Section Bundle Text 2 Content.", "Len Resources: 2|") b.AssertRenderCountPage(8) b.AssertRenderCountContent(9) }) } func TestRebuilEditContentFileInLeafBundle(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) b.AssertFileContent("public/mysection/mysectionbundle/index.html", "My Section Bundle Content Content.") b.EditFileReplaceAll("content/mysection/mysectionbundle/mysectionbundlecontent.md", "Content Content.", "Content Content Edited.").Build() b.AssertFileContent("public/mysection/mysectionbundle/index.html", "My Section Bundle Content Content Edited.") } func TestRebuilEditContentFileThenAnother(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) b.EditFileReplaceAll("content/mysection/mysectionbundle/mysectionbundlecontent.md", "Content Content.", "Content Content Edited.").Build() b.AssertFileContent("public/mysection/mysectionbundle/index.html", "My Section Bundle Content Content Edited.") b.AssertRenderCountPage(1) b.AssertRenderCountContent(2) b.EditFileReplaceAll("content/myothersection/myothersectionpage.md", "myothersectionpage Content.", "myothersectionpage Content Edited.").Build() b.AssertFileContent("public/myothersection/myothersectionpage/index.html", "myothersectionpage Content Edited") b.AssertRenderCountPage(2) b.AssertRenderCountContent(2) } func TestRebuildRenameTextFileInBranchBundle(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) b.AssertFileContent("public/mysection/index.html", "My Section") b.RenameFile("content/mysection/mysectiontext.txt", "content/mysection/mysectiontext2.txt").Build() b.AssertFileContent("public/mysection/index.html", "mysectiontext2", "My Section") b.AssertRenderCountPage(3) b.AssertRenderCountContent(2) } func TestRebuildRenameTextFileInHomeBundle(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) b.AssertFileContent("public/index.html", "Home Text Content.") b.RenameFile("content/hometext.txt", "content/hometext2.txt").Build() b.AssertFileContent("public/index.html", "hometext2", "Home Text Content.") b.AssertRenderCountPage(5) } func TestRebuildRenameDirectoryWithLeafBundle(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) b.RenameDir("content/mysection/mysectionbundle", "content/mysection/mysectionbundlerenamed").Build() b.AssertFileContent("public/mysection/mysectionbundlerenamed/index.html", "My Section Bundle") b.AssertRenderCountPage(2) } func TestRebuildRenameDirectoryWithBranchBundle(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) b.RenameDir("content/mysection", "content/mysectionrenamed").Build() b.AssertFileContent("public/mysectionrenamed/index.html", "My Section") b.AssertFileContent("public/mysectionrenamed/mysectionbundle/index.html", "My Section Bundle") b.AssertFileContent("public/mysectionrenamed/mysectionbundle/mysectionbundletext.txt", "My Section Bundle Text 2 Content.") b.AssertRenderCountPage(5) } func TestRebuildRenameDirectoryWithRegularPageUsedInHome(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableLiveReload = true -- content/foo/p1.md -- --- title: "P1" --- -- layouts/home.html -- Pages: {{ range .Site.RegularPages }}{{ .RelPermalink }}|{{ end }}$ ` b := TestRunning(t, files) b.AssertFileContent("public/index.html", "Pages: /foo/p1/|$") b.RenameDir("content/foo", "content/bar").Build() b.AssertFileContent("public/index.html", "Pages: /bar/p1/|$") } func TestRebuildAddRegularFileRegularPageUsedInHomeMultilingual(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableLiveReload = true [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [languages.fr] weight = 3 [languages.a] weight = 4 [languages.b] weight = 5 [languages.c] weight = 6 [languages.d] weight = 7 [languages.e] weight = 8 [languages.f] weight = 9 [languages.g] weight = 10 [languages.h] weight = 11 [languages.i] weight = 12 [languages.j] weight = 13 -- content/foo/_index.md -- -- content/foo/data.txt -- -- content/foo/p1.md -- -- content/foo/p1.nn.md -- -- content/foo/p1.fr.md -- -- content/foo/p1.a.md -- -- content/foo/p1.b.md -- -- content/foo/p1.c.md -- -- content/foo/p1.d.md -- -- content/foo/p1.e.md -- -- content/foo/p1.f.md -- -- content/foo/p1.g.md -- -- content/foo/p1.h.md -- -- content/foo/p1.i.md -- -- content/foo/p1.j.md -- -- layouts/home.html -- RegularPages: {{ range .Site.RegularPages }}{{ .RelPermalink }}|{{ end }}$ ` b := TestRunning(t, files) b.AssertFileContent("public/index.html", "RegularPages: /foo/p1/|$") b.AssertFileContent("public/nn/index.html", "RegularPages: /nn/foo/p1/|$") b.AssertFileContent("public/i/index.html", "RegularPages: /i/foo/p1/|$") b.AddFiles("content/foo/p2.md", ``).Build() b.AssertFileContent("public/index.html", "RegularPages: /foo/p1/|/foo/p2/|$") b.AssertFileContent("public/fr/index.html", "RegularPages: /fr/foo/p1/|$") b.AddFiles("content/foo/p2.fr.md", ``).Build() b.AssertFileContent("public/fr/index.html", "RegularPages: /fr/foo/p1/|/fr/foo/p2/|$") b.AddFiles("content/foo/p2.i.md", ``).Build() b.AssertFileContent("public/i/index.html", "RegularPages: /i/foo/p1/|/i/foo/p2/|$") } func TestRebuildRenameDirectoryWithBranchBundleFastRender(t *testing.T) { recentlyVisited := types.NewEvictingQueue[string](10).Add("/a/b/c/") b := TestRunning(t, rebuildFilesSimple, func(cfg *IntegrationTestConfig) { cfg.BuildCfg = BuildCfg{RecentlyTouched: recentlyVisited} }) b.RenameDir("content/mysection", "content/mysectionrenamed").Build() b.AssertFileContent("public/mysectionrenamed/index.html", "My Section") b.AssertFileContent("public/mysectionrenamed/mysectionbundle/index.html", "My Section Bundle") b.AssertFileContent("public/mysectionrenamed/mysectionbundle/mysectionbundletext.txt", "My Section Bundle Text 2 Content.") b.AssertRenderCountPage(5) } func TestRebuilErrorRecovery(t *testing.T) { b := TestRunning(t, rebuildFilesSimple) _, err := b.EditFileReplaceAll("content/mysection/mysectionbundle/index.md", "My Section Bundle Content.", "My Section Bundle Content\n\n\n\n{{< foo }}.").BuildE() b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`"/content/mysection/mysectionbundle/index.md:8:9": unrecognized character`)) // Fix the error b.EditFileReplaceAll("content/mysection/mysectionbundle/index.md", "{{< foo }}", "{{< foo >}}").Build() } func TestRebuildAddPageListPagesInHome(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableLiveReload = true -- content/asection/s1.md -- -- content/p1.md -- --- title: "P1" weight: 1 --- -- layouts/single.html -- Single: {{ .Title }}|{{ .Content }}| -- layouts/home.html -- Pages: {{ range .RegularPages }}{{ .RelPermalink }}|{{ end }}$ ` b := TestRunning(t, files) b.AssertFileContent("public/index.html", "Pages: /p1/|$") b.AddFiles("content/p2.md", ``).Build() b.AssertFileContent("public/index.html", "Pages: /p1/|/p2/|$") } func TestRebuildAddPageWithSpaceListPagesInHome(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableLiveReload = true -- content/asection/s1.md -- -- content/p1.md -- --- title: "P1" weight: 1 --- -- layouts/single.html -- Single: {{ .Title }}|{{ .Content }}| -- layouts/home.html -- Pages: {{ range .RegularPages }}{{ .RelPermalink }}|{{ end }}$ ` b := TestRunning(t, files) b.AssertFileContent("public/index.html", "Pages: /p1/|$") b.AddFiles("content/test test/index.md", ``).Build() b.AssertFileContent("public/index.html", "Pages: /p1/|/test-test/|$") } func TestRebuildScopedToOutputFormat(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["term", "taxonomy", "sitemap", "robotstxt", "404"] disableLiveReload = true -- content/p1.md -- --- title: "P1" outputs: ["html", "json"] --- P1 Content. {{< myshort >}} -- layouts/single.html -- Single HTML: {{ .Title }}|{{ .Content }}| -- layouts/single.json -- Single JSON: {{ .Title }}|{{ .Content }}| -- layouts/_shortcodes/myshort.html -- My short. ` b := Test(t, files, TestOptRunning()) b.AssertRenderCountPage(3) b.AssertRenderCountContent(1) b.AssertFileContent("public/p1/index.html", "Single HTML: P1|<p>P1 Content.</p>\n") b.AssertFileContent("public/p1/index.json", "Single JSON: P1|<p>P1 Content.</p>\n") b.EditFileReplaceAll("layouts/single.html", "Single HTML", "Single HTML Edited").Build() b.AssertFileContent("public/p1/index.html", "Single HTML Edited: P1|<p>P1 Content.</p>\n") b.AssertRenderCountPage(1) // Edit shortcode. Note that this is reused across all output formats. b.EditFileReplaceAll("layouts/_shortcodes/myshort.html", "My short", "My short edited").Build() b.AssertFileContent("public/p1/index.html", "My short edited") b.AssertFileContent("public/p1/index.json", "My short edited") b.AssertRenderCountPage(3) // rss (uses .Content) + 2 single pages. } func TestRebuildBaseof(t *testing.T) { files := ` -- hugo.toml -- title = "Hugo Site" baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] disableLiveReload = true -- layouts/baseof.html -- Baseof: {{ .Title }}| {{ block "main" . }}default{{ end }} -- layouts/home.html -- {{ define "main" }} Home: {{ .Title }}|{{ .Content }}| {{ end }} ` testRebuildBothWatchingAndRunning(t, files, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", "Baseof: Hugo Site|", "Home: Hugo Site||") b.EditFileReplaceFunc("layouts/baseof.html", func(s string) string { return strings.Replace(s, "Baseof", "Baseof Edited", 1) }).Build() b.AssertFileContent("public/index.html", "Baseof Edited: Hugo Site|", "Home: Hugo Site||") }) } func TestRebuildSingle(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- title = "Hugo Site" baseURL = "https://example.com" disableKinds = ["term", "taxonomy", "sitemap", "robotstxt", "404"] disableLiveReload = true -- content/p1.md -- --- title: "P1" --- P1 Content. -- layouts/home.html -- Home. -- layouts/single.html -- Single: {{ .Title }}|{{ .Content }}| {{ with (templates.Defer (dict "key" "global")) }} Defer. {{ end }} ` b := Test(t, files, TestOptRunning()) b.AssertFileContent("public/p1/index.html", "Single: P1|", "Defer.") b.AssertRenderCountPage(3) b.AssertRenderCountContent(1) b.EditFileReplaceFunc("layouts/single.html", func(s string) string { s = strings.Replace(s, "Single", "Single Edited", 1) s = strings.Replace(s, "Defer.", "Defer Edited.", 1) return s }).Build() b.AssertFileContent("public/p1/index.html", "Single Edited: P1|", "Defer Edited.") b.AssertRenderCountPage(1) b.AssertRenderCountContent(0) } func TestRebuildSingleWithBaseofEditSingle(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- title = "Hugo Site" baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] disableLiveReload = true -- content/p1.md -- --- title: "P1" --- P1 Content. [foo](/foo) -- layouts/baseof.html -- Baseof: {{ .Title }}| {{ block "main" . }}default{{ end }} {{ with (templates.Defer (dict "foo" "bar")) }} Defer. {{ end }} -- layouts/home.html -- Home. -- layouts/single.html -- {{ define "main" }} Single: {{ .Title }}|{{ .Content }}| {{ end }} ` b := Test(t, files, TestOptRunning()) b.AssertFileContent("public/p1/index.html", "Single: P1|") b.EditFileReplaceFunc("layouts/single.html", func(s string) string { return strings.Replace(s, "Single", "Single Edited", 1) }).Build() b.AssertFileContent("public/p1/index.html", "Single Edited") } func TestRebuildSingleWithBaseofEditBaseof(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- title = "Hugo Site" baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] disableLiveReload = true -- content/p1.md -- --- title: "P1" --- P1 Content. [foo](/foo) -- layouts/baseof.html -- Baseof: {{ .Title }}| {{ block "main" . }}default{{ end }} {{ with (templates.Defer (dict "foo" "bar")) }} Defer. {{ end }} -- layouts/home.html -- Home. -- layouts/single.html -- {{ define "main" }} Single: {{ .Title }}|{{ .Content }}| {{ end }} ` b := Test(t, files, TestOptRunning()) b.AssertFileContent("public/p1/index.html", "Single: P1|") fmt.Println("===============") b.EditFileReplaceAll("layouts/baseof.html", "Baseof", "Baseof Edited").Build() b.AssertFileContent("public/p1/index.html", "Baseof Edited") } func TestRebuildWithDeferEditRenderHook(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- title = "Hugo Site" baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] disableLiveReload = true -- content/p1.md -- --- title: "P1" --- P1 Content. [foo](/foo) -- layouts/baseof.html -- Baseof: {{ .Title }}| {{ block "main" . }}default{{ end }} {{ with (templates.Defer (dict "foo" "bar")) }} Defer. {{ end }} -- layouts/single.html -- {{ define "main" }} Single: {{ .Title }}|{{ .Content }}| {{ end }} -- layouts/_markup/render-link.html -- Render Link. ` b := Test(t, files, TestOptRunning()) // Edit render hook. b.EditFileReplaceAll("layouts/_markup/render-link.html", "Render Link", "Render Link Edited").Build() b.AssertFileContent("public/p1/index.html", "Render Link Edited") } func TestRebuildFromString(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["term", "taxonomy", "sitemap", "robotstxt", "404"] disableLiveReload = true -- content/p1.md -- --- title: "P1" layout: "l1" --- P1 Content. -- content/p2.md -- --- title: "P2" layout: "l2" --- P2 Content. -- assets/mytext.txt -- My Text -- layouts/l1.html -- {{ $r := partial "get-resource.html" . }} L1: {{ .Title }}|{{ .Content }}|R: {{ $r.Content }}| -- layouts/l2.html -- L2. -- layouts/_partials/get-resource.html -- {{ $mytext := resources.Get "mytext.txt" }} {{ $txt := printf "Text: %s" $mytext.Content }} {{ $r := resources.FromString "r.txt" $txt }} {{ return $r }} ` b := TestRunning(t, files) b.AssertFileContent("public/p1/index.html", "L1: P1|<p>P1 Content.</p>\n|R: Text: My Text|") b.EditFileReplaceAll("assets/mytext.txt", "My Text", "My Text Edited").Build() b.AssertFileContent("public/p1/index.html", "L1: P1|<p>P1 Content.</p>\n|R: Text: My Text Edited|") b.AssertRenderCountPage(1) } func TestRebuildDeeplyNestedLink(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/" disableKinds = ["term", "taxonomy", "sitemap", "robotstxt", "404"] disableLiveReload = true -- content/s/p1.md -- --- title: "P1" --- -- content/s/p2.md -- --- title: "P2" --- -- content/s/p3.md -- --- title: "P3" --- -- content/s/p4.md -- --- title: "P4" --- -- content/s/p5.md -- --- title: "P5" --- -- content/s/p6.md -- --- title: "P6" --- -- content/s/p7.md -- --- title: "P7" --- -- layouts/list.html -- List. -- layouts/single.html -- Single. -- layouts/single.html -- Next: {{ with .PrevInSection }}{{ .Title }}{{ end }}| Prev: {{ with .NextInSection }}{{ .Title }}{{ end }}| ` b := TestRunning(t, files) b.AssertFileContent("public/s/p1/index.html", "Next: P2|") b.EditFileReplaceAll("content/s/p7.md", "P7", "P7 Edited").Build() b.AssertFileContent("public/s/p6/index.html", "Next: P7 Edited|") } const rebuildBasicFiles = ` -- hugo.toml -- baseURL = "https://example.com/" disableLiveReload = true disableKinds = ["sitemap", "robotstxt", "404", "rss"] -- content/_index.md -- --- title: "Home" cascade: target: kind: "page" date: 2019-05-06 params: myparam: "myvalue" --- -- content/mysection/_index.md -- --- title: "My Section" date: 2024-02-01 --- -- content/mysection/p1.md -- --- title: "P1" date: 2020-01-01 --- -- content/mysection/p2.md -- --- title: "P2" date: 2021-02-01 --- -- content/mysection/p3.md -- --- title: "P3" --- -- layouts/all.html -- all. {{ .Title }}|Param: {{ .Params.myparam }}|Lastmod: {{ .Lastmod.Format "2006-01-02" }}| ` func TestRebuildEditPageTitle(t *testing.T) { t.Parallel() b := TestRunning(t, rebuildBasicFiles) b.AssertFileContent("public/index.html", "all. Home|Param: |Lastmod: 2024-02-01|") b.AssertFileContent("public/mysection/p1/index.html", "P1|Param: myvalue|", "Lastmod: 2020-01-01|") b.EditFileReplaceAll("content/mysection/p1.md", "P1", "P1edit").Build() b.AssertRenderCountPage(2) b.AssertFileContent("public/mysection/p1/index.html", "all. P1edit|Param: myvalue|") } func TestRebuildEditPageDate(t *testing.T) { t.Parallel() b := TestRunning(t, rebuildBasicFiles) b.AssertFileContent("public/index.html", "all. Home|Param: |Lastmod: 2024-02-01|") b.EditFileReplaceAll("content/mysection/p2.md", "2021-02-01", "2025-04-02").Build() b.AssertRenderCountPage(2) b.AssertFileContent("public/index.html", "all. Home|Param: |Lastmod: 2025-04-02|") b.AssertFileContent("public/mysection/p2/index.html", "all. P2|Param: myvalue|Lastmod: 2025-04-02|") } func TestRebuildEditHomeCascadeEditParam(t *testing.T) { t.Parallel() b := TestRunning(t, rebuildBasicFiles) b.AssertRenderCountPage(7) b.EditFileReplaceAll("content/_index.md", "myvalue", "myvalue-edit").Build() b.AssertRenderCountPage(7) b.AssertFileContent("public/mysection/p1/index.html", "all. P1|Param: myvalue-edit|") } func TestRebuildEditHomeCascadeRemoveParam(t *testing.T) { t.Parallel() b := TestRunning(t, rebuildBasicFiles) b.AssertRenderCountPage(7) b.EditFileReplaceAll("content/_index.md", `myparam: "myvalue"`, "").Build() b.AssertRenderCountPage(7) b.AssertFileContent("public/mysection/p1/index.html", "all. P1|Param: |") } func TestRebuildEditHomeCascadeEditDate(t *testing.T) { t.Parallel() b := TestRunning(t, rebuildBasicFiles) b.AssertRenderCountPage(7) b.AssertFileContent("public/mysection/p3/index.html", "all. P3|Param: myvalue|Lastmod: 2019-05-06") b.EditFileReplaceAll("content/_index.md", "2019-05-06", "2025-05-06").Build() b.AssertRenderCountPage(7) b.AssertFileContent("public/index.html", "all. Home|Param: |Lastmod: 2025-05-06|") b.AssertFileContent("public/mysection/index.html", "all. My Section|Param: |Lastmod: 2024-02-01|") b.AssertFileContent("public/mysection/p3/index.html", "all. P3|Param: myvalue|Lastmod: 2025-05-06") } func TestRebuildEditSectionRemoveDate(t *testing.T) { t.Parallel() b := TestRunning(t, rebuildBasicFiles) b.AssertFileContent("public/mysection/index.html", "all. My Section|Param: |Lastmod: 2024-02-01|") b.EditFileReplaceAll("content/mysection/_index.md", "date: 2024-02-01", "").Build() b.AssertRenderCountPage(5) b.AssertFileContent("public/mysection/index.html", "all. My Section|Param: |Lastmod: 2021-02-01|") } func TestRebuildVariations(t *testing.T) { // t.Parallel() not supported, see https://github.com/fortytw2/leaktest/issues/4 // This leaktest seems to be a little bit shaky on Travis. if !htesting.IsRealCI() { defer leaktest.CheckTimeout(t, 10*time.Second)() } files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] disableLiveReload = true defaultContentLanguage = "nn" [pagination] pagerSize = 20 [security] enableInlineShortcodes = true [languages] [languages.en] weight = 1 [languages.nn] weight = 2 -- content/mysect/p1/index.md -- --- title: "P1" --- P1 Content. {{< include "mysect/p2" >}} §§§go { page="mysect/p3" } hello §§§ {{< foo.inline >}}Foo{{< /foo.inline >}} -- content/mysect/p2/index.md -- --- title: "P2" --- P2 Content. -- content/mysect/p3/index.md -- --- title: "P3" --- P3 Content. -- content/mysect/sub/_index.md -- -- content/mysect/sub/p4/index.md -- --- title: "P4" --- P4 Content. -- content/mysect/sub/p5/index.md -- --- title: "P5" lastMod: 2019-03-02 --- P5 Content. -- content/myothersect/_index.md -- --- cascade: - _target: cascadeparam: "cascadevalue" --- -- content/myothersect/sub/_index.md -- -- content/myothersect/sub/p6/index.md -- --- title: "P6" --- P6 Content. -- content/translations/p7.en.md -- --- title: "P7 EN" --- P7 EN Content. -- content/translations/p7.nn.md -- --- title: "P7 NN" --- P7 NN Content. -- layouts/home.html -- Home: {{ .Title }}|{{ .Content }}| RegularPages: {{ range .RegularPages }}{{ .RelPermalink }}|{{ end }}$ Len RegularPagesRecursive: {{ len .RegularPagesRecursive }} Site.Lastmod: {{ .Site.Lastmod.Format "2006-01-02" }}| Paginate: {{ range (.Paginate .Site.RegularPages).Pages }}{{ .RelPermalink }}|{{ .Title }}|{{ end }}$ -- layouts/single.html -- Single: .Site: {{ .Site }} Single: {{ .Title }}|{{ .Content }}| Single Partial Cached: {{ partialCached "pcached" . }}| Page.Lastmod: {{ .Lastmod.Format "2006-01-02" }}| Cascade param: {{ .Params.cascadeparam }}| -- layouts/list.html -- List: {{ .Title }}|{{ .Content }}| RegularPages: {{ range .RegularPages }}{{ .Title }}|{{ end }}$ Len RegularPagesRecursive: {{ len .RegularPagesRecursive }} RegularPagesRecursive: {{ range .RegularPagesRecursive }}{{ .RelPermalink }}|{{ end }}$ List Partial P1: {{ partial "p1" . }}| Page.Lastmod: {{ .Lastmod.Format "2006-01-02" }}| Cascade param: {{ .Params.cascadeparam }}| -- layouts/_partials/p1.html -- Partial P1. -- layouts/_partials/pcached.html -- Partial Pcached. -- layouts/_shortcodes/include.html -- {{ $p := site.GetPage (.Get 0)}} .Page.Site: {{ .Page.Site }} :: site: {{ site }} {{ with $p }} Shortcode Include: {{ .Title }}| {{ end }} Shortcode .Page.Title: {{ .Page.Title }}| Shortcode Partial P1: {{ partial "p1" . }}| -- layouts/_markup/render-codeblock.html -- {{ $p := site.GetPage (.Attributes.page)}} {{ with $p }} Codeblock Include: {{ .Title }}| {{ end }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: false, BuildCfg: BuildCfg{ testCounters: &buildCounters{}, }, LogLevel: logg.LevelWarn, }, ).Build() // When running the server, this is done on shutdown. // Do this here to satisfy the leak detector above. defer func() { b.Assert(b.H.Close(), qt.IsNil) }() contentRenderCount := b.counters.contentRenderCounter.Load() pageRenderCount := b.counters.pageRenderCounter.Load() b.Assert(contentRenderCount > 0, qt.IsTrue) b.Assert(pageRenderCount > 0, qt.IsTrue) // Test cases: // - Edit content file direct // - Edit content file transitive shortcode // - Edit content file transitive render hook // - Rename one language version of a content file // - Delete content file, check site.RegularPages and section.RegularPagesRecursive (length) // - Add content file (see above). // - Edit shortcode // - Edit inline shortcode // - Edit render hook // - Edit partial used in template // - Edit partial used in shortcode // - Edit partial cached. // - Edit lastMod date in content file, check site.Lastmod. editFile := func(filename string, replacementFunc func(s string) string) { b.EditFileReplaceFunc(filename, replacementFunc).Build() b.Assert(b.counters.contentRenderCounter.Load() < contentRenderCount, qt.IsTrue, qt.Commentf("count %d < %d", b.counters.contentRenderCounter.Load(), contentRenderCount)) b.Assert(b.counters.pageRenderCounter.Load() < pageRenderCount, qt.IsTrue, qt.Commentf("count %d < %d", b.counters.pageRenderCounter.Load(), pageRenderCount)) } b.AssertFileContent("public/index.html", "RegularPages: $", "Len RegularPagesRecursive: 7", "Site.Lastmod: 2019-03-02") b.AssertFileContent("public/mysect/p1/index.html", "Single: P1|<p>P1 Content.", "Shortcode Include: P2|", "Codeblock Include: P3|") editFile("content/mysect/p1/index.md", func(s string) string { return strings.ReplaceAll(s, "P1", "P1 Edited") }) b.AssertFileContent("public/mysect/p1/index.html", "Single: P1 Edited|<p>P1 Edited Content.") b.AssertFileContent("public/index.html", "RegularPages: $", "Len RegularPagesRecursive: 7", "Paginate: /mysect/sub/p5/|P5|/mysect/p1/|P1 Edited") b.AssertFileContent("public/mysect/index.html", "RegularPages: P1 Edited|P2|P3|$", "Len RegularPagesRecursive: 5") // p2 is included in p1 via shortcode. editFile("content/mysect/p2/index.md", func(s string) string { return strings.ReplaceAll(s, "P2", "P2 Edited") }) b.AssertFileContent("public/mysect/p1/index.html", "Shortcode Include: P2 Edited|") // p3 is included in p1 via codeblock hook. editFile("content/mysect/p3/index.md", func(s string) string { return strings.ReplaceAll(s, "P3", "P3 Edited") }) b.AssertFileContent("public/mysect/p1/index.html", "Codeblock Include: P3 Edited|") // Remove a content file in a nested section. b.RemoveFiles("content/mysect/sub/p4/index.md").Build() b.AssertFileContent("public/mysect/index.html", "RegularPages: P1 Edited|P2 Edited|P3 Edited", "Len RegularPagesRecursive: 4") b.AssertFileContent("public/mysect/sub/index.html", "RegularPages: P5|$", "RegularPagesRecursive: 1") // Rename one of the translations. b.AssertFileContent("public/translations/index.html", "RegularPagesRecursive: /translations/p7/") b.AssertFileContent("public/en/translations/index.html", "RegularPagesRecursive: /en/translations/p7/") b.RenameFile("content/translations/p7.nn.md", "content/translations/p7rename.nn.md").Build()
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__fragments_test.go
hugolib/page__fragments_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 hugolib import "testing" // #10794 func TestFragmentsAndToCCrossSiteAccess(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "home"] defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 [languages.fr] weight = 2 -- content/p1.en.md -- --- title: "P1" outputs: ["HTML", "JSON"] --- ## Heading 1 EN -- content/p1.fr.md -- --- title: "P1" outputs: ["HTML", "JSON"] --- ## Heading 1 FR -- layouts/single.html -- HTML -- layouts/single.json -- {{ $secondSite := index .Sites 1 }} {{ $p1 := $secondSite.GetPage "p1" }} ToC: {{ $p1.TableOfContents }} Fragments : {{ $p1.Fragments.Identifiers }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ TxtarString: files, T: t, }, ).Build() b.AssertFileContent("public/en/p1/index.html", "HTML") b.AssertFileContent("public/en/p1/index.json", "ToC: <nav id=\"TableOfContents\">\n <ul>\n <li><a href=\"#heading-1-fr\">Heading 1 FR</a></li>\n </ul>\n</nav>\nFragments : [heading-1-fr]") } // Issue #10866 func TestTableOfContentsWithIncludedMarkdownFile(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "home"] -- content/p1.md -- --- title: "P1" --- ## Heading P1 1 {{% include "p2" %}} -- content/p2.md -- --- title: "P2" --- ### Heading P2 1 ### Heading P2 2 -- layouts/_shortcodes/include.html -- {{ with site.GetPage (.Get 0) }}{{ .RawContent }}{{ end }} -- layouts/single.html -- Fragments: {{ .Fragments.Identifiers }}| ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ TxtarString: files, T: t, }, ).Build() b.AssertFileContent("public/p1/index.html", "Fragments: [heading-p1-1 heading-p2-1 heading-p2-2]|") b.AssertFileContent("public/p2/index.html", "Fragments: [heading-p2-1 heading-p2-2]|") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/shortcode_test.go
hugolib/shortcode_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 hugolib import "testing" func BenchmarkCreateShortcodePlaceholders(b *testing.B) { var ordinal int = 42 for b.Loop() { createShortcodePlaceholder("shortcodeName", 32, uint64(ordinal)) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/pages_capture.go
hugolib/pages_capture.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "fmt" "os" "path/filepath" "strings" "sync" "sync/atomic" "time" "github.com/bep/logg" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/rungroup" "github.com/spf13/afero" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/hugofs" ) func newPagesCollector( ctx context.Context, h *HugoSites, sp *source.SourceSpec, logger loggers.Logger, infoLogger logg.LevelLogger, m *pageMap, buildConfig *BuildCfg, ids []pathChange, ) *pagesCollector { return &pagesCollector{ ctx: ctx, h: h, fs: sp.BaseFs.Content.Fs, m: m, sp: sp, logger: logger, infoLogger: infoLogger, buildConfig: buildConfig, ids: ids, seenDirs: make(map[string]bool), } } type pagesCollector struct { ctx context.Context h *HugoSites sp *source.SourceSpec logger loggers.Logger infoLogger logg.LevelLogger m *pageMap fs afero.Fs buildConfig *BuildCfg // List of paths that have changed. Used in partial builds. ids []pathChange seenDirs map[string]bool g rungroup.Group[hugofs.FileMetaInfo] } // Collect collects content by walking the file system and storing // it in the content tree. // It may be restricted by filenames set on the collector (partial build). func (c *pagesCollector) Collect() (collectErr error) { var ( numWorkers = c.h.numWorkers numFilesProcessedTotal atomic.Uint64 numPageSourcesProcessedTotal atomic.Uint64 numResourceSourcesProcessed atomic.Uint64 numFilesProcessedLast uint64 fileBatchTimer = time.Now() fileBatchTimerMu sync.Mutex ) l := c.infoLogger.WithField("substep", "collect") logFilesProcessed := func(force bool) { fileBatchTimerMu.Lock() if force || time.Since(fileBatchTimer) > 3*time.Second { numFilesProcessedBatch := numFilesProcessedTotal.Load() - numFilesProcessedLast numFilesProcessedLast = numFilesProcessedTotal.Load() loggers.TimeTrackf(l, fileBatchTimer, logg.Fields{ logg.Field{Name: "files", Value: numFilesProcessedBatch}, logg.Field{Name: "files_total", Value: numFilesProcessedTotal.Load()}, logg.Field{Name: "pagesources_total", Value: numPageSourcesProcessedTotal.Load()}, logg.Field{Name: "resourcesources_total", Value: numResourceSourcesProcessed.Load()}, }, "", ) fileBatchTimer = time.Now() } fileBatchTimerMu.Unlock() } defer func() { logFilesProcessed(true) }() c.g = rungroup.Run(c.ctx, rungroup.Config[hugofs.FileMetaInfo]{ NumWorkers: numWorkers, Handle: func(ctx context.Context, fi hugofs.FileMetaInfo) error { numPageSources, numResourceSources, err := c.m.AddFi(fi, c.buildConfig) if err != nil { return hugofs.AddFileInfoToError(err, fi, c.h.SourceFs) } numFilesProcessedTotal.Add(1) numPageSourcesProcessedTotal.Add(numPageSources) numResourceSourcesProcessed.Add(numResourceSources) if numFilesProcessedTotal.Load()%1000 == 0 { logFilesProcessed(false) } return nil }, }) if c.ids == nil { // Collect everything. collectErr = c.collectDir(nil, false, nil) } else { for _, s := range c.h.Sites { s.pageMap.cfg.isRebuild = true } var hasStructuralChange bool for _, id := range c.ids { if id.isStructuralChange() { hasStructuralChange = true break } } for _, id := range c.ids { if id.p.IsLeafBundle() { collectErr = c.collectDir( id.p, false, func(fim hugofs.FileMetaInfo) bool { if hasStructuralChange { return true } fimp := fim.Meta().PathInfo if fimp == nil { return true } return fimp.Path() == id.p.Path() }, ) } else if id.p.IsBranchBundle() { collectErr = c.collectDir( id.p, false, func(fim hugofs.FileMetaInfo) bool { if fim.IsDir() { return id.isStructuralChange() } fimp := fim.Meta().PathInfo if fimp == nil { return false } return strings.HasPrefix(fimp.Path(), paths.AddTrailingSlash(id.p.Dir())) }, ) } else { // We always start from a directory. collectErr = c.collectDir(id.p, id.isDir, func(fim hugofs.FileMetaInfo) bool { if id.isStructuralChange() { if id.isDir && fim.Meta().PathInfo.IsLeafBundle() { return strings.HasPrefix(fim.Meta().PathInfo.Path(), paths.AddTrailingSlash(id.p.Path())) } if id.p.IsContentData() { return strings.HasPrefix(fim.Meta().PathInfo.Path(), paths.AddTrailingSlash(id.p.Dir())) } return id.p.Dir() == fim.Meta().PathInfo.Dir() } if fim.Meta().PathInfo.IsLeafBundle() && id.p.Type() == paths.TypeContentSingle { return id.p.Dir() == fim.Meta().PathInfo.Dir() } return id.p.Path() == fim.Meta().PathInfo.Path() }) } if collectErr != nil { break } } } werr := c.g.Wait() if collectErr == nil { collectErr = werr } return } func (c *pagesCollector) collectDir(dirPath *paths.Path, isDir bool, inFilter func(fim hugofs.FileMetaInfo) bool) error { var dpath string if dirPath != nil { if isDir { dpath = filepath.FromSlash(dirPath.Unnormalized().Path()) } else { dpath = filepath.FromSlash(dirPath.Unnormalized().Dir()) } } if c.seenDirs[dpath] { return nil } c.seenDirs[dpath] = true root, err := c.fs.Stat(dpath) if err != nil { if os.IsNotExist(err) { return nil } return err } rootm := root.(hugofs.FileMetaInfo) if err := c.collectDirDir(dpath, rootm, inFilter); err != nil { return err } return nil } func (c *pagesCollector) collectDirDir(path string, root hugofs.FileMetaInfo, inFilter func(fim hugofs.FileMetaInfo) bool) error { ctx := context.Background() filter := func(fim hugofs.FileMetaInfo) bool { if inFilter != nil { return inFilter(fim) } return true } preHook := func(ctx context.Context, dir hugofs.FileMetaInfo, path string, readdir []hugofs.FileMetaInfo) ([]hugofs.FileMetaInfo, error) { filtered := readdir[:0] for _, fi := range readdir { if filter(fi) { filtered = append(filtered, fi) } } readdir = filtered if len(readdir) == 0 { return nil, nil } n := 0 for _, fi := range readdir { if fi.Meta().PathInfo.IsContentData() { // _content.json // These are not part of any bundle, so just add them directly and remove them from the readdir slice. if err := c.g.Enqueue(fi); err != nil { return nil, err } } else { readdir[n] = fi n++ } } readdir = readdir[:n] // Pick the first regular file. var first hugofs.FileMetaInfo for _, fi := range readdir { if fi.IsDir() { continue } first = fi break } if first == nil { // Only dirs, keep walking. return readdir, nil } // Any bundle file will always be first. firstPi := first.Meta().PathInfo if firstPi == nil { panic(fmt.Sprintf("collectDirDir: no path info for %q", first.Meta().Filename)) } if firstPi.IsLeafBundle() { if err := c.handleBundleLeaf(ctx, dir, path, readdir); err != nil { return nil, err } return nil, filepath.SkipDir } // seen := map[types.Strings2]hugofs.FileMetaInfo{} for _, fi := range readdir { if fi.IsDir() { continue } pi := fi.Meta().PathInfo meta := fi.Meta() if pi == nil { panic(fmt.Sprintf("no path info for %q", meta.Filename)) } if err := c.g.Enqueue(fi); err != nil { return nil, err } } // Keep walking. return readdir, nil } var postHook hugofs.WalkHook wfn := func(ctx context.Context, path string, fi hugofs.FileMetaInfo) error { return nil } w := hugofs.NewWalkway( hugofs.WalkwayConfig{ Logger: c.logger, Root: path, Info: root, Fs: c.fs, IgnoreFile: c.h.SourceSpec.IgnoreFile, Ctx: ctx, PathParser: c.h.Conf.PathParser(), HookPre: preHook, HookPost: postHook, WalkFn: wfn, }) return w.Walk() } func (c *pagesCollector) handleBundleLeaf(ctx context.Context, dir hugofs.FileMetaInfo, inPath string, readdir []hugofs.FileMetaInfo) error { walk := func(ctx context.Context, path string, info hugofs.FileMetaInfo) error { if info.IsDir() { return nil } return c.g.Enqueue(info) } // Start a new walker from the given path. w := hugofs.NewWalkway( hugofs.WalkwayConfig{ Root: inPath, Fs: c.fs, Logger: c.logger, Info: dir, DirEntries: readdir, Ctx: ctx, IgnoreFile: c.h.SourceSpec.IgnoreFile, PathParser: c.h.Conf.PathParser(), WalkFn: walk, }) return w.Walk() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/minify_publisher_test.go
hugolib/minify_publisher_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 hugolib import ( "testing" ) func TestMinifyPublisher(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org/" [minify] minifyOutput = true -- layouts/home.html -- <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>HTML5 boilerplate – all you really need…</title> <link rel="stylesheet" href="css/style.css"> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body id="home"> <h1>{{ .Title }}</h1> <p>{{ .Permalink }}</p> </body> </html> ` b := Test(t, files) // Check minification // HTML b.AssertFileContent("public/index.html", "<!doctype html>") // RSS b.AssertFileContent("public/index.xml", "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\"><channel><title/><link>https://example.org/</link>") // Sitemap b.AssertFileContent("public/sitemap.xml", "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"><url><loc>h") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/404_test.go
hugolib/404_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 hugolib import ( "fmt" "testing" ) func Test404(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "taxonomy", "term"] baseURL = "http://example.com/" -- layouts/all.html -- All. {{ .Kind }}. {{ .Title }}|Lastmod: {{ .Lastmod.Format "2006-01-02" }}| -- layouts/404.html -- {{ $home := site.Home }} 404: Parent: {{ .Parent.Kind }}|{{ .Parent.Path }}| IsAncestor: {{ .IsAncestor $home }}/{{ $home.IsAncestor . }} IsDescendant: {{ .IsDescendant $home }}/{{ $home.IsDescendant . }} CurrentSection: {{ .CurrentSection.Kind }}| FirstSection: {{ .FirstSection.Kind }}| InSection: {{ .InSection $home.Section }}|{{ $home.InSection . }} Sections: {{ len .Sections }}| Page: {{ .Page.RelPermalink }}| Data: {{ len .Data }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "All. home. |") // Note: We currently have only 1 404 page. One might think that we should have // multiple, to follow the Custom Output scheme, but I don't see how that would work // right now. b.AssertFileContent("public/404.html", ` 404: Parent: home IsAncestor: false/true IsDescendant: true/false CurrentSection: home| FirstSection: home| InSection: false|true Sections: 0| Page: /404.html| Data: 1| `) } func Test404EditTemplate(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" disableLiveReload = true [internal] fastRenderMode = true -- layouts/baseof.html -- Base: {{ block "main" . }}{{ end }} -- layouts/404.html -- {{ define "main" }} Not found. {{ end }} ` b := TestRunning(t, files) b.AssertFileContent("public/404.html", `Not found.`) b.EditFiles("layouts/404.html", `Not found. Updated.`).Build() fmt.Println("Rebuilding") b.BuildPartial("/does-not-exist") b.AssertFileContent("public/404.html", `Not found. Updated.`) } func Test404Panic14283(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/all.html -- All. {{ .Kind }}. {{ .Title }}| -- content/404/_index.md -- --- title: "404 branch" --- This is the 404 branch. ` b := Test(t, files) // panic. b.AssertFileContent("public/404/index.html", "All. section. 404 branch|") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/pagebundler_test.go
hugolib/pagebundler_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 hugolib import ( "testing" qt "github.com/frankban/quicktest" ) func TestPageBundlerBasic(t *testing.T) { files := ` -- hugo.toml -- -- content/mybundle/index.md -- --- title: "My Bundle" --- -- content/mybundle/p1.md -- --- title: "P1" --- -- content/mybundle/p1.html -- --- title: "P1 HTML" --- -- content/mybundle/data.txt -- Data txt. -- content/mybundle/sub/data.txt -- Data sub txt. -- content/mybundle/sub/index.md -- -- content/mysection/_index.md -- --- title: "My Section" --- -- content/mysection/data.txt -- Data section txt. -- layouts/all.html -- All. {{ .Title }}|{{ .RelPermalink }}|{{ .Kind }}|{{ .BundleType }}| ` b := Test(t, files) b.AssertFileContent("public/mybundle/index.html", "My Bundle|/mybundle/|page|leaf|") } func TestPageBundlerBundleInRoot(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] -- content/root/index.md -- --- title: "Root" --- -- layouts/single.html -- Basic: {{ .Title }}|{{ .Kind }}|{{ .BundleType }}|{{ .RelPermalink }}| Tree: Section: {{ .Section }}|CurrentSection: {{ .CurrentSection.RelPermalink }}|Parent: {{ .Parent.RelPermalink }}|FirstSection: {{ .FirstSection.RelPermalink }} ` b := Test(t, files) b.AssertFileContent("public/root/index.html", "Basic: Root|page|leaf|/root/|", "Tree: Section: |CurrentSection: /|Parent: /|FirstSection: /", ) } func TestPageBundlerShortcodeInBundledPage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] -- content/section/mybundle/index.md -- --- title: "Mybundle" --- -- content/section/mybundle/p1.md -- --- title: "P1" --- P1 content. {{< myShort >}} -- layouts/single.html -- Bundled page: {{ .RelPermalink}}|{{ with .Resources.Get "p1.md" }}Title: {{ .Title }}|Content: {{ .Content }}{{ end }}| -- layouts/_shortcodes/myShort.html -- MyShort. ` b := Test(t, files) b.AssertFileContent("public/section/mybundle/index.html", "Bundled page: /section/mybundle/|Title: P1|Content: <p>P1 content.</p>\nMyShort.", ) } func TestPageBundlerResourceMultipleOutputFormatsWithDifferentPaths(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] [outputformats] [outputformats.cpath] mediaType = "text/html" path = "cpath" -- content/section/mybundle/index.md -- --- title: "My Bundle" outputs: ["html", "cpath"] --- -- content/section/mybundle/hello.txt -- Hello. -- content/section/mybundle/p1.md -- --- title: "P1" --- P1. {{< hello >}} -- layouts/_shortcodes/hello.html -- Hello HTML. -- layouts/single.html -- Basic: {{ .Title }}|{{ .Kind }}|{{ .BundleType }}|{{ .RelPermalink }}| Resources: {{ range .Resources }}RelPermalink: {{ .RelPermalink }}|Content: {{ .Content }}|{{ end }}| -- layouts/_shortcodes/hello.cpath -- Hello CPATH. -- layouts/single.cpath -- Basic: {{ .Title }}|{{ .Kind }}|{{ .BundleType }}|{{ .RelPermalink }}| Resources: {{ range .Resources }}RelPermalink: {{ .RelPermalink }}|Content: {{ .Content }}|{{ end }}| ` b := Test(t, files) b.AssertFileContent("public/section/mybundle/index.html", "Basic: My Bundle|page|leaf|/section/mybundle/|", "Resources: RelPermalink: |Content: <p>P1.</p>\nHello HTML.\n|RelPermalink: /section/mybundle/hello.txt|Content: Hello.||", ) b.AssertFileContent("public/cpath/section/mybundle/index.html", "Basic: My Bundle|page|leaf|/section/mybundle/|\nResources: RelPermalink: |Content: <p>P1.</p>\nHello CPATH.\n|RelPermalink: /section/mybundle/hello.txt|Content: Hello.||") } func TestPageBundlerMultilingualTextResource(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 [languages.en.permalinks] "/" = "/enpages/:slug/" [languages.nn] weight = 2 -- content/mybundle/index.md -- --- title: "My Bundle" --- -- content/mybundle/index.nn.md -- --- title: "My Bundle NN" --- -- content/mybundle/f1.txt -- F1 -- content/mybundle/f2.txt -- F2 -- content/mybundle/f2.nn.txt -- F2 nn. -- layouts/single.html -- {{ .Title }}|{{ .RelPermalink }}|{{ .Lang }}| Resources: {{ range .Resources }}RelPermalink: {{ .RelPermalink }}|Content: {{ .Content }}|{{ end }}| ` b := Test(t, files) b.AssertFileContent("public/en/enpages/my-bundle/index.html", "My Bundle|/en/enpages/my-bundle/|en|\nResources: RelPermalink: /en/enpages/my-bundle/f1.txt|Content: F1|RelPermalink: /en/enpages/my-bundle/f2.txt|Content: F2||") b.AssertFileContent("public/nn/mybundle/index.html", "My Bundle NN|/nn/mybundle/|nn|\nResources: RelPermalink: /en/enpages/my-bundle/f1.txt|Content: F1|RelPermalink: /nn/mybundle/f2.nn.txt|Content: F2 nn.||") } func TestMultilingualDisableLanguage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 [languages.nn] weight = 2 disabled = true -- content/mysect/_index.md -- --- title: "My Sect En" --- -- content/mysect/p1/index.md -- --- title: "P1" --- P1 -- content/mysect/_index.nn.md -- --- title: "My Sect Nn" --- -- content/mysect/p1/index.nn.md -- --- title: "P1nn" --- P1nn -- layouts/home.html -- Len RegularPages: {{ len .Site.RegularPages }}|RegularPages: {{ range site.RegularPages }}{{ .RelPermalink }}: {{ .Title }}|{{ end }}| Len Pages: {{ len .Site.Pages }}| Len Sites: {{ len .Site.Sites }}| -- layouts/single.html -- {{ .Title }}|{{ .Content }}|{{ .Lang }}| ` b := Test(t, files) b.AssertFileContent("public/en/index.html", "Len RegularPages: 1|") b.AssertFileContent("public/en/mysect/p1/index.html", "P1|<p>P1</p>\n|en|") b.AssertFileExists("public/public/nn/mysect/p1/index.html", false) b.Assert(len(b.H.Sites), qt.Equals, 1) } func TestMultilingualDisableLanguageMounts(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [[module.mounts]] source = 'content/nn' target = 'content' [module.mounts.sites.matrix] languages = "nn" [[module.mounts]] source = 'content/en' target = 'content' [module.mounts.sites.matrix] languages = "en" [languages] [languages.en] weight = 1 [languages.nn] weight = 2 disabled = true -- content/en/mysect/_index.md -- --- title: "My Sect En" --- -- content/en/mysect/p1/index.md -- --- title: "P1" --- P1 -- content/nn/mysect/_index.md -- --- title: "My Sect Nn" --- -- content/nn/mysect/p1/index.md -- --- title: "P1nn" --- P1nn -- layouts/home.html -- Len RegularPages: {{ len .Site.RegularPages }}|RegularPages: {{ range site.RegularPages }}{{ .RelPermalink }}: {{ .Title }}|{{ end }}| Len Pages: {{ len .Site.Pages }}| Len Sites: {{ len .Site.Sites }}| -- layouts/single.html -- {{ .Title }}|{{ .Content }}|{{ .Lang }}| ` b := Test(t, files) b.AssertFileContent("public/en/index.html", "Len RegularPages: 1|") b.AssertFileContent("public/en/mysect/p1/index.html", "P1|<p>P1</p>\n|en|") b.AssertFileExists("public/public/nn/mysect/p1/index.html", false) b.Assert(len(b.H.Sites), qt.Equals, 1) } func TestPageBundlerHeadlessIssue6552(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/headless/h1/index.md -- --- title: My Headless Bundle1 headless: true --- -- content/headless/h1/p1.md -- --- title: P1 --- -- content/headless/h2/index.md -- --- title: My Headless Bundle2 headless: true --- -- layouts/home.html -- {{ $headless1 := .Site.GetPage "headless/h1" }} {{ $headless2 := .Site.GetPage "headless/h2" }} HEADLESS1: {{ $headless1.Title }}|{{ $headless1.RelPermalink }}|{{ len $headless1.Resources }}| HEADLESS2: {{ $headless2.Title }}{{ $headless2.RelPermalink }}|{{ len $headless2.Resources }}| ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` HEADLESS1: My Headless Bundle1||1| HEADLESS2: My Headless Bundle2|0| `) } func TestMultiSiteBundles(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" defaultContentLanguage = "en" [languages] [languages.en] weight = 10 contentDir = "content/en" [languages.nn] weight = 20 contentDir = "content/nn" -- content/en/mybundle/index.md -- --- headless: true --- -- content/nn/mybundle/index.md -- --- headless: true --- -- content/en/mybundle/data.yaml -- data en -- content/en/mybundle/forms.yaml -- forms en -- content/nn/mybundle/data.yaml -- data nn -- content/en/_index.md -- --- Title: Home --- Home content. -- content/en/section-not-bundle/_index.md -- --- Title: Section Page --- Section content. -- content/en/section-not-bundle/single.md -- --- Title: Section Single Date: 2018-02-01 --- Single content. -- layouts/single.html -- {{ .Title }}|{{ .Content }} -- layouts/list.html -- {{ .Title }}|{{ .Content }} ` b := Test(t, files) b.AssertFileContent("public/nn/mybundle/data.yaml", "data nn") b.AssertFileContent("public/mybundle/data.yaml", "data en") b.AssertFileContent("public/mybundle/forms.yaml", "forms en") b.AssertFileExists("public/nn/nn/mybundle/data.yaml", false) b.AssertFileExists("public/en/mybundle/data.yaml", false) homeEn := b.H.Sites[0].home b.Assert(homeEn, qt.Not(qt.IsNil)) b.Assert(homeEn.Date().Year(), qt.Equals, 2018) b.AssertFileContent("public/section-not-bundle/index.html", "Section Page|<p>Section content.</p>") b.AssertFileContent("public/section-not-bundle/single/index.html", "Section Single|<p>Single content.</p>") } func TestBundledResourcesMultilingualDuplicateResourceFiles(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/" [markup] [markup.goldmark] duplicateResourceFiles = true [languages] [languages.en] weight = 1 [languages.en.permalinks] "/" = "/enpages/:slug/" [languages.nn] weight = 2 [languages.nn.permalinks] "/" = "/nnpages/:slug/" -- content/mybundle/index.md -- --- title: "My Bundle" --- {{< getresource "f1.txt" >}} {{< getresource "f2.txt" >}} -- content/mybundle/index.nn.md -- --- title: "My Bundle NN" --- {{< getresource "f1.txt" >}} f2.nn.txt is the original name. {{< getresource "f2.nn.txt" >}} {{< getresource "f2.txt" >}} {{< getresource "sub/f3.txt" >}} -- content/mybundle/f1.txt -- F1 en. -- content/mybundle/sub/f3.txt -- F1 en. -- content/mybundle/f2.txt -- F2 en. -- content/mybundle/f2.nn.txt -- F2 nn. -- layouts/_shortcodes/getresource.html -- {{ $r := .Page.Resources.Get (.Get 0)}} Resource: {{ (.Get 0) }}|{{ with $r }}{{ .RelPermalink }}|{{ .Content }}|{{ else }}Not found.{{ end}} -- layouts/single.html -- {{ .Title }}|{{ .RelPermalink }}|{{ .Lang }}|{{ .Content }}| ` b := Test(t, files) // helpers.PrintFs(b.H.Fs.PublishDir, "", os.Stdout) b.AssertFileContent("public/nn/nnpages/my-bundle-nn/index.html", ` My Bundle NN Resource: f1.txt|/nn/nnpages/my-bundle-nn/f1.txt| Resource: f2.txt|/nn/nnpages/my-bundle-nn/f2.nn.txt|F2 nn.| Resource: f2.nn.txt|/nn/nnpages/my-bundle-nn/f2.nn.txt|F2 nn.| Resource: sub/f3.txt|/nn/nnpages/my-bundle-nn/sub/f3.txt|F1 en.| `) b.AssertFileContent("public/enpages/my-bundle/f2.txt", "F2 en.") b.AssertFileContent("public/nn/nnpages/my-bundle-nn/f2.nn.txt", "F2 nn") b.AssertFileContent("public/enpages/my-bundle/index.html", ` Resource: f1.txt|/enpages/my-bundle/f1.txt|F1 en.| Resource: f2.txt|/enpages/my-bundle/f2.txt|F2 en.| `) b.AssertFileContent("public/enpages/my-bundle/f1.txt", "F1 en.") // Should be duplicated to the nn bundle. b.AssertFileContent("public/nn/nnpages/my-bundle-nn/f1.txt", "F1 en.") } // https://github.com/gohugoio/hugo/issues/5858 func TestBundledResourcesWhenMultipleOutputFormats(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" disableKinds = ["taxonomy", "term"] disableLiveReload = true [outputs] # This looks odd, but it triggers the behavior in #5858 # The total output formats list gets sorted, so CSS before HTML. home = [ "CSS" ] -- content/mybundle/index.md -- --- title: Page --- -- content/mybundle/data.json -- MyData -- layouts/single.html -- {{ range .Resources }} {{ .ResourceType }}|{{ .Title }}| {{ end }} ` b := TestRunning(t, files) b.AssertFileContent("public/mybundle/data.json", "MyData") b.EditFileReplaceAll("content/mybundle/data.json", "MyData", "My changed data").Build() b.AssertFileContent("public/mybundle/data.json", "My changed data") } // See #11663 func TestPageBundlerPartialTranslations(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.nn] weight = 2 [languages.en] weight = 1 -- content/section/mybundle/index.md -- --- title: "Mybundle" --- -- content/section/mybundle/bundledpage.md -- --- title: "Bundled page en" --- -- content/section/mybundle/bundledpage.nn.md -- --- title: "Bundled page nn" --- -- layouts/single.html -- Bundled page: {{ .RelPermalink}}|Len resources: {{ len .Resources }}| ` b := Test(t, files) b.AssertFileContent("public/en/section/mybundle/index.html", "Bundled page: /en/section/mybundle/|Len resources: 1|", ) b.AssertFileExists("public/nn/section/mybundle/index.html", false) } // #6208 func TestBundleIndexInSubFolder(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" -- layouts/single.html -- {{ range .Resources }} {{ .ResourceType }}|{{ .Title }}| {{ end }} -- content/bundle/index.md -- --- title: "bundle index" --- -- content/bundle/p1.md -- --- title: "bundle p1" --- -- content/bundle/sub/p2.md -- --- title: "bundle sub p2" --- -- content/bundle/sub/index.md -- --- title: "bundle sub index" --- -- content/bundle/sub/data.json -- data ` b := Test(t, files) b.AssertFileContent("public/bundle/index.html", ` application|sub/data.json| page|bundle p1| page|bundle sub index| page|bundle sub p2| `) } func TestPageBundlerHome(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: Home --- ![Alt text](image.jpg) -- content/data.json -- DATA -- layouts/home.html -- Title: {{ .Title }}|First Resource: {{ index .Resources 0 }}|Content: {{ .Content }} -- layouts/_markup/render-image.html -- Hook Len Page Resources {{ len .Page.Resources }} ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Title: Home|First Resource: data.json|Content: <p>Hook Len Page Resources 1</p> `) } func TestHTMLFilesIsue11999(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap", "robotsTXT", "404"] [permalinks] posts = "/myposts/:slugorfilename" -- content/posts/markdown-without-frontmatter.md -- -- content/posts/html-without-frontmatter.html -- <html>hello</html> -- content/posts/html-with-frontmatter.html -- --- title: "HTML with frontmatter" --- <html>hello</html> -- content/posts/html-with-commented-out-frontmatter.html -- <!-- --- title: "HTML with commented out frontmatter" --- --> <html>hello</html> -- content/posts/markdown-with-frontmatter.md -- --- title: "Markdown" --- -- content/posts/mybundle/index.md -- --- title: My Bundle --- -- content/posts/mybundle/data.txt -- Data.txt -- content/posts/mybundle/html-in-bundle-without-frontmatter.html -- <html>hell</html> -- content/posts/mybundle/html-in-bundle-with-frontmatter.html -- --- title: Hello --- <html>hello</html> -- content/posts/mybundle/html-in-bundle-with-commented-out-frontmatter.html -- <!-- --- title: "HTML with commented out frontmatter" --- --> <html>hello</html> -- layouts/home.html -- {{ range site.RegularPages }}{{ .RelPermalink }}|{{ end }}$ -- layouts/single.html -- {{ .Title }}|{{ .RelPermalink }}Resources: {{ range .Resources }}{{ .Name }}|{{ end }}$ ` b := Test(t, files) b.AssertFileContent("public/index.html", "/myposts/html-with-commented-out-frontmatter/|/myposts/html-without-frontmatter/|/myposts/markdown-without-frontmatter/|/myposts/html-with-frontmatter/|/myposts/markdown-with-frontmatter/|/myposts/mybundle/|$") b.AssertFileContent("public/myposts/mybundle/index.html", "My Bundle|/myposts/mybundle/Resources: html-in-bundle-with-commented-out-frontmatter.html|html-in-bundle-without-frontmatter.html|html-in-bundle-with-frontmatter.html|data.txt|$") b.AssertPublishDir(` index.html myposts/html-with-commented-out-frontmatter myposts/html-with-commented-out-frontmatter/index.html myposts/html-with-frontmatter myposts/html-with-frontmatter/index.html myposts/html-without-frontmatter myposts/html-without-frontmatter/index.html myposts/markdown-with-frontmatter myposts/markdown-with-frontmatter/index.html myposts/markdown-without-frontmatter myposts/markdown-without-frontmatter/index.html myposts/mybundle/data.txt myposts/mybundle/index.html ! myposts/mybundle/html-in-bundle-with-frontmatter.html `) } func TestBundleDuplicatePagesAndResources(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] -- content/mysection/mybundle/index.md -- -- content/mysection/mybundle/index.html -- -- content/mysection/mybundle/p1.md -- -- content/mysection/mybundle/p1.html -- -- content/mysection/mybundle/foo/p1.html -- -- content/mysection/mybundle/data.txt -- Data txt. -- content/mysection/mybundle/data.en.txt -- Data en txt. -- content/mysection/mybundle/data.json -- Data JSON. -- content/mysection/_index.md -- -- content/mysection/_index.html -- -- content/mysection/sectiondata.json -- Secion data JSON. -- content/mysection/sectiondata.txt -- Section data TXT. -- content/mysection/p2.md -- -- content/mysection/p2.html -- -- content/mysection/foo/p2.md -- -- layouts/single.html -- Single:{{ .Title }}|{{ .Path }}|File LogicalName: {{ with .File }}{{ .LogicalName }}{{ end }}||{{ .RelPermalink }}|{{ .Kind }}|Resources: {{ range .Resources}}{{ .Name }}: {{ .Content }}|{{ end }}$ -- layouts/list.html -- List: {{ .Title }}|{{ .Path }}|File LogicalName: {{ with .File }}{{ .LogicalName }}{{ end }}|{{ .RelPermalink }}|{{ .Kind }}|Resources: {{ range .Resources}}{{ .Name }}: {{ .Content }}|{{ end }}$ RegularPages: {{ range .RegularPages }}{{ .RelPermalink }}|File LogicalName: {{ with .File }}{{ .LogicalName }}|{{ end }}{{ end }}$ ` b := Test(t, files) // Note that the sort order gives us the most specific data file for the en language (the data.en.json). b.AssertFileContent("public/mysection/mybundle/index.html", `Single:|/mysection/mybundle|File LogicalName: index.md||/mysection/mybundle/|page|Resources: data.en.txt: Data en txt.|data.json: Data JSON.|foo/p1.html: |p1.html: |p1.md: |$`) b.AssertFileContent("public/mysection/index.html", "List: |/mysection|File LogicalName: _index.md|/mysection/|section|Resources: sectiondata.json: Secion data JSON.|sectiondata.txt: Section data TXT.|$", "RegularPages: /mysection/foo/p2/|File LogicalName: p2.md|/mysection/mybundle/|File LogicalName: index.md|/mysection/p2/|File LogicalName: p2.md|$") } func TestBundleResourcesGetMatchOriginalName(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" -- content/mybundle/index.md -- -- content/mybundle/f1.en.txt -- F1. -- layouts/single.html -- GetMatch: {{ with .Resources.GetMatch "f1.en.*" }}{{ .Name }}: {{ .Content }}|{{ end }} Match: {{ range .Resources.Match "f1.En.*" }}{{ .Name }}: {{ .Content }}|{{ end }} ` b := Test(t, files) b.AssertFileContent("public/mybundle/index.html", "GetMatch: f1.en.txt: F1.|", "Match: f1.en.txt: F1.|") } func TestBundleResourcesWhenLanguageVariantIsDraft(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" [languages] [languages.en] weight = 1 [languages.nn] weight = 2 -- content/mybundle/index.en.md -- -- content/mybundle/index.nn.md -- --- draft: true --- -- content/mybundle/f1.en.txt -- F1. -- layouts/single.html -- GetMatch: {{ with .Resources.GetMatch "f1.*" }}{{ .Name }}: {{ .Content }}|{{ end }}$ ` b := Test(t, files) b.AssertFileContent("public/mybundle/index.html", "GetMatch: f1.en.txt: F1.|") } func TestBundleBranchIssue12320(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','sitemap','taxonomy','term'] defaultContentLanguage = 'en' defaultContentLanguageInSubdir = true [languages.en] baseURL = "https://en.example.org/" contentDir = "content/en" [languages.fr] baseURL = "https://fr.example.org/" contentDir = "content/fr" -- content/en/s1/p1.md -- --- title: p1 --- -- content/en/s1/p1.txt -- --- p1.txt --- -- layouts/single.html -- {{ .Title }}| -- layouts/list.html -- {{ .Title }}| ` b := Test(t, files) b.AssertFileExists("public/en/s1/index.html", true) b.AssertFileExists("public/en/s1/p1/index.html", true) b.AssertFileExists("public/en/s1/p1.txt", true) b.AssertFileExists("public/fr/s1/index.html", false) b.AssertFileExists("public/fr/s1/p1/index.html", false) b.AssertFileExists("public/fr/s1/p1.txt", false) // failing test }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/config_legacy1_test.go
hugolib/config_legacy1_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 hugolib import ( "strings" "testing" ) func TestLegacyConfigDotToml(t *testing.T) { const filesTemplate = ` -- config.toml -- title = "My Site" -- layouts/home.html -- Site: {{ .Site.Title }} ` t.Run("In root", func(t *testing.T) { t.Parallel() files := filesTemplate b := Test(t, files) b.AssertFileContent("public/index.html", "Site: My Site") }) t.Run("In config dir", func(t *testing.T) { t.Parallel() files := strings.Replace(filesTemplate, "-- config.toml --", "-- config/_default/config.toml --", 1) b := Test(t, files) b.AssertFileContent("public/index.html", "Site: My Site") }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/fileInfo_test.go
hugolib/fileInfo_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" qt "github.com/frankban/quicktest" "github.com/spf13/cast" ) func TestFileInfo(t *testing.T) { t.Run("String", func(t *testing.T) { t.Parallel() c := qt.New(t) fi := &fileInfo{} _, err := cast.ToStringE(fi) c.Assert(err, qt.IsNil) }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false