mirror of
https://github.com/gohugoio/hugo.git
synced 2024-12-01 14:49:08 -05:00
7285e74090
There are some breaking changes in this commit, see #11455. Closes #11455 Closes #11549 This fixes a set of bugs (see issue list) and it is also paying some technical debt accumulated over the years. We now build with Staticcheck enabled in the CI build. The performance should be about the same as before for regular sized Hugo sites, but it should perform and scale much better to larger data sets, as objects that uses lots of memory (e.g. rendered Markdown, big JSON files read into maps with transform.Unmarshal etc.) will now get automatically garbage collected if needed. Performance on partial rebuilds when running the server in fast render mode should be the same, but the change detection should be much more accurate. A list of the notable new features: * A new dependency tracker that covers (almost) all of Hugo's API and is used to do fine grained partial rebuilds when running the server. * A new and simpler tree document store which allows fast lookups and prefix-walking in all dimensions (e.g. language) concurrently. * You can now configure an upper memory limit allowing for much larger data sets and/or running on lower specced PCs. We have lifted the "no resources in sub folders" restriction for branch bundles (e.g. sections). Memory Limit * Hugos will, by default, set aside a quarter of the total system memory, but you can set this via the OS environment variable HUGO_MEMORYLIMIT (in gigabytes). This is backed by a partitioned LRU cache used throughout Hugo. A cache that gets dynamically resized in low memory situations, allowing Go's Garbage Collector to free the memory. New Dependency Tracker: Hugo has had a rule based coarse grained approach to server rebuilds that has worked mostly pretty well, but there have been some surprises (e.g. stale content). This is now revamped with a new dependency tracker that can quickly calculate the delta given a changed resource (e.g. a content file, template, JS file etc.). This handles transitive relations, e.g. $page -> js.Build -> JS import, or $page1.Content -> render hook -> site.GetPage -> $page2.Title, or $page1.Content -> shortcode -> partial -> site.RegularPages -> $page2.Content -> shortcode ..., and should also handle changes to aggregated values (e.g. site.Lastmod) effectively. This covers all of Hugo's API with 2 known exceptions (a list that may not be fully exhaustive): Changes to files loaded with template func os.ReadFile may not be handled correctly. We recommend loading resources with resources.Get Changes to Hugo objects (e.g. Page) passed in the template context to lang.Translate may not be detected correctly. We recommend having simple i18n templates without too much data context passed in other than simple types such as strings and numbers. Note that the cachebuster configuration (when A changes then rebuild B) works well with the above, but we recommend that you revise that configuration, as it in most situations should not be needed. One example where it is still needed is with TailwindCSS and using changes to hugo_stats.json to trigger new CSS rebuilds. Document Store: Previously, a little simplified, we split the document store (where we store pages and resources) in a tree per language. This worked pretty well, but the structure made some operations harder than they needed to be. We have now restructured it into one Radix tree for all languages. Internally the language is considered to be a dimension of that tree, and the tree can be viewed in all dimensions concurrently. This makes some operations re. language simpler (e.g. finding translations is just a slice range), but the idea is that it should also be relatively inexpensive to add more dimensions if needed (e.g. role). Fixes #10169 Fixes #10364 Fixes #10482 Fixes #10630 Fixes #10656 Fixes #10694 Fixes #10918 Fixes #11262 Fixes #11439 Fixes #11453 Fixes #11457 Fixes #11466 Fixes #11540 Fixes #11551 Fixes #11556 Fixes #11654 Fixes #11661 Fixes #11663 Fixes #11664 Fixes #11669 Fixes #11671 Fixes #11807 Fixes #11808 Fixes #11809 Fixes #11815 Fixes #11840 Fixes #11853 Fixes #11860 Fixes #11883 Fixes #11904 Fixes #7388 Fixes #7425 Fixes #7436 Fixes #7544 Fixes #7882 Fixes #7960 Fixes #8255 Fixes #8307 Fixes #8863 Fixes #8927 Fixes #9192 Fixes #9324
364 lines
11 KiB
Go
364 lines
11 KiB
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 template
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"reflect"
|
|
|
|
"github.com/gohugoio/hugo/common/hreflect"
|
|
|
|
"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
|
|
)
|
|
|
|
/*
|
|
|
|
This files contains the Hugo related addons. All the other files in this
|
|
package is auto generated.
|
|
|
|
*/
|
|
|
|
// Export it so we can populate Hugo's func map with it, which makes it faster.
|
|
var GoFuncs = builtinFuncs()
|
|
|
|
// Preparer prepares the template before execution.
|
|
type Preparer interface {
|
|
Prepare() (*Template, error)
|
|
}
|
|
|
|
// ExecHelper allows some custom eval hooks.
|
|
type ExecHelper interface {
|
|
Init(ctx context.Context, tmpl Preparer)
|
|
GetFunc(ctx context.Context, tmpl Preparer, name string) (reflect.Value, reflect.Value, bool)
|
|
GetMethod(ctx context.Context, tmpl Preparer, receiver reflect.Value, name string) (method reflect.Value, firstArg reflect.Value)
|
|
GetMapValue(ctx context.Context, tmpl Preparer, receiver, key reflect.Value) (reflect.Value, bool)
|
|
}
|
|
|
|
// Executer executes a given template.
|
|
type Executer interface {
|
|
ExecuteWithContext(ctx context.Context, p Preparer, wr io.Writer, data any) error
|
|
}
|
|
|
|
type executer struct {
|
|
helper ExecHelper
|
|
}
|
|
|
|
func NewExecuter(helper ExecHelper) Executer {
|
|
return &executer{helper: helper}
|
|
}
|
|
|
|
// Note: The context is currently not fully implemented in Hugo. This is a work in progress.
|
|
func (t *executer) ExecuteWithContext(ctx context.Context, p Preparer, wr io.Writer, data any) error {
|
|
if ctx == nil {
|
|
panic("nil context")
|
|
}
|
|
|
|
tmpl, err := p.Prepare()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
value, ok := data.(reflect.Value)
|
|
if !ok {
|
|
value = reflect.ValueOf(data)
|
|
}
|
|
|
|
state := &state{
|
|
ctx: ctx,
|
|
helper: t.helper,
|
|
prep: p,
|
|
tmpl: tmpl,
|
|
wr: wr,
|
|
vars: []variable{{"$", value}},
|
|
}
|
|
|
|
t.helper.Init(ctx, p)
|
|
|
|
return tmpl.executeWithState(state, value)
|
|
}
|
|
|
|
// Prepare returns a template ready for execution.
|
|
func (t *Template) Prepare() (*Template, error) {
|
|
return t, nil
|
|
}
|
|
|
|
func (t *Template) executeWithState(state *state, value reflect.Value) (err error) {
|
|
defer errRecover(&err)
|
|
if t.Tree == nil || t.Root == nil {
|
|
state.errorf("%q is an incomplete or empty template", t.Name())
|
|
}
|
|
state.walk(value, t.Root)
|
|
return
|
|
}
|
|
|
|
// Below are modified structs etc. The changes are marked with "Added for Hugo."
|
|
|
|
// state represents the state of an execution. It's not part of the
|
|
// template so that multiple executions of the same template
|
|
// can execute in parallel.
|
|
type state struct {
|
|
tmpl *Template
|
|
ctx context.Context // Added for Hugo. The original data context.
|
|
prep Preparer // Added for Hugo.
|
|
helper ExecHelper // Added for Hugo.
|
|
wr io.Writer
|
|
node parse.Node // current node, for errors
|
|
vars []variable // push-down stack of variable values.
|
|
depth int // the height of the stack of executing templates.
|
|
}
|
|
|
|
func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
|
|
s.at(node)
|
|
name := node.Ident
|
|
|
|
var function reflect.Value
|
|
// Added for Hugo.
|
|
var first reflect.Value
|
|
var ok bool
|
|
var isBuiltin bool
|
|
if s.helper != nil {
|
|
isBuiltin = name == "and" || name == "or"
|
|
function, first, ok = s.helper.GetFunc(s.ctx, s.prep, name)
|
|
}
|
|
|
|
if !ok {
|
|
function, isBuiltin, ok = findFunction(name, s.tmpl)
|
|
}
|
|
|
|
if !ok {
|
|
s.errorf("%q is not a defined function", name)
|
|
}
|
|
if first != zero {
|
|
return s.evalCall(dot, function, isBuiltin, cmd, name, args, final, first)
|
|
}
|
|
return s.evalCall(dot, function, isBuiltin, cmd, name, args, final)
|
|
}
|
|
|
|
// evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
|
|
// The 'final' argument represents the return value from the preceding
|
|
// value of the pipeline, if any.
|
|
func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
|
|
if !receiver.IsValid() {
|
|
if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
|
|
s.errorf("nil data; no entry for key %q", fieldName)
|
|
}
|
|
return zero
|
|
}
|
|
typ := receiver.Type()
|
|
receiver, isNil := indirect(receiver)
|
|
if receiver.Kind() == reflect.Interface && isNil {
|
|
// Calling a method on a nil interface can't work. The
|
|
// MethodByName method call below would panic.
|
|
s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
|
|
return zero
|
|
}
|
|
|
|
// Unless it's an interface, need to get to a value of type *T to guarantee
|
|
// we see all methods of T and *T.
|
|
ptr := receiver
|
|
if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Pointer && ptr.CanAddr() {
|
|
ptr = ptr.Addr()
|
|
}
|
|
|
|
// Added for Hugo.
|
|
var first reflect.Value
|
|
var method reflect.Value
|
|
if s.helper != nil {
|
|
method, first = s.helper.GetMethod(s.ctx, s.prep, ptr, fieldName)
|
|
} else {
|
|
method = ptr.MethodByName(fieldName)
|
|
}
|
|
|
|
if method.IsValid() {
|
|
if first != zero {
|
|
return s.evalCall(dot, method, false, node, fieldName, args, final, first)
|
|
}
|
|
|
|
return s.evalCall(dot, method, false, node, fieldName, args, final)
|
|
}
|
|
|
|
if method := ptr.MethodByName(fieldName); method.IsValid() {
|
|
return s.evalCall(dot, method, false, node, fieldName, args, final)
|
|
}
|
|
hasArgs := len(args) > 1 || final != missingVal
|
|
// It's not a method; must be a field of a struct or an element of a map.
|
|
switch receiver.Kind() {
|
|
case reflect.Struct:
|
|
tField, ok := receiver.Type().FieldByName(fieldName)
|
|
if ok {
|
|
field, err := receiver.FieldByIndexErr(tField.Index)
|
|
if !tField.IsExported() {
|
|
s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
|
|
}
|
|
if err != nil {
|
|
s.errorf("%v", err)
|
|
}
|
|
// If it's a function, we must call it.
|
|
if hasArgs {
|
|
s.errorf("%s has arguments but cannot be invoked as function", fieldName)
|
|
}
|
|
return field
|
|
}
|
|
case reflect.Map:
|
|
// If it's a map, attempt to use the field name as a key.
|
|
nameVal := reflect.ValueOf(fieldName)
|
|
if nameVal.Type().AssignableTo(receiver.Type().Key()) {
|
|
if hasArgs {
|
|
s.errorf("%s is not a method but has arguments", fieldName)
|
|
}
|
|
var result reflect.Value
|
|
if s.helper != nil {
|
|
// Added for Hugo.
|
|
result, _ = s.helper.GetMapValue(s.ctx, s.prep, receiver, nameVal)
|
|
} else {
|
|
result = receiver.MapIndex(nameVal)
|
|
}
|
|
if !result.IsValid() {
|
|
switch s.tmpl.option.missingKey {
|
|
case mapInvalid:
|
|
// Just use the invalid value.
|
|
case mapZeroValue:
|
|
result = reflect.Zero(receiver.Type().Elem())
|
|
case mapError:
|
|
s.errorf("map has no entry for key %q", fieldName)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
case reflect.Pointer:
|
|
etyp := receiver.Type().Elem()
|
|
if etyp.Kind() == reflect.Struct {
|
|
if _, ok := etyp.FieldByName(fieldName); !ok {
|
|
// If there's no such field, say "can't evaluate"
|
|
// instead of "nil pointer evaluating".
|
|
break
|
|
}
|
|
}
|
|
if isNil {
|
|
s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
|
|
}
|
|
}
|
|
s.errorf("can't evaluate field %s in type %s", fieldName, typ)
|
|
panic("not reached")
|
|
}
|
|
|
|
// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
|
|
// it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
|
|
// as the function itself.
|
|
func (s *state) evalCall(dot, fun reflect.Value, isBuiltin bool, node parse.Node, name string, args []parse.Node, final reflect.Value, first ...reflect.Value) reflect.Value {
|
|
if args != nil {
|
|
args = args[1:] // Zeroth arg is function name/node; not passed to function.
|
|
}
|
|
|
|
typ := fun.Type()
|
|
numFirst := len(first)
|
|
numIn := len(args) + numFirst // Added for Hugo
|
|
if final != missingVal {
|
|
numIn++
|
|
}
|
|
numFixed := len(args) + len(first) // Adjusted for Hugo
|
|
if typ.IsVariadic() {
|
|
numFixed = typ.NumIn() - 1 // last arg is the variadic one.
|
|
if numIn < numFixed {
|
|
s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
|
|
}
|
|
} else if numIn != typ.NumIn() {
|
|
s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn)
|
|
}
|
|
if !goodFunc(typ) {
|
|
// TODO: This could still be a confusing error; maybe goodFunc should provide info.
|
|
s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
|
|
}
|
|
|
|
unwrap := func(v reflect.Value) reflect.Value {
|
|
if v.Type() == reflectValueType {
|
|
v = v.Interface().(reflect.Value)
|
|
}
|
|
return v
|
|
}
|
|
|
|
// Special case for builtin and/or, which short-circuit.
|
|
if isBuiltin && (name == "and" || name == "or") {
|
|
argType := typ.In(0)
|
|
var v reflect.Value
|
|
for _, arg := range args {
|
|
v = s.evalArg(dot, argType, arg).Interface().(reflect.Value)
|
|
if truth(v) == (name == "or") {
|
|
// This value was already unwrapped
|
|
// by the .Interface().(reflect.Value).
|
|
return v
|
|
}
|
|
}
|
|
if final != missingVal {
|
|
// The last argument to and/or is coming from
|
|
// the pipeline. We didn't short circuit on an earlier
|
|
// argument, so we are going to return this one.
|
|
// We don't have to evaluate final, but we do
|
|
// have to check its type. Then, since we are
|
|
// going to return it, we have to unwrap it.
|
|
v = unwrap(s.validateType(final, argType))
|
|
}
|
|
return v
|
|
}
|
|
|
|
// Build the arg list.
|
|
argv := make([]reflect.Value, numIn)
|
|
// Args must be evaluated. Fixed args first.
|
|
i := len(first) // Adjusted for Hugo.
|
|
for ; i < numFixed && i < len(args)+numFirst; i++ { // Adjusted for Hugo.
|
|
argv[i] = s.evalArg(dot, typ.In(i), args[i-numFirst]) // Adjusted for Hugo.
|
|
}
|
|
// Now the ... args.
|
|
if typ.IsVariadic() {
|
|
argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
|
|
for ; i < len(args)+numFirst; i++ { // Adjusted for Hugo.
|
|
argv[i] = s.evalArg(dot, argType, args[i-numFirst]) // Adjusted for Hugo.
|
|
}
|
|
}
|
|
// Add final value if necessary.
|
|
if final != missingVal {
|
|
t := typ.In(typ.NumIn() - 1)
|
|
if typ.IsVariadic() {
|
|
if numIn-1 < numFixed {
|
|
// The added final argument corresponds to a fixed parameter of the function.
|
|
// Validate against the type of the actual parameter.
|
|
t = typ.In(numIn - 1)
|
|
} else {
|
|
// The added final argument corresponds to the variadic part.
|
|
// Validate against the type of the elements of the variadic slice.
|
|
t = t.Elem()
|
|
}
|
|
}
|
|
argv[i] = s.validateType(final, t)
|
|
}
|
|
|
|
// Added for Hugo
|
|
for i := 0; i < len(first); i++ {
|
|
argv[i] = s.validateType(first[i], typ.In(i))
|
|
}
|
|
|
|
v, err := safeCall(fun, argv)
|
|
// If we have an error that is not nil, stop execution and return that
|
|
// error to the caller.
|
|
if err != nil {
|
|
s.at(node)
|
|
s.errorf("error calling %s: %w", name, err)
|
|
}
|
|
return unwrap(v)
|
|
}
|
|
|
|
func isTrue(val reflect.Value) (truth, ok bool) {
|
|
return hreflect.IsTruthfulValue(val), true
|
|
}
|