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/tpl/data/resources.go | tpl/data/resources.go | // Copyright 2016 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package data
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"path/filepath"
"time"
"github.com/gohugoio/hugo/cache/filecache"
"github.com/gohugoio/hugo/common/hashing"
"github.com/spf13/afero"
)
var (
resSleep = time.Second * 2 // if JSON decoding failed sleep for n seconds before retrying
resRetries = 1 // number of retries to load the JSON from URL
)
// getRemote loads the content of a remote file. This method is thread safe.
func (ns *Namespace) getRemote(cache *filecache.Cache, unmarshal func([]byte) (bool, error), req *http.Request) error {
url := req.URL.String()
if err := ns.deps.ExecHelper.Sec().CheckAllowedHTTPURL(url); err != nil {
return err
}
if err := ns.deps.ExecHelper.Sec().CheckAllowedHTTPMethod("GET"); err != nil {
return err
}
var headers bytes.Buffer
req.Header.Write(&headers)
id := hashing.MD5FromStringHexEncoded(url + headers.String())
var handled bool
var retry bool
_, b, err := cache.GetOrCreateBytes(id, func() ([]byte, error) {
var err error
handled = true
for i := 0; i <= resRetries; i++ {
ns.deps.Log.Infof("Downloading: %s ...", url)
var res *http.Response
res, err = ns.client.Do(req)
if err != nil {
return nil, err
}
var b []byte
b, err = io.ReadAll(res.Body)
if err != nil {
return nil, err
}
res.Body.Close()
if isHTTPError(res) {
return nil, fmt.Errorf("failed to retrieve remote file: %s, body: %q", http.StatusText(res.StatusCode), b)
}
retry, err = unmarshal(b)
if err == nil {
// Return it so it can be cached.
return b, nil
}
if !retry {
return nil, err
}
ns.deps.Log.Infof("Cannot read remote resource %s: %s", url, err)
ns.deps.Log.Infof("Retry #%d for %s and sleeping for %s", i+1, url, resSleep)
time.Sleep(resSleep)
}
return nil, err
})
if !handled {
// This is cached content and should be correct.
_, err = unmarshal(b)
}
return err
}
// getLocal loads the content of a local file
func getLocal(workingDir, url string, fs afero.Fs) ([]byte, error) {
filename := filepath.Join(workingDir, url)
return afero.ReadFile(fs, filename)
}
// getResource loads the content of a local or remote file and returns its content and the
// cache ID used, if relevant.
func (ns *Namespace) getResource(cache *filecache.Cache, unmarshal func(b []byte) (bool, error), req *http.Request) error {
switch req.URL.Scheme {
case "":
url, err := url.QueryUnescape(req.URL.String())
if err != nil {
return err
}
b, err := getLocal(ns.deps.Conf.BaseConfig().WorkingDir, url, ns.deps.Fs.Source)
if err != nil {
return err
}
_, err = unmarshal(b)
return err
default:
return ns.getRemote(cache, unmarshal, req)
}
}
func isHTTPError(res *http.Response) bool {
return res.StatusCode < 200 || res.StatusCode > 299
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/data/data_test.go | tpl/data/data_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 data
import (
"bytes"
"html/template"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"github.com/bep/logg"
"github.com/gohugoio/hugo/common/maps"
qt "github.com/frankban/quicktest"
)
func TestGetCSV(t *testing.T) {
t.Parallel()
c := qt.New(t)
for i, test := range []struct {
sep string
url string
content string
expect any
}{
// Remotes
{
",",
`http://success/`,
"gomeetup,city\nyes,Sydney\nyes,San Francisco\nyes,Stockholm\n",
[][]string{{"gomeetup", "city"}, {"yes", "Sydney"}, {"yes", "San Francisco"}, {"yes", "Stockholm"}},
},
{
",",
`http://error.extra.field/`,
"gomeetup,city\nyes,Sydney\nyes,San Francisco\nyes,Stockholm,EXTRA\n",
false,
},
{
",",
`http://nofound/404`,
``,
false,
},
// Locals
{
";",
"pass/semi",
"gomeetup;city\nyes;Sydney\nyes;San Francisco\nyes;Stockholm\n",
[][]string{{"gomeetup", "city"}, {"yes", "Sydney"}, {"yes", "San Francisco"}, {"yes", "Stockholm"}},
},
{
";",
"fail/no-file",
"",
false,
},
} {
c.Run(test.url, func(c *qt.C) {
msg := qt.Commentf("Test %d", i)
ns := newTestNs()
// Setup HTTP test server
var srv *httptest.Server
srv, ns.client = getTestServer(func(w http.ResponseWriter, r *http.Request) {
if !hasHeaderValue(r.Header, "Accept", "text/csv") && !hasHeaderValue(r.Header, "Accept", "text/plain") {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
if r.URL.Path == "/404" {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
w.Header().Add("Content-type", "text/csv")
w.Write([]byte(test.content))
})
defer func() { srv.Close() }()
// Setup local test file for schema-less URLs
if !strings.Contains(test.url, ":") && !strings.HasPrefix(test.url, "fail/") {
f, err := ns.deps.Fs.Source.Create(filepath.Join(ns.deps.Conf.BaseConfig().WorkingDir, test.url))
c.Assert(err, qt.IsNil, msg)
f.WriteString(test.content)
f.Close()
}
// Get on with it
got, err := ns.GetCSV(test.sep, test.url)
if _, ok := test.expect.(bool); ok {
c.Assert(int(ns.deps.Log.LoggCount(logg.LevelError)), qt.Equals, 1)
c.Assert(got, qt.IsNil)
return
}
c.Assert(err, qt.IsNil, msg)
c.Assert(int(ns.deps.Log.LoggCount(logg.LevelError)), qt.Equals, 0)
c.Assert(got, qt.Not(qt.IsNil), msg)
c.Assert(got, qt.DeepEquals, test.expect, msg)
})
}
}
func TestGetJSON(t *testing.T) {
t.Parallel()
c := qt.New(t)
for i, test := range []struct {
url string
content string
expect any
}{
{
`http://success/`,
`{"gomeetup":["Sydney","San Francisco","Stockholm"]}`,
map[string]any{"gomeetup": []any{"Sydney", "San Francisco", "Stockholm"}},
},
{
`http://malformed/`,
`{gomeetup:["Sydney","San Francisco","Stockholm"]}`,
false,
},
{
`http://nofound/404`,
``,
false,
},
// Locals
{
"pass/semi",
`{"gomeetup":["Sydney","San Francisco","Stockholm"]}`,
map[string]any{"gomeetup": []any{"Sydney", "San Francisco", "Stockholm"}},
},
{
"fail/no-file",
"",
false,
},
{
`pass/üńīçøðê-url.json`,
`{"gomeetup":["Sydney","San Francisco","Stockholm"]}`,
map[string]any{"gomeetup": []any{"Sydney", "San Francisco", "Stockholm"}},
},
} {
c.Run(test.url, func(c *qt.C) {
msg := qt.Commentf("Test %d", i)
ns := newTestNs()
// Setup HTTP test server
var srv *httptest.Server
srv, ns.client = getTestServer(func(w http.ResponseWriter, r *http.Request) {
if !hasHeaderValue(r.Header, "Accept", "application/json") {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
if r.URL.Path == "/404" {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
w.Header().Add("Content-type", "application/json")
w.Write([]byte(test.content))
})
defer func() { srv.Close() }()
// Setup local test file for schema-less URLs
if !strings.Contains(test.url, ":") && !strings.HasPrefix(test.url, "fail/") {
f, err := ns.deps.Fs.Source.Create(filepath.Join(ns.deps.Conf.BaseConfig().WorkingDir, test.url))
c.Assert(err, qt.IsNil, msg)
f.WriteString(test.content)
f.Close()
}
// Get on with it
got, _ := ns.GetJSON(test.url)
if _, ok := test.expect.(bool); ok {
c.Assert(int(ns.deps.Log.LoggCount(logg.LevelError)), qt.Equals, 1)
return
}
c.Assert(int(ns.deps.Log.LoggCount(logg.LevelError)), qt.Equals, 0, msg)
c.Assert(got, qt.Not(qt.IsNil), msg)
c.Assert(got, qt.DeepEquals, test.expect)
})
}
}
func TestHeaders(t *testing.T) {
t.Parallel()
c := qt.New(t)
for _, test := range []struct {
name string
headers any
assert func(c *qt.C, headers string)
}{
{
`Misc header variants`,
map[string]any{
"Accept-Charset": "utf-8",
"Max-forwards": "10",
"X-Int": 32,
"X-Templ": template.HTML("a"),
"X-Multiple": []string{"a", "b"},
"X-MultipleInt": []int{3, 4},
},
func(c *qt.C, headers string) {
c.Assert(headers, qt.Contains, "Accept-Charset: utf-8")
c.Assert(headers, qt.Contains, "Max-Forwards: 10")
c.Assert(headers, qt.Contains, "X-Int: 32")
c.Assert(headers, qt.Contains, "X-Templ: a")
c.Assert(headers, qt.Contains, "X-Multiple: a")
c.Assert(headers, qt.Contains, "X-Multiple: b")
c.Assert(headers, qt.Contains, "X-Multipleint: 3")
c.Assert(headers, qt.Contains, "X-Multipleint: 4")
c.Assert(headers, qt.Contains, "User-Agent: Hugo Static Site Generator")
},
},
{
`Params`,
maps.Params{
"Accept-Charset": "utf-8",
},
func(c *qt.C, headers string) {
c.Assert(headers, qt.Contains, "Accept-Charset: utf-8")
},
},
{
`Override User-Agent`,
map[string]any{
"User-Agent": "007",
},
func(c *qt.C, headers string) {
c.Assert(headers, qt.Contains, "User-Agent: 007")
},
},
} {
c.Run(test.name, func(c *qt.C) {
ns := newTestNs()
// Setup HTTP test server
var srv *httptest.Server
var headers bytes.Buffer
srv, ns.client = getTestServer(func(w http.ResponseWriter, r *http.Request) {
c.Assert(r.URL.String(), qt.Equals, "http://gohugo.io/api?foo")
w.Write([]byte("{}"))
r.Header.Write(&headers)
})
defer func() { srv.Close() }()
testFunc := func(fn func(args ...any) error) {
defer headers.Reset()
err := fn("http://example.org/api", "?foo", test.headers)
c.Assert(err, qt.IsNil)
c.Assert(int(ns.deps.Log.LoggCount(logg.LevelError)), qt.Equals, 0)
test.assert(c, headers.String())
}
testFunc(func(args ...any) error {
_, err := ns.GetJSON(args...)
return err
})
testFunc(func(args ...any) error {
_, err := ns.GetCSV(",", args...)
return err
})
})
}
}
func TestToURLAndHeaders(t *testing.T) {
t.Parallel()
c := qt.New(t)
url, headers := toURLAndHeaders([]any{"https://foo?id=", 32})
c.Assert(url, qt.Equals, "https://foo?id=32")
c.Assert(headers, qt.IsNil)
url, headers = toURLAndHeaders([]any{"https://foo?id=", 32, map[string]any{"a": "b"}})
c.Assert(url, qt.Equals, "https://foo?id=32")
c.Assert(headers, qt.DeepEquals, map[string]any{"a": "b"})
}
func TestParseCSV(t *testing.T) {
t.Parallel()
c := qt.New(t)
for i, test := range []struct {
csv []byte
sep string
exp string
err bool
}{
{[]byte("a,b,c\nd,e,f\n"), "", "", true},
{[]byte("a,b,c\nd,e,f\n"), "~/", "", true},
{[]byte("a,b,c\nd,e,f"), "|", "a,b,cd,e,f", false},
{[]byte("q,w,e\nd,e,f"), ",", "qwedef", false},
{[]byte("a|b|c\nd|e|f|g"), "|", "abcdefg", true},
{[]byte("z|y|c\nd|e|f"), "|", "zycdef", false},
} {
msg := qt.Commentf("Test %d: %v", i, test)
csv, err := parseCSV(test.csv, test.sep)
if test.err {
c.Assert(err, qt.Not(qt.IsNil), msg)
continue
}
c.Assert(err, qt.IsNil, msg)
act := ""
for _, v := range csv {
act = act + strings.Join(v, "")
}
c.Assert(act, qt.Equals, test.exp, msg)
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/data/resources_test.go | tpl/data/resources_test.go | // Copyright 2016 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package data
import (
"bytes"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"sync"
"testing"
"time"
"github.com/gohugoio/hugo/cache/filecache"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/config/testconfig"
"github.com/gohugoio/hugo/helpers"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/hugofs"
"github.com/spf13/afero"
)
func TestScpGetLocal(t *testing.T) {
t.Parallel()
v := config.New()
workingDir := "/my/working/dir"
v.Set("workingDir", workingDir)
v.Set("publishDir", "public")
fs := hugofs.NewFromOld(afero.NewMemMapFs(), v)
ps := helpers.FilePathSeparator
tests := []struct {
path string
content []byte
}{
{"testpath" + ps + "test.txt", []byte(`T€st Content 123 fOO,bar:foo%bAR`)},
{"FOo" + ps + "BaR.html", []byte(`FOo/BaR.html T€st Content 123`)},
{"трям" + ps + "трям", []byte(`T€st трям/трям Content 123`)},
{"은행", []byte(`T€st C은행ontent 123`)},
{"Банковский кассир", []byte(`Банковский кассир T€st Content 123`)},
}
for _, test := range tests {
r := bytes.NewReader(test.content)
err := helpers.WriteToDisk(filepath.Join(workingDir, test.path), r, fs.Source)
if err != nil {
t.Error(err)
}
c, err := getLocal(workingDir, test.path, fs.Source)
if err != nil {
t.Errorf("Error getting resource content: %s", err)
}
if !bytes.Equal(c, test.content) {
t.Errorf("\nExpected: %s\nActual: %s\n", string(test.content), string(c))
}
}
}
func getTestServer(handler func(w http.ResponseWriter, r *http.Request)) (*httptest.Server, *http.Client) {
testServer := httptest.NewServer(http.HandlerFunc(handler))
client := &http.Client{
Transport: &http.Transport{Proxy: func(r *http.Request) (*url.URL, error) {
// Remove when https://github.com/golang/go/issues/13686 is fixed
r.Host = "gohugo.io"
return url.Parse(testServer.URL)
}},
}
return testServer, client
}
func TestScpGetRemote(t *testing.T) {
t.Parallel()
c := qt.New(t)
fs := new(afero.MemMapFs)
cache := filecache.NewCache(fs, 100, "")
tests := []struct {
path string
content []byte
}{
{"http://Foo.Bar/foo_Bar-Foo", []byte(`T€st Content 123`)},
{"http://Doppel.Gänger/foo_Bar-Foo", []byte(`T€st Cont€nt 123`)},
{"http://Doppel.Gänger/Fizz_Bazz-Foo", []byte(`T€st Банковский кассир Cont€nt 123`)},
{"http://Doppel.Gänger/Fizz_Bazz-Bar", []byte(`T€st Банковский кассир Cont€nt 456`)},
}
for _, test := range tests {
msg := qt.Commentf("%v", test)
req, err := http.NewRequest("GET", test.path, nil)
c.Assert(err, qt.IsNil, msg)
srv, cl := getTestServer(func(w http.ResponseWriter, r *http.Request) {
w.Write(test.content)
})
defer func() { srv.Close() }()
ns := newTestNs()
ns.client = cl
var cb []byte
f := func(b []byte) (bool, error) {
cb = b
return false, nil
}
err = ns.getRemote(cache, f, req)
c.Assert(err, qt.IsNil, msg)
c.Assert(string(cb), qt.Equals, string(test.content))
c.Assert(string(cb), qt.Equals, string(test.content))
}
}
func TestScpGetRemoteParallel(t *testing.T) {
t.Parallel()
c := qt.New(t)
content := []byte(`T€st Content 123`)
srv, cl := getTestServer(func(w http.ResponseWriter, r *http.Request) {
w.Write(content)
})
defer func() { srv.Close() }()
url := "http://Foo.Bar/foo_Bar-Foo"
req, err := http.NewRequest("GET", url, nil)
c.Assert(err, qt.IsNil)
for _, ignoreCache := range []bool{false} {
cfg := config.New()
cfg.Set("ignoreCache", ignoreCache)
ns := New(newDeps(cfg))
ns.client = cl
var wg sync.WaitGroup
for i := range 1 {
wg.Add(1)
go func(gor int) {
defer wg.Done()
for range 10 {
var cb []byte
f := func(b []byte) (bool, error) {
cb = b
return false, nil
}
err := ns.getRemote(ns.cacheGetJSON, f, req)
c.Assert(err, qt.IsNil)
if string(content) != string(cb) {
t.Errorf("expected\n%q\ngot\n%q", content, cb)
}
time.Sleep(23 * time.Millisecond)
}
}(i)
}
wg.Wait()
}
}
func newDeps(cfg config.Provider) *deps.Deps {
conf := testconfig.GetTestConfig(nil, cfg)
logger := loggers.NewDefault()
fs := hugofs.NewFrom(afero.NewMemMapFs(), conf.BaseConfig())
d := &deps.Deps{
Fs: fs,
Log: logger,
Conf: conf,
}
if err := d.Init(); err != nil {
panic(err)
}
return d
}
func newTestNs() *Namespace {
return New(newDeps(config.New()))
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/path/init.go | tpl/path/init.go | // Copyright 2018 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package path
import (
"context"
"fmt"
"path/filepath"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/internal"
)
const name = "path"
func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
ctx := New(d)
ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },
}
ns.AddMethodMapping(ctx.Base,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.BaseName,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Clean,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Dir,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Ext,
nil,
[][2]string{},
)
testDir := filepath.Join("my", "path")
testFile := filepath.Join(testDir, "filename.txt")
ns.AddMethodMapping(ctx.Join,
nil,
[][2]string{
{fmt.Sprintf(`{{ slice %q "filename.txt" | path.Join }}`, testDir), `my/path/filename.txt`},
{`{{ path.Join "my" "path" "filename.txt" }}`, `my/path/filename.txt`},
{fmt.Sprintf(`{{ %q | path.Ext }}`, testFile), `.txt`},
{fmt.Sprintf(`{{ %q | path.Base }}`, testFile), `filename.txt`},
{fmt.Sprintf(`{{ %q | path.Dir }}`, testFile), `my/path`},
},
)
ns.AddMethodMapping(ctx.Split,
nil,
[][2]string{
{`{{ "/my/path/filename.txt" | path.Split }}`, `/my/path/|filename.txt`},
{fmt.Sprintf(`{{ %q | path.Split }}`, filepath.FromSlash("/my/path/filename.txt")), `/my/path/|filename.txt`},
},
)
return ns
}
internal.AddTemplateFuncsNamespace(f)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/path/path.go | tpl/path/path.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 path provides template functions for manipulating paths.
package path
import (
_path "path"
"path/filepath"
"strings"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/cast"
)
// New returns a new instance of the path-namespaced template functions.
func New(deps *deps.Deps) *Namespace {
return &Namespace{
deps: deps,
}
}
// Namespace provides template functions for the "os" namespace.
type Namespace struct {
deps *deps.Deps
}
// Ext returns the file name extension used by path.
// The extension is the suffix beginning at the final dot
// in the final slash-separated element of path;
// it is empty if there is no dot.
// The input path is passed into filepath.ToSlash converting any Windows slashes
// to forward slashes.
func (ns *Namespace) Ext(path any) (string, error) {
spath, err := cast.ToStringE(path)
if err != nil {
return "", err
}
spath = filepath.ToSlash(spath)
return _path.Ext(spath), nil
}
// Dir returns all but the last element of path, typically the path's directory.
// After dropping the final element using Split, the path is Cleaned and trailing
// slashes are removed.
// If the path is empty, Dir returns ".".
// If the path consists entirely of slashes followed by non-slash bytes, Dir
// returns a single slash. In any other case, the returned path does not end in a
// slash.
// The input path is passed into filepath.ToSlash converting any Windows slashes
// to forward slashes.
func (ns *Namespace) Dir(path any) (string, error) {
spath, err := cast.ToStringE(path)
if err != nil {
return "", err
}
spath = filepath.ToSlash(spath)
return _path.Dir(spath), nil
}
// Base returns the last element of path.
// Trailing slashes are removed before extracting the last element.
// If the path is empty, Base returns ".".
// If the path consists entirely of slashes, Base returns "/".
// The input path is passed into filepath.ToSlash converting any Windows slashes
// to forward slashes.
func (ns *Namespace) Base(path any) (string, error) {
spath, err := cast.ToStringE(path)
if err != nil {
return "", err
}
spath = filepath.ToSlash(spath)
return _path.Base(spath), nil
}
// BaseName returns the last element of path, removing the extension if present.
// Trailing slashes are removed before extracting the last element.
// If the path is empty, Base returns ".".
// If the path consists entirely of slashes, Base returns "/".
// The input path is passed into filepath.ToSlash converting any Windows slashes
// to forward slashes.
func (ns *Namespace) BaseName(path any) (string, error) {
spath, err := cast.ToStringE(path)
if err != nil {
return "", err
}
spath = filepath.ToSlash(spath)
return strings.TrimSuffix(_path.Base(spath), _path.Ext(spath)), nil
}
// Split splits path immediately following the final slash,
// separating it into a directory and file name component.
// If there is no slash in path, Split returns an empty dir and
// file set to path.
// The input path is passed into filepath.ToSlash converting any Windows slashes
// to forward slashes.
// The returned values have the property that path = dir+file.
func (ns *Namespace) Split(path any) (paths.DirFile, error) {
spath, err := cast.ToStringE(path)
if err != nil {
return paths.DirFile{}, err
}
spath = filepath.ToSlash(spath)
dir, file := _path.Split(spath)
return paths.DirFile{Dir: dir, File: file}, nil
}
// Join joins any number of path elements into a single path, adding a
// separating slash if necessary. All the input
// path elements are passed into filepath.ToSlash converting any Windows slashes
// to forward slashes.
// The result is Cleaned; in particular,
// all empty strings are ignored.
func (ns *Namespace) Join(elements ...any) (string, error) {
var pathElements []string
for _, elem := range elements {
switch v := elem.(type) {
case []string:
for _, e := range v {
pathElements = append(pathElements, filepath.ToSlash(e))
}
case []any:
for _, e := range v {
elemStr, err := cast.ToStringE(e)
if err != nil {
return "", err
}
pathElements = append(pathElements, filepath.ToSlash(elemStr))
}
default:
elemStr, err := cast.ToStringE(elem)
if err != nil {
return "", err
}
pathElements = append(pathElements, filepath.ToSlash(elemStr))
}
}
return _path.Join(pathElements...), nil
}
// Clean replaces the separators used with standard slashes and then
// extraneous slashes are removed.
func (ns *Namespace) Clean(path any) (string, error) {
spath, err := cast.ToStringE(path)
if err != nil {
return "", err
}
spath = filepath.ToSlash(spath)
return _path.Clean(spath), nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/path/path_test.go | tpl/path/path_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 path
import (
"path/filepath"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/config/testconfig"
)
func newNs() *Namespace {
return New(testconfig.GetTestDeps(nil, nil))
}
type tstNoStringer struct{}
func TestBase(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
for _, test := range []struct {
path any
expect any
}{
{filepath.FromSlash(`foo/bar.txt`), `bar.txt`},
{filepath.FromSlash(`foo/bar/txt `), `txt `},
{filepath.FromSlash(`foo/bar.t`), `bar.t`},
{`foo.bar.txt`, `foo.bar.txt`},
{`.x`, `.x`},
{``, `.`},
// errors
{tstNoStringer{}, false},
} {
result, err := ns.Base(test.path)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}
c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
}
}
func TestBaseName(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
for _, test := range []struct {
path any
expect any
}{
{filepath.FromSlash(`foo/bar.txt`), `bar`},
{filepath.FromSlash(`foo/bar/txt `), `txt `},
{filepath.FromSlash(`foo/bar.t`), `bar`},
{`foo.bar.txt`, `foo.bar`},
{`.x`, ``},
{``, `.`},
// errors
{tstNoStringer{}, false},
} {
result, err := ns.BaseName(test.path)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}
c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
}
}
func TestDir(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
for _, test := range []struct {
path any
expect any
}{
{filepath.FromSlash(`foo/bar.txt`), `foo`},
{filepath.FromSlash(`foo/bar/txt `), `foo/bar`},
{filepath.FromSlash(`foo/bar.t`), `foo`},
{`foo.bar.txt`, `.`},
{`.x`, `.`},
{``, `.`},
// errors
{tstNoStringer{}, false},
} {
result, err := ns.Dir(test.path)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}
c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
}
}
func TestExt(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
for _, test := range []struct {
path any
expect any
}{
{filepath.FromSlash(`foo/bar.json`), `.json`},
{`foo.bar.txt `, `.txt `},
{``, ``},
{`.x`, `.x`},
// errors
{tstNoStringer{}, false},
} {
result, err := ns.Ext(test.path)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}
c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
}
}
func TestJoin(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
for _, test := range []struct {
elements any
expect any
}{
{
[]string{"", "baz", filepath.FromSlash(`foo/bar.txt`)},
`baz/foo/bar.txt`,
},
{
[]any{"", "baz", paths.DirFile{Dir: "big", File: "john"}, filepath.FromSlash(`foo/bar.txt`)},
`baz/big|john/foo/bar.txt`,
},
{nil, ""},
// errors
{tstNoStringer{}, false},
{[]any{"", tstNoStringer{}}, false},
} {
result, err := ns.Join(test.elements)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}
c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
}
}
func TestSplit(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
for _, test := range []struct {
path any
expect any
}{
{filepath.FromSlash(`foo/bar.txt`), paths.DirFile{Dir: `foo/`, File: `bar.txt`}},
{filepath.FromSlash(`foo/bar/txt `), paths.DirFile{Dir: `foo/bar/`, File: `txt `}},
{`foo.bar.txt`, paths.DirFile{Dir: ``, File: `foo.bar.txt`}},
{``, paths.DirFile{Dir: ``, File: ``}},
// errors
{tstNoStringer{}, false},
} {
result, err := ns.Split(test.path)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}
c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
}
}
func TestClean(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
for _, test := range []struct {
path any
expect any
}{
{filepath.FromSlash(`foo/bar.txt`), `foo/bar.txt`},
{filepath.FromSlash(`foo/bar/txt`), `foo/bar/txt`},
{filepath.FromSlash(`foo/bar`), `foo/bar`},
{filepath.FromSlash(`foo/bar.t`), `foo/bar.t`},
{``, `.`},
// errors
{tstNoStringer{}, false},
} {
result, err := ns.Clean(test.path)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}
c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/diagrams/init.go | tpl/diagrams/init.go | // Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package diagrams provides template functions for generating diagrams.
package diagrams
import (
"context"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/internal"
)
const name = "diagrams"
func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
ctx := &Namespace{
d: d,
}
ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },
}
ns.AddMethodMapping(ctx.Goat,
nil,
[][2]string{},
)
return ns
}
internal.AddTemplateFuncsNamespace(f)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/diagrams/goat.go | tpl/diagrams/goat.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 diagrams
import (
"bytes"
"html/template"
"io"
"strings"
"github.com/bep/goat"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/cast"
)
type goatDiagram struct {
d goat.SVG
}
func (d goatDiagram) Inner() template.HTML {
return template.HTML(d.d.Body)
}
func (d goatDiagram) Wrapped() template.HTML {
return template.HTML(d.d.String())
}
func (d goatDiagram) Width() int {
return d.d.Width
}
func (d goatDiagram) Height() int {
return d.d.Height
}
// Namespace provides template functions for the diagrams namespace.
type Namespace struct {
d *deps.Deps
}
// Goat creates a new SVG diagram from input v.
func (d *Namespace) Goat(v any) SVGDiagram {
var r io.Reader
switch vv := v.(type) {
case io.Reader:
r = vv
case []byte:
r = bytes.NewReader(vv)
default:
r = strings.NewReader(cast.ToString(v))
}
return goatDiagram{
d: goat.BuildSVG(r),
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/diagrams/diagrams.go | tpl/diagrams/diagrams.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 diagrams
import (
"html/template"
)
type SVGDiagram interface {
// Wrapped returns the diagram as an SVG, including the <svg> container.
Wrapped() template.HTML
// Inner returns the inner markup of the SVG.
// This allows for the <svg> container to be created manually.
Inner() template.HTML
// Width returns the width of the SVG.
Width() int
// Height returns the height of the SVG.
Height() int
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/images/init.go | tpl/images/init.go | // Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package images
import (
"context"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/internal"
)
const name = "images"
func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
ctx := New(d)
ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },
}
ns.AddMethodMapping(ctx.Config,
[]string{"imageConfig"},
[][2]string{},
)
ns.AddMethodMapping(ctx.Filter,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.QR,
nil,
[][2]string{},
)
return ns
}
internal.AddTemplateFuncsNamespace(f)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/images/images.go | tpl/images/images.go | // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package images provides template functions for manipulating images.
package images
import (
"errors"
"fmt"
"image"
"path"
"sync"
"github.com/bep/overlayfs"
"github.com/gohugoio/hugo/common/hashing"
"github.com/gohugoio/hugo/common/hugio"
"github.com/gohugoio/hugo/resources/images"
"github.com/gohugoio/hugo/resources/resource_factories/create"
"github.com/mitchellh/mapstructure"
"rsc.io/qr"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/afero"
"github.com/spf13/cast"
)
// New returns a new instance of the images-namespaced template functions.
func New(d *deps.Deps) *Namespace {
var readFileFs afero.Fs
// The docshelper script does not have or need all the dependencies set up.
if d.PathSpec != nil {
readFileFs = overlayfs.New(overlayfs.Options{
Fss: []afero.Fs{
d.PathSpec.BaseFs.Work,
d.PathSpec.BaseFs.Content.Fs,
},
})
}
return &Namespace{
readFileFs: readFileFs,
Filters: &images.Filters{},
cache: map[string]image.Config{},
deps: d,
createClient: create.New(d.ResourceSpec),
}
}
// Namespace provides template functions for the "images" namespace.
type Namespace struct {
*images.Filters
readFileFs afero.Fs
cacheMu sync.RWMutex
cache map[string]image.Config
deps *deps.Deps
createClient *create.Client
}
// Config returns the image.Config for the specified path relative to the
// working directory.
func (ns *Namespace) Config(path any) (image.Config, error) {
filename, err := cast.ToStringE(path)
if err != nil {
return image.Config{}, err
}
if filename == "" {
return image.Config{}, errors.New("config needs a filename")
}
// Check cache for image config.
ns.cacheMu.RLock()
config, ok := ns.cache[filename]
ns.cacheMu.RUnlock()
if ok {
return config, nil
}
f, err := ns.readFileFs.Open(filename)
if err != nil {
return image.Config{}, err
}
defer f.Close()
config, _, err = ns.deps.ResourceSpec.Imaging.Codec.DecodeConfig(f)
if err != nil {
return config, err
}
ns.cacheMu.Lock()
ns.cache[filename] = config
ns.cacheMu.Unlock()
return config, nil
}
// Filter applies the given filters to the image given as the last element in args.
func (ns *Namespace) Filter(args ...any) (images.ImageResource, error) {
if len(args) < 2 {
return nil, errors.New("must provide an image and one or more filters")
}
img := args[len(args)-1].(images.ImageResource)
filtersv := args[:len(args)-1]
return img.Filter(filtersv...)
}
var qrErrorCorrectionLevels = map[string]qr.Level{
"low": qr.L,
"medium": qr.M,
"quartile": qr.Q,
"high": qr.H,
}
// QR encodes the given text into a QR code using the specified options,
// returning an image resource.
func (ns *Namespace) QR(args ...any) (images.ImageResource, error) {
const (
qrDefaultErrorCorrectionLevel = "medium"
qrDefaultScale = 4
)
opts := struct {
Level string // error correction level; one of low, medium, quartile, or high
Scale int // number of image pixels per QR code module
TargetDir string // target directory relative to publishDir
}{
Level: qrDefaultErrorCorrectionLevel,
Scale: qrDefaultScale,
}
if len(args) == 0 || len(args) > 2 {
return nil, errors.New("requires 1 or 2 arguments")
}
text, err := cast.ToStringE(args[0])
if err != nil {
return nil, err
}
if text == "" {
return nil, errors.New("cannot encode an empty string")
}
if len(args) == 2 {
err := mapstructure.WeakDecode(args[1], &opts)
if err != nil {
return nil, err
}
}
level, ok := qrErrorCorrectionLevels[opts.Level]
if !ok {
return nil, errors.New("error correction level must be one of low, medium, quartile, or high")
}
if opts.Scale < 2 {
return nil, errors.New("scale must be an integer greater than or equal to 2")
}
targetPath := path.Join(opts.TargetDir, fmt.Sprintf("qr_%s.png", hashing.HashStringHex(text, opts)))
r, err := ns.createClient.FromOpts(
create.Options{
TargetPath: targetPath,
TargetPathHasHash: true,
CreateContent: func() (func() (hugio.ReadSeekCloser, error), error) {
code, err := qr.Encode(text, level)
if err != nil {
return nil, err
}
code.Scale = opts.Scale
png := code.PNG()
return func() (hugio.ReadSeekCloser, error) {
return hugio.NewReadSeekerNoOpCloserFromBytes(png), nil
}, nil
},
},
)
if err != nil {
return nil, err
}
ir, ok := r.(images.ImageResource)
if !ok {
panic("bug: resource is not an image resource")
}
return ir, nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/images/images_integration_test.go | tpl/images/images_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 images_test
import (
"strings"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/resources/images/imagetesting"
)
func TestImageConfigFromModule(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = 'http://example.com/'
theme = ["mytheme"]
-- static/images/pixel1.png --
iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==
-- themes/mytheme/static/images/pixel2.png --
iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==
-- layouts/home.html --
{{ $path := "static/images/pixel1.png" }}
fileExists OK: {{ fileExists $path }}|
imageConfig OK: {{ (imageConfig $path).Width }}|
{{ $path2 := "static/images/pixel2.png" }}
fileExists2 OK: {{ fileExists $path2 }}|
imageConfig2 OK: {{ (imageConfig $path2).Width }}|
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", `
fileExists OK: true|
imageConfig OK: 1|
fileExists2 OK: true|
imageConfig2 OK: 1|
`)
}
func TestQR(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- layouts/home.html --
{{- $text := "https://gohugo.io" }}
{{- $optionMaps := slice
(dict)
(dict "level" "medium")
(dict "level" "medium" "scale" 4)
(dict "level" "low" "scale" 2)
(dict "level" "medium" "scale" 3)
(dict "level" "quartile" "scale" 5)
(dict "level" "high" "scale" 6)
(dict "level" "high" "scale" 6 "targetDir" "foo/bar")
}}
{{- range $k, $opts := $optionMaps }}
{{- with images.QR $text $opts }}
<img data-id="{{ $k }}" data-img-hash="{{ .Content | hash.XxHash }}" data-level="{{ $opts.level }}" data-scale="{{ $opts.scale }}" data-targetDir="{{ $opts.targetDir }}" src="{{ .RelPermalink }}">
{{- end }}
{{- end }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html",
`<img data-id="0" data-img-hash="6ccacf8056c41475" data-level="" data-scale="" data-targetDir="" src="/qr_924bf7d80a564b23.png">`,
`<img data-id="1" data-img-hash="6ccacf8056c41475" data-level="medium" data-scale="" data-targetDir="" src="/qr_924bf7d80a564b23.png">`,
`<img data-id="2" data-img-hash="6ccacf8056c41475" data-level="medium" data-scale="4" data-targetDir="" src="/qr_924bf7d80a564b23.png">`,
`<img data-id="3" data-img-hash="c29338c3d105b156" data-level="low" data-scale="2" data-targetDir="" src="/qr_9bf1ce25c5f2c058.png">`,
`<img data-id="4" data-img-hash="8f7a639cea917b0e" data-level="medium" data-scale="3" data-targetDir="" src="/qr_7af14b329dd10af7.png">`,
`<img data-id="5" data-img-hash="2d15d6dcb861b5da" data-level="quartile" data-scale="5" data-targetDir="" src="/qr_9600ecb2010c2185.png">`,
`<img data-id="6" data-img-hash="113c45f2c091bc4d" data-level="high" data-scale="6" data-targetDir="" src="/qr_bdc74ee7f5c11cc6.png">`,
`<img data-id="7" data-img-hash="113c45f2c091bc4d" data-level="high" data-scale="6" data-targetDir="foo/bar" src="/foo/bar/qr_14162f02f2b83fff.png">`,
)
files = strings.ReplaceAll(files, "low", "foo")
b, err := hugolib.TestE(t, files)
b.Assert(err.Error(), qt.Contains, "error correction level must be one of low, medium, quartile, or high")
files = strings.ReplaceAll(files, "foo", "low")
files = strings.ReplaceAll(files, "https://gohugo.io", "")
b, err = hugolib.TestE(t, files)
b.Assert(err.Error(), qt.Contains, "cannot encode an empty string")
}
func TestImagesGoldenFuncs(t *testing.T) {
t.Parallel()
if imagetesting.SkipGoldenTests {
t.Skip("Skip golden test on this architecture")
}
// Will be used as the base folder for generated images.
name := "funcs"
files := `
-- hugo.toml --
-- assets/sunset.jpg --
sourcefilename: ../../resources/testdata/sunset.jpg
-- layouts/home.html --
Home.
{{ template "copy" (dict "name" "qr-default.png" "img" (images.QR "https://gohugo.io")) }}
{{ template "copy" (dict "name" "qr-level-high_scale-6.png" "img" (images.QR "https://gohugo.io" (dict "level" "high" "scale" 6))) }}
{{ define "copy"}}
{{ if lt (len (path.Ext .name)) 4 }}
{{ errorf "No extension in %q" .name }}
{{ end }}
{{ $img := .img }}
{{ $name := printf "images/%s" .name }}
{{ with $img | resources.Copy $name }}
{{ .Publish }}
{{ end }}
{{ end }}
`
opts := imagetesting.DefaultGoldenOpts
opts.T = t
opts.Name = name
opts.Files = files
imagetesting.RunGolden(opts)
}
func TestPNGIssue14288(t *testing.T) {
t.Parallel()
files := `
-- assets/qr.png --
sourcefilename: testdata/images_golden/funcs/qr-level-high_scale-6.png
-- layouts/home.html --
{{ $img := resources.Get "qr.png" }}
images.Config: {{ (images.Config "assets/qr.png").Width }}
Resize to 100x100: {{ ($img.Resize "100x100" ).Width }}
Brightnes method: {{ ($img.Filter (images.Brightness 12) ).RelPermalink }}
Brightnes func: {{ ($img | images.Filter (images.Brightness 12) ).RelPermalink }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", `
images.Config: 222
Resize to 100x100: 100
Brightnes method: /qr_hu_d5f06fd7594d0594.png
Brightnes func: /qr_hu_d5f06fd7594d0594.png
`)
}
func TestPNGNamedWebpIssue14288(t *testing.T) {
t.Parallel()
files := `
-- assets/qr.webp --
sourcefilename: testdata/images_golden/funcs/qr-level-high_scale-6.png
-- layouts/home.html --
{{ $img := resources.Get "qr.webp" }}
images.Config: {{ (images.Config "assets/qr.webp").Width }}
Resize to 100x100: {{ ($img.Resize "100x100" ).Width }}
Brightnes method: {{ ($img.Filter (images.Brightness 12) ).RelPermalink }}
Brightnes func: {{ ($img | images.Filter (images.Brightness 12) ).RelPermalink }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", `
images.Config: 222
Resize to 100x100: 100
Brightnes method: /qr_hu_d5f06fd7594d0594.webp
Brightnes func: /qr_hu_d5f06fd7594d0594.webp
`)
}
// Note that this test doesn't really reproduce the original issue,
// but keep it as a regression test for WebP decoding in general.
// TODO(bep) I fixed the failing site, but I don't really understand why it failed. But now it's Christmas.
func TestPNGIssue14295(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableLiveReload = true
-- assets/qr.png --
sourcefilename: testdata/images_golden/funcs/qr-level-high_scale-6.png
-- layouts/home.html --
{{ $img := resources.Get "qr.png" }}
{{ $img = $img.Resize "200x webp" | images.Filter (images.GaussianBlur 5) }}
Image: {{ $img.RelPermalink }}
`
tempDir := t.TempDir()
for range 2 {
b := hugolib.Test(t, files, hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
cfg.NeedsOsFS = true
cfg.WorkingDir = tempDir
}))
b.AssertFileContent("public/index.html", `Image: /qr_hu_6b5f59be9c4d3b3a.webp`)
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/images/images_test.go | tpl/images/images_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 images
import (
"bytes"
"image"
"image/color"
"path/filepath"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/config/testconfig"
"github.com/gohugoio/hugo/resources/images"
"github.com/spf13/afero"
"github.com/spf13/cast"
)
type tstNoStringer struct{}
type widthHeight struct {
Width int
Height int
}
var configTests = []struct {
path any
input widthHeight
expect any
}{
{
path: "a.png",
input: widthHeight{10, 10},
expect: image.Config{
Width: 10,
Height: 10,
ColorModel: color.NRGBAModel,
},
},
{
path: "a.png",
input: widthHeight{10, 10},
expect: image.Config{
Width: 10,
Height: 10,
ColorModel: color.NRGBAModel,
},
},
{
path: "b.png",
input: widthHeight{20, 15},
expect: image.Config{
Width: 20,
Height: 15,
ColorModel: color.NRGBAModel,
},
},
{
path: "a.png",
input: widthHeight{20, 15},
expect: image.Config{
Width: 10,
Height: 10,
ColorModel: color.NRGBAModel,
},
},
// errors
{path: tstNoStringer{}, expect: false},
{path: "non-existent.png", expect: false},
{path: "", expect: false},
}
func TestNSConfig(t *testing.T) {
t.Parallel()
c := qt.New(t)
afs := afero.NewMemMapFs()
v := config.New()
v.Set("workingDir", "/a/b")
d := testconfig.GetTestDeps(afs, v)
bcfg := d.Conf
ns := New(d)
for _, test := range configTests {
// check for expected errors early to avoid writing files
if b, ok := test.expect.(bool); ok && !b {
_, err := ns.Config(test.path)
c.Assert(err, qt.Not(qt.IsNil))
continue
}
// cast path to string for afero.WriteFile
sp, err := cast.ToStringE(test.path)
c.Assert(err, qt.IsNil)
img := blankImage(d.ResourceSpec.Imaging.Codec, test.input.Width, test.input.Height)
afero.WriteFile(ns.deps.Fs.Source, filepath.Join(bcfg.WorkingDir(), sp), img, 0o755)
result, err := ns.Config(test.path)
c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
c.Assert(len(ns.cache), qt.Not(qt.Equals), 0)
}
}
func blankImage(codec *images.Codec, width, height int) []byte {
var buf bytes.Buffer
img := image.NewRGBA(image.Rect(0, 0, width, height))
cfg := images.ImageConfig{
TargetFormat: images.PNG,
}
if err := codec.EncodeTo(cfg, &buf, img); err != nil {
panic(err)
}
return buf.Bytes()
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/hugo/init.go | tpl/hugo/init.go | // Copyright 2018 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package hugo provides template functions for accessing the Site Hugo object.
package hugo
import (
"context"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/internal"
)
const name = "hugo"
func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
if d.Site == nil {
panic("no site in deps")
}
h := d.Site.Hugo()
ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(cctx context.Context, args ...any) (any, error) { return h, nil },
}
// We just add the Hugo struct as the namespace here. No method mappings.
return ns
}
internal.AddTemplateFuncsNamespace(f)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/crypto/init.go | tpl/crypto/init.go | // Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package crypto
import (
"context"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/internal"
)
const name = "crypto"
func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
ctx := New()
ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },
}
// Deprecated. Use hash.FNV32a instead.
ns.AddMethodMapping(ctx.FNV32a,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.HMAC,
[]string{"hmac"},
[][2]string{
{`{{ hmac "sha256" "Secret key" "Hello world, gophers!" }}`, `b6d11b6c53830b9d87036272ca9fe9d19306b8f9d8aa07b15da27d89e6e34f40`},
},
)
ns.AddMethodMapping(ctx.MD5,
[]string{"md5"},
[][2]string{
{`{{ md5 "Hello world, gophers!" }}`, `b3029f756f98f79e7f1b7f1d1f0dd53b`},
{`{{ crypto.MD5 "Hello world, gophers!" }}`, `b3029f756f98f79e7f1b7f1d1f0dd53b`},
},
)
ns.AddMethodMapping(ctx.SHA1,
[]string{"sha1"},
[][2]string{
{`{{ sha1 "Hello world, gophers!" }}`, `c8b5b0e33d408246e30f53e32b8f7627a7a649d4`},
},
)
ns.AddMethodMapping(ctx.SHA256,
[]string{"sha256"},
[][2]string{
{`{{ sha256 "Hello world, gophers!" }}`, `6ec43b78da9669f50e4e422575c54bf87536954ccd58280219c393f2ce352b46`},
},
)
return ns
}
internal.AddTemplateFuncsNamespace(f)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/crypto/crypto_test.go | tpl/crypto/crypto_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 crypto
import (
"testing"
qt "github.com/frankban/quicktest"
)
func TestMD5(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := New()
for i, test := range []struct {
in any
expect any
}{
{"Hello world, gophers!", "b3029f756f98f79e7f1b7f1d1f0dd53b"},
{"Lorem ipsum dolor", "06ce65ac476fc656bea3fca5d02cfd81"},
{t, false},
} {
errMsg := qt.Commentf("[%d] %v", i, test.in)
result, err := ns.MD5(test.in)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil), errMsg)
continue
}
c.Assert(err, qt.IsNil, errMsg)
c.Assert(result, qt.Equals, test.expect, errMsg)
}
}
func TestSHA1(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := New()
for i, test := range []struct {
in any
expect any
}{
{"Hello world, gophers!", "c8b5b0e33d408246e30f53e32b8f7627a7a649d4"},
{"Lorem ipsum dolor", "45f75b844be4d17b3394c6701768daf39419c99b"},
{t, false},
} {
errMsg := qt.Commentf("[%d] %v", i, test.in)
result, err := ns.SHA1(test.in)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil), errMsg)
continue
}
c.Assert(err, qt.IsNil, errMsg)
c.Assert(result, qt.Equals, test.expect, errMsg)
}
}
func TestSHA256(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := New()
for i, test := range []struct {
in any
expect any
}{
{"Hello world, gophers!", "6ec43b78da9669f50e4e422575c54bf87536954ccd58280219c393f2ce352b46"},
{"Lorem ipsum dolor", "9b3e1beb7053e0f900a674dd1c99aca3355e1275e1b03d3cb1bc977f5154e196"},
{t, false},
} {
errMsg := qt.Commentf("[%d] %v", i, test.in)
result, err := ns.SHA256(test.in)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil), errMsg)
continue
}
c.Assert(err, qt.IsNil, errMsg)
c.Assert(result, qt.Equals, test.expect, errMsg)
}
}
func TestHMAC(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := New()
for i, test := range []struct {
hash any
key any
msg any
encoding any
expect any
}{
{"md5", "Secret key", "Hello world, gophers!", nil, "36eb69b6bf2de96b6856fdee8bf89754"},
{"sha1", "Secret key", "Hello world, gophers!", nil, "84a76647de6cd47ac6ae4258e3753f711172ce68"},
{"sha256", "Secret key", "Hello world, gophers!", nil, "b6d11b6c53830b9d87036272ca9fe9d19306b8f9d8aa07b15da27d89e6e34f40"},
{"sha512", "Secret key", "Hello world, gophers!", nil, "dc3e586cd936865e2abc4c12665e9cc568b2dad714df3c9037cbea159d036cfc4209da9e3fcd30887ff441056941966899f6fb7eec9646ff9ddb592595a8eb7f"},
{"md5", "Secret key", "Hello world, gophers!", "hex", "36eb69b6bf2de96b6856fdee8bf89754"},
{"md5", "Secret key", "Hello world, gophers!", "binary", "6\xebi\xb6\xbf-\xe9khV\xfd\xee\x8b\xf8\x97T"},
{"md5", "Secret key", "Hello world, gophers!", "foo", false},
{"md5", "Secret key", "Hello world, gophers!", "", false},
{"", t, "", nil, false},
} {
errMsg := qt.Commentf("[%d] %v, %v, %v, %v", i, test.hash, test.key, test.msg, test.encoding)
result, err := ns.HMAC(test.hash, test.key, test.msg, test.encoding)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil), errMsg)
continue
}
c.Assert(err, qt.IsNil, errMsg)
c.Assert(result, qt.Equals, test.expect, errMsg)
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/crypto/crypto.go | tpl/crypto/crypto.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 crypto provides template functions for cryptographic operations.
package crypto
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"fmt"
"hash"
"hash/fnv"
"github.com/gohugoio/hugo/common/hugo"
"github.com/spf13/cast"
)
// New returns a new instance of the crypto-namespaced template functions.
func New() *Namespace {
return &Namespace{}
}
// Namespace provides template functions for the "crypto" namespace.
type Namespace struct{}
// MD5 hashes the v and returns its MD5 checksum.
func (ns *Namespace) MD5(v any) (string, error) {
conv, err := cast.ToStringE(v)
if err != nil {
return "", err
}
hash := md5.Sum([]byte(conv))
return hex.EncodeToString(hash[:]), nil
}
// SHA1 hashes v and returns its SHA1 checksum.
func (ns *Namespace) SHA1(v any) (string, error) {
conv, err := cast.ToStringE(v)
if err != nil {
return "", err
}
hash := sha1.Sum([]byte(conv))
return hex.EncodeToString(hash[:]), nil
}
// SHA256 hashes v and returns its SHA256 checksum.
func (ns *Namespace) SHA256(v any) (string, error) {
conv, err := cast.ToStringE(v)
if err != nil {
return "", err
}
hash := sha256.Sum256([]byte(conv))
return hex.EncodeToString(hash[:]), nil
}
// FNV32a hashes v using fnv32a algorithm.
// <docsmeta>{"newIn": "0.98.0" }</docsmeta>
func (ns *Namespace) FNV32a(v any) (int, error) {
hugo.Deprecate("crypto.FNV32a", "Use hash.FNV32a.", "v0.129.0")
conv, err := cast.ToStringE(v)
if err != nil {
return 0, err
}
algorithm := fnv.New32a()
algorithm.Write([]byte(conv))
return int(algorithm.Sum32()), nil
}
// HMAC returns a cryptographic hash that uses a key to sign a message.
func (ns *Namespace) HMAC(h any, k any, m any, e ...any) (string, error) {
ha, err := cast.ToStringE(h)
if err != nil {
return "", err
}
var hash func() hash.Hash
switch ha {
case "md5":
hash = md5.New
case "sha1":
hash = sha1.New
case "sha256":
hash = sha256.New
case "sha512":
hash = sha512.New
default:
return "", fmt.Errorf("hmac: %s is not a supported hash function", ha)
}
msg, err := cast.ToStringE(m)
if err != nil {
return "", err
}
key, err := cast.ToStringE(k)
if err != nil {
return "", err
}
mac := hmac.New(hash, []byte(key))
_, err = mac.Write([]byte(msg))
if err != nil {
return "", err
}
encoding := "hex"
if len(e) > 0 && e[0] != nil {
encoding, err = cast.ToStringE(e[0])
if err != nil {
return "", err
}
}
switch encoding {
case "binary":
return string(mac.Sum(nil)[:]), nil
case "hex":
return hex.EncodeToString(mac.Sum(nil)[:]), nil
default:
return "", fmt.Errorf("%q is not a supported encoding method", encoding)
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/templates.go | tpl/tplimpl/templates.go | package tplimpl
import (
"io"
"iter"
"regexp"
"strconv"
"strings"
"sync/atomic"
"unicode"
"unicode/utf8"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/tpl"
htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"
texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
)
func (t *templateNamespace) readTemplateInto(templ *TemplInfo) error {
if err := func() error {
meta := templ.Fi.Meta()
f, err := meta.Open()
if err != nil {
return err
}
defer f.Close()
b, err := io.ReadAll(f)
if err != nil {
return err
}
templ.content = removeLeadingBOM(string(b))
if !templ.noBaseOf {
templ.noBaseOf = !needsBaseTemplate(templ.content)
}
return nil
}(); err != nil {
return err
}
return nil
}
// The tweet and twitter shortcodes were deprecated in favor of the x shortcode
// in v0.141.0. We can remove these aliases in v0.155.0 or later.
var embeddedTemplatesAliases = map[string][]string{
"_shortcodes/twitter.html": {"_shortcodes/tweet.html"},
}
func (s *TemplateStore) parseTemplate(ti *TemplInfo, replace bool) error {
err := s.tns.doParseTemplate(ti, replace)
if err != nil {
return s.addFileContext(ti, "parse of template failed", err)
}
return err
}
func (t *templateNamespace) newBlankTemplate(ti *TemplInfo) tpl.Template {
if ti.D.IsPlainText {
tt, err := t.parseText.New(ti.Name()).Parse("")
if err != nil {
panic(err)
}
return tt
}
tt, err := t.parseHTML.New(ti.Name()).Parse("")
if err != nil {
panic(err)
}
return tt
}
func (t *templateNamespace) doParseTemplate(ti *TemplInfo, replace bool) error {
if !ti.noBaseOf || ti.category == CategoryBaseof {
// Delay parsing until we have the base template.
return nil
}
pi := ti.PathInfo
name := pi.PathNoLeadingSlash()
var (
templ tpl.Template
err error
)
if ti.D.IsPlainText {
prototype := t.parseText
if !replace && prototype.Lookup(name) != nil {
name += "-" + strconv.FormatUint(t.nameCounter.Add(1), 10)
}
templ, err = prototype.New(name).Parse(ti.content)
if err != nil {
return err
}
} else {
prototype := t.parseHTML
if !replace && prototype.Lookup(name) != nil {
name += "-" + strconv.FormatUint(t.nameCounter.Add(1), 10)
}
templ, err = prototype.New(name).Parse(ti.content)
if err != nil {
return err
}
if ti.subCategory == SubCategoryEmbedded {
// In Hugo 0.146.0 we moved the internal templates around.
// For the "_internal/twitter_cards.html" style templates, they
// were moved to the _partials directory.
// But we need to make them accessible from the old path for a while.
if pi.Type() == paths.TypePartial {
aliasName := strings.TrimPrefix(name, "_partials/")
aliasName = "_internal/" + aliasName
_, err = prototype.AddParseTree(aliasName, templ.(*htmltemplate.Template).Tree)
if err != nil {
return err
}
}
// This was also possible before Hugo 0.146.0, but this should be deprecated.
if pi.Type() == paths.TypeShortcode {
aliasName := strings.TrimPrefix(name, "_shortcodes/")
aliasName = "_internal/shortcodes/" + aliasName
_, err = prototype.AddParseTree(aliasName, templ.(*htmltemplate.Template).Tree)
if err != nil {
return err
}
}
}
// Issue #13599.
if ti.category == CategoryPartial && ti.Fi != nil && ti.Fi.Meta().PathInfo.Section() == "partials" {
aliasName := strings.TrimPrefix(name, "_")
if _, err := prototype.AddParseTree(aliasName, templ.(*htmltemplate.Template).Tree); err != nil {
return err
}
}
}
ti.Template = templ
return nil
}
func (t *templateNamespace) applyBaseTemplate(overlay *TemplInfo, base keyTemplateInfo) error {
tb := &TemplWithBaseApplied{
Overlay: overlay,
Base: base.Info,
}
base.Info.overlays = append(base.Info.overlays, overlay)
var templ tpl.Template
if overlay.D.IsPlainText {
tt := texttemplate.Must(t.parseText.Clone()).New(overlay.PathInfo.PathNoLeadingSlash())
var err error
tt, err = tt.Parse(base.Info.content)
if err != nil {
return err
}
tt, err = tt.Parse(overlay.content)
if err != nil {
return err
}
templ = tt
t.baseofTextClones = append(t.baseofTextClones, tt)
} else {
tt := htmltemplate.Must(t.parseHTML.CloneShallow()).New(overlay.PathInfo.PathNoLeadingSlash())
var err error
tt, err = tt.Parse(base.Info.content)
if err != nil {
return err
}
tt, err = tt.Parse(overlay.content)
if err != nil {
return err
}
templ = tt
t.baseofHtmlClones = append(t.baseofHtmlClones, tt)
}
tb.Template = &TemplInfo{
Template: templ,
base: base.Info,
PathInfo: overlay.PathInfo,
Fi: overlay.Fi,
D: overlay.D,
matrix: overlay.matrix,
noBaseOf: true,
}
variants := overlay.baseVariants.Get(base.Key)
if variants == nil {
variants = make(map[TemplateDescriptor]*TemplWithBaseApplied)
overlay.baseVariants.Insert(base.Key, variants)
}
variants[base.Info.D] = tb
return nil
}
func (t *templateNamespace) templatesIn(in tpl.Template) iter.Seq[tpl.Template] {
return func(yield func(t tpl.Template) bool) {
switch in := in.(type) {
case *htmltemplate.Template:
for t := range in.All() {
if !yield(t) {
return
}
}
case *texttemplate.Template:
for t := range in.All() {
if !yield(t) {
return
}
}
}
}
}
var baseTemplateDefineRe = regexp.MustCompile(`^{{-?\s*define`)
// needsBaseTemplate returns true if the first non-comment template block is a
// define block.
func needsBaseTemplate(templ string) bool {
idx := -1
inComment := false
for i := 0; i < len(templ); {
if !inComment && strings.HasPrefix(templ[i:], "{{/*") {
inComment = true
i += 4
} else if !inComment && strings.HasPrefix(templ[i:], "{{- /*") {
inComment = true
i += 6
} else if inComment && strings.HasPrefix(templ[i:], "*/}}") {
inComment = false
i += 4
} else if inComment && strings.HasPrefix(templ[i:], "*/ -}}") {
inComment = false
i += 6
} else {
r, size := utf8.DecodeRuneInString(templ[i:])
if !inComment {
if strings.HasPrefix(templ[i:], "{{") {
idx = i
break
} else if !unicode.IsSpace(r) {
break
}
}
i += size
}
}
if idx == -1 {
return false
}
return baseTemplateDefineRe.MatchString(templ[idx:])
}
func removeLeadingBOM(s string) string {
const bom = '\ufeff'
for i, r := range s {
if i == 0 && r != bom {
return s
}
if i > 0 {
return s[i:]
}
}
return s
}
type templateNamespace struct {
parseText *texttemplate.Template
parseHTML *htmltemplate.Template
prototypeText *texttemplate.Template
prototypeHTML *htmltemplate.Template
nameCounter atomic.Uint64
standaloneText *texttemplate.Template
baseofTextClones []*texttemplate.Template
baseofHtmlClones []*htmltemplate.Template
}
func (t *templateNamespace) createPrototypesParse() error {
if t.prototypeHTML == nil {
panic("prototypeHTML not set")
}
t.parseHTML = htmltemplate.Must(t.prototypeHTML.Clone())
t.parseText = texttemplate.Must(t.prototypeText.Clone())
return nil
}
func (t *templateNamespace) createPrototypes(init bool) error {
if init {
t.prototypeHTML = htmltemplate.Must(t.parseHTML.Clone())
t.prototypeText = texttemplate.Must(t.parseText.Clone())
}
return nil
}
func newTemplateNamespace(funcs map[string]any) *templateNamespace {
return &templateNamespace{
parseHTML: htmltemplate.New("").Funcs(funcs),
parseText: texttemplate.New("").Funcs(funcs),
standaloneText: texttemplate.New("").Funcs(funcs),
}
}
func isText(t tpl.Template) bool {
switch t.(type) {
case *texttemplate.Template:
return true
case *htmltemplate.Template:
return false
default:
panic("unknown template type")
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/templatedescriptor_test.go | tpl/tplimpl/templatedescriptor_test.go | package tplimpl
import (
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/resources/kinds"
)
func TestTemplateDescriptorCompare(t *testing.T) {
c := qt.New(t)
dh := descriptorHandler{
opts: StoreOptions{
OutputFormats: output.DefaultFormats,
DefaultOutputFormat: "html",
},
}
less := func(category Category, this, other1, other2 TemplateDescriptor) {
c.Helper()
result1 := dh.compareDescriptors(category, this, other1, nil, nil)
result2 := dh.compareDescriptors(category, this, other2, nil, nil)
c.Assert(result1.w1 < result2.w1, qt.IsTrue, qt.Commentf("%d < %d", result1, result2))
}
check := func(category Category, this, other TemplateDescriptor, less bool) {
c.Helper()
result := dh.compareDescriptors(category, this, other, nil, nil)
if less {
c.Assert(result.w1 < 0, qt.IsTrue, qt.Commentf("%d", result))
} else {
c.Assert(result.w1 >= 0, qt.IsTrue, qt.Commentf("%d", result))
}
}
check(
CategoryBaseof,
TemplateDescriptor{Kind: "", LayoutFromTemplate: "", OutputFormat: "404", MediaType: "text/html"},
TemplateDescriptor{Kind: "", LayoutFromTemplate: "", OutputFormat: "html", MediaType: "text/html"},
false,
)
check(
CategoryLayout,
TemplateDescriptor{Kind: "", OutputFormat: "404", MediaType: "text/html"},
TemplateDescriptor{Kind: "", LayoutFromTemplate: "", OutputFormat: "alias", MediaType: "text/html"},
true,
)
less(
CategoryLayout,
TemplateDescriptor{Kind: kinds.KindHome, LayoutFromTemplate: "list", OutputFormat: "html"},
TemplateDescriptor{LayoutFromTemplate: "list", OutputFormat: "html"},
TemplateDescriptor{Kind: kinds.KindHome, OutputFormat: "html"},
)
check(
CategoryLayout,
TemplateDescriptor{Kind: kinds.KindHome, LayoutFromTemplate: "list", OutputFormat: "html", MediaType: "text/html"},
TemplateDescriptor{Kind: kinds.KindHome, LayoutFromTemplate: "list", OutputFormat: "myformat", MediaType: "text/html"},
false,
)
}
// INFO timer: name resolveTemplate count 779 duration 5.482274ms average 7.037µs median 4µs
func BenchmarkCompareDescriptors(b *testing.B) {
dh := descriptorHandler{
opts: StoreOptions{
OutputFormats: output.DefaultFormats,
DefaultOutputFormat: "html",
},
}
pairs := []struct {
d1, d2 TemplateDescriptor
}{
{
TemplateDescriptor{Kind: "", LayoutFromTemplate: "", OutputFormat: "404", MediaType: "text/html", Variant1: "", Variant2: "", LayoutFromUserMustMatch: false, IsPlainText: false},
TemplateDescriptor{Kind: "", LayoutFromTemplate: "", OutputFormat: "rss", MediaType: "application/rss+xml", Variant1: "", Variant2: "", LayoutFromUserMustMatch: false, IsPlainText: false},
},
{
TemplateDescriptor{Kind: "page", LayoutFromTemplate: "single", OutputFormat: "html", MediaType: "text/html", Variant1: "", Variant2: "", LayoutFromUserMustMatch: false, IsPlainText: false},
TemplateDescriptor{Kind: "", LayoutFromTemplate: "list", OutputFormat: "", MediaType: "application/rss+xml", Variant1: "", Variant2: "", LayoutFromUserMustMatch: false, IsPlainText: false},
},
{
TemplateDescriptor{Kind: "page", LayoutFromTemplate: "single", OutputFormat: "html", MediaType: "text/html", Variant1: "", Variant2: "", LayoutFromUserMustMatch: false, IsPlainText: false},
TemplateDescriptor{Kind: "", LayoutFromTemplate: "", OutputFormat: "alias", MediaType: "text/html", Variant1: "", Variant2: "", LayoutFromUserMustMatch: false, IsPlainText: false},
},
{
TemplateDescriptor{Kind: "page", LayoutFromTemplate: "single", OutputFormat: "rss", MediaType: "application/rss+xml", Variant1: "", Variant2: "", LayoutFromUserMustMatch: false, IsPlainText: false},
TemplateDescriptor{Kind: "", LayoutFromTemplate: "single", OutputFormat: "rss", MediaType: "application/rss+xml", Variant1: "", Variant2: "", LayoutFromUserMustMatch: false, IsPlainText: false},
},
}
for b.Loop() {
for _, pair := range pairs {
_ = dh.compareDescriptors(CategoryLayout, pair.d1, pair.d2, nil, nil)
}
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/tplimpl_integration_test.go | tpl/tplimpl/tplimpl_integration_test.go | // Copyright 2025 The Hugo Authors. All rights reserved.
//
// Portions Copyright The Go Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tplimpl_test
import (
"strings"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugolib"
)
// Verify that the new keywords in Go 1.18 is available.
func TestGo18Constructs(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = 'http://example.com/'
disableKinds = ["section", "home", "rss", "taxonomy", "term", "rss"]
-- content/p1.md --
---
title: "P1"
---
-- layouts/_partials/counter.html --
{{ if .Scratch.Get "counter" }}{{ .Scratch.Add "counter" 1 }}{{ else }}{{ .Scratch.Set "counter" 1 }}{{ end }}{{ return true }}
-- layouts/single.html --
continue:{{ range seq 5 }}{{ if eq . 2 }}{{continue}}{{ end }}{{ . }}{{ end }}:END:
break:{{ range seq 5 }}{{ if eq . 2 }}{{break}}{{ end }}{{ . }}{{ end }}:END:
continue2:{{ range seq 5 }}{{ if eq . 2 }}{{ continue }}{{ end }}{{ . }}{{ end }}:END:
break2:{{ range seq 5 }}{{ if eq . 2 }}{{ break }}{{ end }}{{ . }}{{ end }}:END:
counter1: {{ partial "counter.html" . }}/{{ .Scratch.Get "counter" }}
and1: {{ if (and false (partial "counter.html" .)) }}true{{ else }}false{{ end }}
or1: {{ if (or true (partial "counter.html" .)) }}true{{ else }}false{{ end }}
and2: {{ if (and true (partial "counter.html" .)) }}true{{ else }}false{{ end }}
or2: {{ if (or false (partial "counter.html" .)) }}true{{ else }}false{{ end }}
counter2: {{ .Scratch.Get "counter" }}
`
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
NeedsOsFS: true,
},
)
b.Build()
b.AssertFileContent("public/p1/index.html", `
continue:1345:END:
break:1:END:
continue2:1345:END:
break2:1:END:
counter1: true/1
and1: false
or1: true
and2: true
or2: true
counter2: 3
`)
}
func TestGo23ElseWith(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
title = "Hugo"
-- layouts/home.html --
{{ with false }}{{ else with .Site }}{{ .Title }}{{ end }}|
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "Hugo|")
}
// Issue 10495
func TestCommentsBeforeBlockDefinition(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = 'http://example.com/'
-- content/s1/p1.md --
---
title: "S1P1"
---
-- content/s2/p1.md --
---
title: "S2P1"
---
-- content/s3/p1.md --
---
title: "S3P1"
---
-- layouts/baseof.html --
{{ block "main" . }}{{ end }}
-- layouts/s1/single.html --
{{/* foo */}}
{{ define "main" }}{{ .Title }}{{ end }}
-- layouts/s2/single.html --
{{- /* foo */}}
{{ define "main" }}{{ .Title }}{{ end }}
-- layouts/s3/single.html --
{{- /* foo */ -}}
{{ define "main" }}{{ .Title }}{{ end }}
`
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
},
)
b.Build()
b.AssertFileContent("public/s1/p1/index.html", `S1P1`)
b.AssertFileContent("public/s2/p1/index.html", `S2P1`)
b.AssertFileContent("public/s3/p1/index.html", `S3P1`)
}
func TestGoTemplateBugs(t *testing.T) {
t.Run("Issue 11112", func(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/home.html --
{{ $m := dict "key" "value" }}
{{ $k := "" }}
{{ $v := "" }}
{{ range $k, $v = $m }}
{{ $k }} = {{ $v }}
{{ end }}
`
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
},
)
b.Build()
b.AssertFileContent("public/index.html", `key = value`)
})
}
func TestSecurityAllowActionJSTmpl(t *testing.T) {
filesTemplate := `
-- hugo.toml --
SECURITYCONFIG
-- layouts/home.html --
<script>
var a = §§{{.Title }}§§;
</script>
`
files := strings.ReplaceAll(filesTemplate, "SECURITYCONFIG", "")
b, err := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
},
).BuildE()
// This used to fail, but not in >= Hugo 0.121.0.
b.Assert(err, qt.IsNil)
}
func TestGoogleAnalyticsTemplate(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','section','rss','sitemap','taxonomy','term']
[privacy.googleAnalytics]
disable = false
DNT
[services.googleAnalytics]
id = 'G-0123456789'
-- layouts/home.html --
{{ partial "google_analytics.html" . }}
`
// default respectDoNotTrack value
f := strings.ReplaceAll(files, "DNT", "")
b := hugolib.Test(t, f)
b.AssertFileContent("public/index.html",
`<script async src="https://www.googletagmanager.com/gtag/js?id=G-0123456789"></script>`,
`if ( true )`,
)
// respectDoNotTrack = true
f = strings.ReplaceAll(files, "DNT", "respectDoNotTrack = true")
b = hugolib.Test(t, f)
b.AssertFileContent("public/index.html",
`<script async src="https://www.googletagmanager.com/gtag/js?id=G-0123456789"></script>`,
`if ( true )`,
)
// respectDoNotTrack = false
f = strings.ReplaceAll(files, "DNT", "respectDoNotTrack = false")
b = hugolib.Test(t, f)
b.AssertFileContent("public/index.html",
`<script async src="https://www.googletagmanager.com/gtag/js?id=G-0123456789"></script>`,
`if ( false )`,
)
}
func TestDisqusTemplate(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','section','rss','sitemap','taxonomy','term']
[services.disqus]
shortname = 'foo'
[privacy.disqus]
disable = false
-- layouts/home.html --
{{ template "_internal/disqus.html" . }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html",
`s.src = '//' + "foo" + '.disqus.com/embed.js';`,
)
}
func TestSitemap(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','rss','section','taxonomy','term']
[sitemap]
disable = true
-- content/p1.md --
---
title: p1
sitemap:
p1_disable: foo
---
-- content/p2.md --
---
title: p2
---
-- layouts/single.html --
{{ .Title }}
`
// Test A: Exclude all pages via site config.
b := hugolib.Test(t, files)
b.AssertFileContentExact("public/sitemap.xml",
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n \n</urlset>\n",
)
// Test B: Include all pages via site config.
files_b := strings.ReplaceAll(files, "disable = true", "disable = false")
b = hugolib.Test(t, files_b)
b.AssertFileContentExact("public/sitemap.xml",
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n <url>\n <loc>/p1/</loc>\n </url><url>\n <loc>/p2/</loc>\n </url>\n</urlset>\n",
)
// Test C: Exclude all pages via site config, but include p1 via front matter.
files_c := strings.ReplaceAll(files, "p1_disable: foo", "disable: false")
b = hugolib.Test(t, files_c)
b.AssertFileContentExact("public/sitemap.xml",
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n <url>\n <loc>/p1/</loc>\n </url>\n</urlset>\n",
)
// Test D: Include all pages via site config, but exclude p1 via front matter.
files_d := strings.ReplaceAll(files_b, "p1_disable: foo", "disable: true")
b = hugolib.Test(t, files_d)
b.AssertFileContentExact("public/sitemap.xml",
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n <url>\n <loc>/p2/</loc>\n </url>\n</urlset>\n",
)
}
// Issue 12418
func TestOpengraph(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
capitalizeListTitles = false
disableKinds = ['rss','sitemap']
languageCode = 'en-US'
[markup.goldmark.renderer]
unsafe = true
[params]
description = "m <em>n</em> and **o** can't."
[params.social]
facebook_admin = 'foo'
[taxonomies]
series = 'series'
tag = 'tags'
-- layouts/list.html --
{{ template "_internal/opengraph.html" . }}
-- layouts/single.html --
{{ template "_internal/opengraph.html" . }}
-- content/s1/p1.md --
---
title: p1
date: 2024-04-24T08:00:00-07:00
lastmod: 2024-04-24T11:00:00-07:00
images: [a.jpg,b.jpg]
audio: [c.mp3,d.mp3]
videos: [e.mp4,f.mp4]
series: [series-1]
tags: [t1,t2]
---
a <em>b</em> and **c** can't.
-- content/s1/p2.md --
---
title: p2
series: [series-1]
---
d <em>e</em> and **f** can't.
<!--more-->
-- content/s1/p3.md --
---
title: p3
series: [series-1]
summary: g <em>h</em> and **i** can't.
---
-- content/s1/p4.md --
---
title: p4
series: [series-1]
description: j <em>k</em> and **l** can't.
---
-- content/s1/p5.md --
---
title: p5
series: [series-1]
---
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/s1/p1/index.html", `
<meta property="og:url" content="/s1/p1/">
<meta property="og:title" content="p1">
<meta property="og:description" content="a b and c can’t.">
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="article:section" content="s1">
<meta property="article:published_time" content="2024-04-24T08:00:00-07:00">
<meta property="article:modified_time" content="2024-04-24T11:00:00-07:00">
<meta property="article:tag" content="t1">
<meta property="article:tag" content="t2">
<meta property="og:image" content="/a.jpg">
<meta property="og:image" content="/b.jpg">
<meta property="og:audio" content="/c.mp3">
<meta property="og:audio" content="/d.mp3">
<meta property="og:video" content="/e.mp4">
<meta property="og:video" content="/f.mp4">
<meta property="og:see_also" content="/s1/p2/">
<meta property="og:see_also" content="/s1/p3/">
<meta property="og:see_also" content="/s1/p4/">
<meta property="og:see_also" content="/s1/p5/">
<meta property="fb:admins" content="foo">
`,
)
b.AssertFileContent("public/s1/p2/index.html",
`<meta property="og:description" content="d e and f can’t.">`,
)
b.AssertFileContent("public/s1/p3/index.html",
`<meta property="og:description" content="g h and i can’t.">`,
)
// The markdown is intentionally not rendered to HTML.
b.AssertFileContent("public/s1/p4/index.html",
`<meta property="og:description" content="j k and **l** can't.">`,
)
// The markdown is intentionally not rendered to HTML.
b.AssertFileContent("public/s1/p5/index.html",
`<meta property="og:description" content="m n and **o** can't.">`,
)
}
// Issue 12432
func TestSchema(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
capitalizeListTitles = false
disableKinds = ['rss','sitemap']
[markup.goldmark.renderer]
unsafe = true
[params]
description = "m <em>n</em> and **o** can't."
[taxonomies]
tag = 'tags'
-- layouts/list.html --
{{ template "_internal/schema.html" . }}
-- layouts/single.html --
{{ template "_internal/schema.html" . }}
-- content/s1/p1.md --
---
title: p1
date: 2024-04-24T08:00:00-07:00
lastmod: 2024-04-24T11:00:00-07:00
images: [a.jpg,b.jpg]
tags: [t1,t2]
---
a <em>b</em> and **c** can't.
-- content/s1/p2.md --
---
title: p2
---
d <em>e</em> and **f** can't.
<!--more-->
-- content/s1/p3.md --
---
title: p3
summary: g <em>h</em> and **i** can't.
---
-- content/s1/p4.md --
---
title: p4
description: j <em>k</em> and **l** can't.
---
-- content/s1/p5.md --
---
title: p5
---
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/s1/p1/index.html", `
<meta itemprop="name" content="p1">
<meta itemprop="description" content="a b and c can’t.">
<meta itemprop="datePublished" content="2024-04-24T08:00:00-07:00">
<meta itemprop="dateModified" content="2024-04-24T11:00:00-07:00">
<meta itemprop="wordCount" content="5">
<meta itemprop="image" content="/a.jpg">
<meta itemprop="image" content="/b.jpg">
<meta itemprop="keywords" content="t1,t2">
`,
)
b.AssertFileContent("public/s1/p2/index.html",
`<meta itemprop="description" content="d e and f can’t.">`,
)
b.AssertFileContent("public/s1/p3/index.html",
`<meta itemprop="description" content="g h and i can’t.">`,
)
// The markdown is intentionally not rendered to HTML.
b.AssertFileContent("public/s1/p4/index.html",
`<meta itemprop="description" content="j k and **l** can't.">`,
)
// The markdown is intentionally not rendered to HTML.
b.AssertFileContent("public/s1/p5/index.html",
`<meta itemprop="description" content="m n and **o** can't.">`,
)
}
// Issue 12433
func TestTwitterCards(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
capitalizeListTitles = false
disableKinds = ['rss','sitemap','taxonomy','term']
[markup.goldmark.renderer]
unsafe = true
[params]
description = "m <em>n</em> and **o** can't."
[params.social]
twitter = 'foo'
-- layouts/list.html --
{{ template "_internal/twitter_cards.html" . }}
-- layouts/single.html --
{{ template "_internal/twitter_cards.html" . }}
-- content/s1/p1.md --
---
title: p1
images: [a.jpg,b.jpg]
---
a <em>b</em> and **c** can't.
-- content/s1/p2.md --
---
title: p2
---
d <em>e</em> and **f** can't.
<!--more-->
-- content/s1/p3.md --
---
title: p3
summary: g <em>h</em> and **i** can't.
---
-- content/s1/p4.md --
---
title: p4
description: j <em>k</em> and **l** can't.
---
-- content/s1/p5.md --
---
title: p5
---
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/s1/p1/index.html", `
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="/a.jpg">
<meta name="twitter:title" content="p1">
<meta name="twitter:description" content="a b and c can’t.">
<meta name="twitter:site" content="@foo">
`,
)
b.AssertFileContent("public/s1/p2/index.html",
`<meta name="twitter:card" content="summary">`,
`<meta name="twitter:description" content="d e and f can’t.">`,
)
b.AssertFileContent("public/s1/p3/index.html",
`<meta name="twitter:description" content="g h and i can’t.">`,
)
// The markdown is intentionally not rendered to HTML.
b.AssertFileContent("public/s1/p4/index.html",
`<meta name="twitter:description" content="j k and **l** can't.">`,
)
// The markdown is intentionally not rendered to HTML.
b.AssertFileContent("public/s1/p5/index.html",
`<meta name="twitter:description" content="m n and **o** can't.">`,
)
}
// Issue 12963
func TestEditBaseofParseAfterExecute(t *testing.T) {
files := `
-- hugo.toml --
baseURL = "https://example.com"
disableLiveReload = true
disableKinds = ["taxonomy", "term", "rss", "404", "sitemap"]
[internal]
fastRenderMode = true
-- layouts/baseof.html --
Baseof!
{{ block "main" . }}default{{ end }}
{{ with (templates.Defer (dict "key" "global")) }}
Now. {{ now }}
{{ end }}
-- layouts/single.html --
{{ define "main" }}
Single.
{{ end }}
-- layouts/list.html --
{{ define "main" }}
List.
{{ .Content }}
{{ range .Pages }}{{ .Title }}{{ end }}|
{{ end }}
-- content/mybundle1/index.md --
---
title: "My Bundle 1"
---
-- content/mybundle2/index.md --
---
title: "My Bundle 2"
---
-- content/_index.md --
---
title: "Home"
---
Home!
`
b := hugolib.TestRunning(t, files)
b.AssertFileContent("public/index.html", "Home!")
b.EditFileReplaceAll("layouts/baseof.html", "baseof", "Baseof!").Build()
b.BuildPartial("/")
b.AssertFileContent("public/index.html", "Baseof!")
b.BuildPartial("/mybundle1/")
b.AssertFileContent("public/mybundle1/index.html", "Baseof!")
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/template_funcs.go | tpl/tplimpl/template_funcs.go | // Copyright 2025 The Hugo Authors. All rights reserved.
//
// Portions Copyright The Go Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tplimpl
import (
"context"
"reflect"
"strings"
"github.com/gohugoio/hugo/common/hreflect"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/tpl"
texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
)
var (
_ texttemplate.ExecHelper = (*templateExecHelper)(nil)
zero reflect.Value
)
type templateExecHelper struct {
watching bool // whether we're in server/watch mode.
site reflect.Value
siteParams reflect.Value
funcs map[string]reflect.Value
}
func (t *templateExecHelper) GetFunc(ctx context.Context, tmpl texttemplate.Preparer, name string) (fn reflect.Value, firstArg reflect.Value, found bool) {
if fn, found := t.funcs[name]; found {
if fn.Type().NumIn() > 0 {
first := fn.Type().In(0)
if hreflect.IsContextType(first) {
// TODO(bep) check if we can void this conversion every time -- and if that matters.
// The first argument may be context.Context. This is never provided by the end user, but it's used to pass down
// contextual information, e.g. the top level data context (e.g. Page).
return fn, reflect.ValueOf(ctx), true
}
}
return fn, zero, true
}
return zero, zero, false
}
func (t *templateExecHelper) Init(ctx context.Context, tmpl texttemplate.Preparer) {
if t.watching {
_, ok := tmpl.(identity.IdentityProvider)
if ok {
t.trackDependencies(ctx, tmpl, "", reflect.Value{})
}
}
}
func (t *templateExecHelper) GetMapValue(ctx context.Context, tmpl texttemplate.Preparer, receiver, key reflect.Value) (reflect.Value, bool) {
if params, ok := receiver.Interface().(maps.Params); ok {
// Case insensitive.
keystr := strings.ToLower(key.String())
v, found := params[keystr]
if !found {
return zero, false
}
return reflect.ValueOf(v), true
}
v := receiver.MapIndex(key)
return v, v.IsValid()
}
var typeParams = reflect.TypeOf(maps.Params{})
func (t *templateExecHelper) GetMethod(ctx context.Context, tmpl texttemplate.Preparer, receiver reflect.Value, name string) (method reflect.Value, firstArg reflect.Value) {
if strings.EqualFold(name, "mainsections") && receiver.Type() == typeParams && receiver.Pointer() == t.siteParams.Pointer() {
// Moved to site.MainSections in Hugo 0.112.0.
receiver = t.site
name = "MainSections"
}
if t.watching {
ctx = t.trackDependencies(ctx, tmpl, name, receiver)
}
fn := hreflect.GetMethodByName(receiver, name)
if !fn.IsValid() {
return zero, zero
}
if fn.Type().NumIn() > 0 {
first := fn.Type().In(0)
if hreflect.IsContextType(first) {
// The first argument may be context.Context. This is never provided by the end user, but it's used to pass down
// contextual information, e.g. the top level data context (e.g. Page).
return fn, reflect.ValueOf(ctx)
}
}
return fn, zero
}
func (t *templateExecHelper) OnCalled(ctx context.Context, tmpl texttemplate.Preparer, name string, args []reflect.Value, result reflect.Value) {
if !t.watching {
return
}
// This switch is mostly for speed.
switch name {
case "Unmarshal":
default:
return
}
idm := tpl.Context.GetDependencyManagerInCurrentScope(ctx)
if idm == nil {
return
}
for _, arg := range args {
identity.WalkIdentitiesShallow(arg.Interface(), func(level int, id identity.Identity) bool {
idm.AddIdentity(id)
return false
})
}
}
func (t *templateExecHelper) trackDependencies(ctx context.Context, tmpl texttemplate.Preparer, name string, receiver reflect.Value) context.Context {
if tmpl == nil {
panic("must provide a template")
}
idm := tpl.Context.GetDependencyManagerInCurrentScope(ctx)
if idm == nil {
return ctx
}
if info, ok := tmpl.(identity.IdentityProvider); ok {
idm.AddIdentity(info.GetIdentity())
}
// The receive is the "." in the method execution or map lookup, e.g. the Page in .Resources.
if hreflect.IsValid(receiver) {
in := receiver.Interface()
if idlp, ok := in.(identity.ForEeachIdentityByNameProvider); ok {
// This will skip repeated .RelPermalink usage on transformed resources
// which is not fingerprinted, e.g. to
// prevent all HTML pages to be re-rendered on a small CSS change.
idlp.ForEeachIdentityByName(name, func(id identity.Identity) bool {
idm.AddIdentity(id)
return false
})
} else {
identity.WalkIdentitiesShallow(in, func(level int, id identity.Identity) bool {
idm.AddIdentity(id)
return false
})
}
}
return ctx
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/templatestore.go | tpl/tplimpl/templatestore.go | // Copyright 2025 The Hugo Authors. All rights reserved.
//
// Portions Copyright The Go Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tplimpl
import (
"bytes"
"context"
"embed"
"errors"
"fmt"
"io"
"io/fs"
"iter"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gohugoio/hugo/common/collections"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/common/hstrings"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugofs/files"
"github.com/gohugoio/hugo/hugolib/doctree"
"github.com/gohugoio/hugo/hugolib/sitesmatrix"
"github.com/gohugoio/hugo/identity"
gc "github.com/gohugoio/hugo/markup/goldmark/goldmark_config"
"github.com/gohugoio/hugo/media"
"github.com/gohugoio/hugo/metrics"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/resources/kinds"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/tpl"
htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"
texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
"github.com/spf13/afero"
)
const (
CategoryLayout Category = iota + 1
CategoryBaseof
CategoryMarkup
CategoryShortcode
CategoryPartial
// Internal categories
CategoryServer
CategoryHugo
)
const (
SubCategoryMain SubCategory = iota
SubCategoryEmbedded // Internal Hugo templates
SubCategoryInline // Inline partials
)
const (
containerMarkup = "_markup"
containerShortcodes = "_shortcodes"
shortcodesPathIdentifier = "/_shortcodes/"
containerPartials = "_partials"
)
const (
layoutAll = "all"
layoutList = "list"
layoutSingle = "single"
)
var (
_ identity.IdentityProvider = (*TemplInfo)(nil)
_ identity.IsProbablyDependentProvider = (*TemplInfo)(nil)
_ identity.IsProbablyDependencyProvider = (*TemplInfo)(nil)
)
const (
processingStateInitial processingState = iota
processingStateTransformed
)
// The identifiers may be truncated in the log, e.g.
// "executing "main" at <$scaled.SRelPermalin...>: can't evaluate field SRelPermalink in type *resource.Image"
// We need this to identify position in templates with base templates applied.
var identifiersRe = regexp.MustCompile(`at \<(.*?)(\.{3})?\>:`)
var weightNoMatch = weight{w1: -1}
//
//go:embed all:embedded/templates/*
var embeddedTemplatesFs embed.FS
func NewStore(opts StoreOptions, siteOpts SiteOptions) (*TemplateStore, error) {
html, ok := opts.OutputFormats.GetByName("html")
if !ok {
panic("HTML output format not found")
}
s := &TemplateStore{
opts: opts,
siteOpts: siteOpts,
optsOrig: opts,
siteOptsOrig: siteOpts,
htmlFormat: html,
storeSite: configureSiteStorage(siteOpts, opts.Watching),
treeMain: doctree.NewSimpleTree[map[nodeKey]*TemplInfo](),
treeShortcodes: doctree.NewSimpleTree[map[string]map[TemplateDescriptor]*TemplInfo](),
templatesByPath: maps.NewCache[string, *TemplInfo](),
shortcodesByName: maps.NewCache[string, *TemplInfo](),
cacheLookupPartials: maps.NewCache[string, *TemplInfo](),
templatesSnapshotSet: maps.NewCache[*parse.Tree, struct{}](),
// Note that the funcs passed below is just for name validation.
tns: newTemplateNamespace(siteOpts.TemplateFuncs),
dh: descriptorHandler{
opts: opts,
},
}
if err := s.init(); err != nil {
return nil, err
}
if err := s.insertTemplates(nil, false); err != nil {
return nil, err
}
if err := s.insertEmbedded(); err != nil {
return nil, err
}
if err := s.parseTemplates(false); err != nil {
return nil, err
}
if err := s.extractInlinePartials(false); err != nil {
return nil, err
}
if err := s.transformTemplates(); err != nil {
return nil, err
}
if err := s.tns.createPrototypes(true); err != nil {
return nil, err
}
if err := s.prepareTemplates(); err != nil {
return nil, err
}
return s, nil
}
//go:generate stringer -type Category
type Category int
type SiteOptions struct {
Site page.Site
TemplateFuncs map[string]any
}
type StoreOptions struct {
// The filesystem to use.
Fs afero.Fs
// The logger to use.
Log loggers.Logger
// The path handler to use.
PathParser *paths.PathParser
// Set when --enableTemplateMetrics is set.
Metrics metrics.Provider
// All configured output formats.
OutputFormats output.Formats
// All configured media types.
MediaTypes media.Types
// The default output format.
DefaultOutputFormat string
// Taxonomy config.
TaxonomySingularPlural map[string]string
// Whether we are in watch or server mode.
Watching bool
// The render hook configuration.
RenderHooks gc.RenderHooks
// compiled.
legacyMappingTaxonomy map[string]legacyOrdinalMapping
legacyMappingTerm map[string]legacyOrdinalMapping
legacyMappingSection map[string]legacyOrdinalMapping
}
//go:generate stringer -type SubCategory
type SubCategory int
type TemplInfo struct {
// The category of this template.
category Category
subCategory SubCategory
// PathInfo info.
PathInfo *paths.Path
// Set when backed by a file.
Fi hugofs.FileMetaInfo
// The template content with any leading BOM removed.
content string
// The parsed template.
// Note that any baseof template will be applied later.
Template tpl.Template
// If no baseof is needed, this will be set to true.
// E.g. shortcode templates do not need a baseof.
noBaseOf bool
// If NoBaseOf is false, we will look for the final template in this tree.
baseVariants *doctree.SimpleTree[map[TemplateDescriptor]*TemplWithBaseApplied]
// The template variants that are based on this template.
overlays []*TemplInfo
// The base template used, if any.
base *TemplInfo
// The descriptior that this template represents.
D TemplateDescriptor
matrix sitesmatrix.VectorProvider // language, version, role.
// Parser state.
ParseInfo ParseInfo
// The execution counter for this template.
executionCounter atomic.Uint64
// processing state.
state processingState
isLegacyMapped bool
}
func (ti *TemplInfo) SubCategory() SubCategory {
return ti.subCategory
}
func (ti *TemplInfo) BaseVariantsSeq() iter.Seq[*TemplWithBaseApplied] {
return func(yield func(*TemplWithBaseApplied) bool) {
for _, v := range ti.baseVariants.All() {
for _, vv := range v {
if !yield(vv) {
return
}
}
}
}
}
func (t *TemplInfo) IdentifierBase() string {
if t.PathInfo == nil {
return t.Name()
}
return t.PathInfo.IdentifierBase()
}
func (t *TemplInfo) GetIdentity() identity.Identity {
return t
}
func (ti *TemplInfo) Name() string {
if ti.Template == nil {
if ti.PathInfo != nil {
return ti.PathInfo.PathNoLeadingSlash()
}
}
return ti.Template.Name()
}
func (ti *TemplInfo) Prepare() (*texttemplate.Template, error) {
return ti.Template.Prepare()
}
func (t *TemplInfo) IsProbablyDependency(other identity.Identity) bool {
return t.isProbablyTheSameIDAs(other)
}
func (t *TemplInfo) IsProbablyDependent(other identity.Identity) bool {
for _, overlay := range t.overlays {
if overlay.isProbablyTheSameIDAs(other) {
return true
}
}
return t.isProbablyTheSameIDAs(other)
}
func (ti *TemplInfo) String() string {
if ti == nil {
return "<nil>"
}
return ti.PathInfo.String()
}
func (ti *TemplInfo) findBestMatchBaseof(s *TemplateStore, d1 TemplateDescriptor, dims1 sitesmatrix.VectorProvider, k1 string, slashCountK1 int, best *bestMatch) {
if ti.baseVariants == nil {
return
}
ti.baseVariants.WalkPath(k1, func(k2 string, v map[TemplateDescriptor]*TemplWithBaseApplied) (bool, error) {
if !s.inPath(k1, k2) {
return false, nil
}
slashCountK2 := strings.Count(k2, "/")
distance := slashCountK1 - slashCountK2
for d2, vv := range v {
weight := s.dh.compareDescriptors(CategoryBaseof, d1, d2, dims1, vv.Base.matrix)
weight.distance = distance
if best.isBetter(weight, vv.Template) {
best.updateValues(weight, k2, d2, vv.Template)
}
}
return false, nil
})
}
func (t *TemplInfo) isProbablyTheSameIDAs(other identity.Identity) bool {
if t.IdentifierBase() == other.IdentifierBase() {
return true
}
if t.Fi != nil && t.Fi.Meta().PathInfo != t.PathInfo {
return other.IdentifierBase() == t.Fi.Meta().PathInfo.IdentifierBase()
}
return false
}
// Implements the additional methods in tpl.CurrentTemplateInfoOps.
func (ti *TemplInfo) Base() tpl.CurrentTemplateInfoCommonOps {
return ti.base
}
func (ti *TemplInfo) Filename() string {
if ti.Fi == nil {
return ""
}
return ti.Fi.Meta().Filename
}
type TemplWithBaseApplied struct {
// The template that's overlaid on top of the base template.
Overlay *TemplInfo
// The base template.
Base *TemplInfo
// This is the final template that can be used to render a page.
Template *TemplInfo
}
// TemplateQuery is used in LookupPagesLayout to find the best matching template.
type TemplateQuery struct {
// The path to walk down to.
Path string
// The name to look for. Used for shortcode queries.
Name string
// The category to look in.
Category Category
// The sites variants to consider.
Sites sitesmatrix.VectorProvider
// The template descriptor to match against.
Desc TemplateDescriptor
// Whether to even consider this candidate.
Consider func(candidate *TemplInfo) bool
}
func (q *TemplateQuery) init() {
if q.Desc.Kind == kinds.KindTemporary {
q.Desc.Kind = ""
} else if kinds.GetKindMain(q.Desc.Kind) == "" {
q.Desc.Kind = ""
}
if q.Desc.LayoutFromTemplate == "" && q.Desc.Kind != "" {
if q.Desc.Kind == kinds.KindPage {
q.Desc.LayoutFromTemplate = layoutSingle
} else {
q.Desc.LayoutFromTemplate = layoutList
}
}
if q.Consider == nil {
q.Consider = func(match *TemplInfo) bool {
return true
}
}
q.Name = strings.ToLower(q.Name)
if q.Category == 0 {
panic("category not set")
}
}
type TemplateStore struct {
opts StoreOptions
siteOpts SiteOptions
htmlFormat output.Format
treeMain *doctree.SimpleTree[map[nodeKey]*TemplInfo]
treeShortcodes *doctree.SimpleTree[map[string]map[TemplateDescriptor]*TemplInfo]
templatesByPath *maps.Cache[string, *TemplInfo]
shortcodesByName *maps.Cache[string, *TemplInfo]
templatesSnapshotSet *maps.Cache[*parse.Tree, struct{}]
dh descriptorHandler
// The template namespace.
tns *templateNamespace
// Site specific state.
// All above this is reused.
storeSite *storeSite
// For testing benchmarking.
optsOrig StoreOptions
siteOptsOrig SiteOptions
// caches. These need to be refreshed when the templates are refreshed.
cacheLookupPartials *maps.Cache[string, *TemplInfo]
}
// NewFromOpts creates a new store with the same configuration as the original.
// Used for testing/benchmarking.
func (s *TemplateStore) NewFromOpts() (*TemplateStore, error) {
return NewStore(s.optsOrig, s.siteOptsOrig)
}
// In the previous implementation of base templates in Hugo, we parsed and applied these base templates on
// request, e.g. in the middle of rendering. The idea was that we couldn't know upfront which layoyt/base template
// combination that would be used.
// This, however, added a lot of complexity involving a careful dance of template cloning and parsing
// (Go HTML tenplates cannot be parsed after any of the templates in the tree have been executed).
// FindAllBaseTemplateCandidates finds all base template candidates for the given descriptor so we can apply them upfront.
// In this setup we may end up with unused base templates, but not having to do the cloning should more than make up for that.
func (s *TemplateStore) FindAllBaseTemplateCandidates(overlayKey string, d1 TemplateDescriptor, dims1 sitesmatrix.VectorProvider) []keyTemplateInfo {
var result []keyTemplateInfo
s.treeMain.Walk(func(k string, v map[nodeKey]*TemplInfo) (bool, error) {
for _, vv := range v {
if vv.category != CategoryBaseof {
continue
}
if vv.D.isKindInLayout(d1.LayoutFromTemplate) && s.dh.compareDescriptors(CategoryBaseof, d1, vv.D, dims1, vv.matrix).w1 > 0 {
result = append(result, keyTemplateInfo{Key: k, Info: vv})
}
}
return false, nil
})
return result
}
// PrepareTopLevelRenderCtx prepares a context for top-level rendering of a page.
func (t *TemplateStore) PrepareTopLevelRenderCtx(ctx context.Context, p page.Page) context.Context {
if p != nil {
ctx = tpl.Context.Page.Set(ctx, p)
}
ctx = tpl.Context.PartialDecoratorIDStack.Set(ctx, collections.NewStack[*tpl.StringBool]())
return ctx
}
func (t *TemplateStore) ExecuteWithContext(ctx context.Context, ti *TemplInfo, wr io.Writer, data any) error {
return t.ExecuteWithContextAndKey(ctx, "", ti, wr, data)
}
func (t *TemplateStore) ExecuteWithContextAndKey(ctx context.Context, key string, ti *TemplInfo, wr io.Writer, data any) error {
defer func() {
ti.executionCounter.Add(1)
if ti.base != nil {
ti.base.executionCounter.Add(1)
}
}()
templ := ti.Template
parent := tpl.Context.CurrentTemplate.Get(ctx)
var level int
if parent != nil {
level = parent.Level + 1
}
currentTi := &tpl.CurrentTemplateInfo{
Parent: parent,
Level: level,
Key: key,
CurrentTemplateInfoOps: ti,
}
ctx = tpl.Context.CurrentTemplate.Set(ctx, currentTi)
const levelThreshold = 999
if level > levelThreshold {
return fmt.Errorf("maximum template call stack size exceeded in %q", ti.Filename())
}
if t.opts.Metrics != nil {
defer t.opts.Metrics.MeasureSince(templ.Name(), time.Now())
}
execErr := t.storeSite.executer.ExecuteWithContext(ctx, ti, wr, data)
if execErr != nil {
return t.addFileContext(ti, "execute of template failed", execErr)
}
return nil
}
func (t *TemplateStore) GetFunc(name string) (reflect.Value, bool) {
v, found := t.storeSite.execHelper.funcs[name]
return v, found
}
func (s *TemplateStore) GetIdentity(p string) identity.Identity {
p = paths.AddLeadingSlash(p)
v, found := s.templatesByPath.Get(p)
if !found {
return nil
}
return v.GetIdentity()
}
func (t *TemplateStore) LookupByPath(templatePath string) *TemplInfo {
v, _ := t.templatesByPath.Get(templatePath)
return v
}
var bestPool = sync.Pool{
New: func() any {
return &bestMatch{}
},
}
func (s *TemplateStore) getBest() *bestMatch {
v := bestPool.Get()
b := v.(*bestMatch)
b.defaultOutputformat = s.opts.DefaultOutputFormat
return b
}
func (s *TemplateStore) putBest(b *bestMatch) {
b.reset()
bestPool.Put(b)
}
func (s *TemplateStore) LookupPagesLayout(q TemplateQuery) *TemplInfo {
q.init()
key := s.key(q.Path)
slashCountKey := strings.Count(key, "/")
best1 := s.getBest()
defer s.putBest(best1)
s.findBestMatchWalkPath(q, key, slashCountKey, best1)
if best1.w.w1 <= 0 {
return nil
}
m := best1.templ
if m.noBaseOf {
return m
}
best1.reset()
m.findBestMatchBaseof(s, q.Desc, q.Sites, key, slashCountKey, best1)
if best1.w.w1 <= 0 {
return nil
}
return best1.templ
}
func (s *TemplateStore) LookupPartial(pth string) *TemplInfo {
ti, _ := s.cacheLookupPartials.GetOrCreate(pth, func() (*TemplInfo, error) {
pi := s.opts.PathParser.Parse(files.ComponentFolderLayouts, pth).ForType(paths.TypePartial)
k1, _, _, desc, matrix, err := s.toKeyCategoryAndDescriptor(pi, nil)
if err != nil {
return nil, err
}
if desc.OutputFormat == "" && desc.MediaType == "" {
// Assume HTML.
desc.OutputFormat = s.htmlFormat.Name
desc.MediaType = s.htmlFormat.MediaType.Type
desc.IsPlainText = s.htmlFormat.IsPlainText
}
best := s.getBest()
defer s.putBest(best)
s.findBestMatchGet(s.key(path.Join(containerPartials, k1)), CategoryPartial, nil, desc, matrix, best)
return best.templ, nil
})
return ti
}
func (s *TemplateStore) LookupShortcodeByName(name string) *TemplInfo {
name = strings.ToLower(name)
ti, _ := s.shortcodesByName.Get(name)
if ti == nil {
return nil
}
return ti
}
func (s *TemplateStore) LookupShortcode(q TemplateQuery) (*TemplInfo, error) {
q.init()
k1 := s.key(q.Path)
slashCountK1 := strings.Count(k1, "/")
best := s.getBest()
defer s.putBest(best)
s.treeShortcodes.WalkPath(k1, func(k2 string, m map[string]map[TemplateDescriptor]*TemplInfo) (bool, error) {
if !s.inPath(k1, k2) {
return false, nil
}
slashCountK2 := strings.Count(k2, "/")
distance := slashCountK1 - slashCountK2
v, found := m[q.Name]
if !found {
return false, nil
}
for k, vv := range v {
best.candidates = append(best.candidates, vv)
if !q.Consider(vv) {
continue
}
weight := s.dh.compareDescriptors(q.Category, q.Desc, k, q.Sites, vv.matrix)
weight.distance = distance
isBetter := best.isBetter(weight, vv)
if isBetter {
best.updateValues(weight, k2, k, vv)
}
}
return false, nil
})
if best.w.w1 <= 0 {
var err error
if s := best.candidatesAsStringSlice(); s != nil {
msg := fmt.Sprintf("no compatible template found for shortcode %q in %s", q.Name, s)
if !q.Desc.IsPlainText {
msg += "; note that to use plain text template shortcodes in HTML you need to use the shortcode {{% delimiter"
}
err = errors.New(msg)
} else {
err = fmt.Errorf("no template found for shortcode %q", q.Name)
}
return nil, err
}
return best.templ, nil
}
// PrintDebug is for testing/debugging only.
func (s *TemplateStore) PrintDebug(prefix string, category Category, w io.Writer) {
if w == nil {
w = os.Stdout
}
printOne := func(key string, vv *TemplInfo) {
level := strings.Count(key, "/")
if category != vv.category {
return
}
s := strings.ReplaceAll(strings.TrimSpace(vv.content), "\n", " ")
ts := fmt.Sprintf("kind: %q layout: %q content: %.30s", vv.D.Kind, vv.D.LayoutFromTemplate, s)
fmt.Fprintf(w, "%s%s %s\n", strings.Repeat(" ", level), key, ts)
}
s.treeMain.WalkPrefix(prefix, func(key string, v map[nodeKey]*TemplInfo) (bool, error) {
for _, vv := range v {
printOne(key, vv)
}
return false, nil
})
s.treeShortcodes.WalkPrefix(prefix, func(key string, v map[string]map[TemplateDescriptor]*TemplInfo) (bool, error) {
for _, vv := range v {
for _, vv2 := range vv {
printOne(key, vv2)
}
}
return false, nil
})
}
func (s *TemplateStore) clearCaches() {
s.cacheLookupPartials.Reset()
}
// RefreshFiles refreshes this store for the files matching the given predicate.
func (s *TemplateStore) RefreshFiles(include func(fi hugofs.FileMetaInfo) bool) error {
s.clearCaches()
if err := s.tns.createPrototypesParse(); err != nil {
return err
}
if err := s.insertTemplates(include, true); err != nil {
return err
}
if err := s.createTemplatesSnapshot(); err != nil {
return err
}
if err := s.parseTemplates(true); err != nil {
return err
}
if err := s.extractInlinePartials(true); err != nil {
return err
}
if err := s.transformTemplates(); err != nil {
return err
}
if err := s.tns.createPrototypes(false); err != nil {
return err
}
if err := s.prepareTemplates(); err != nil {
return err
}
return nil
}
func (s *TemplateStore) HasTemplate(templatePath string) bool {
templatePath = strings.ToLower(templatePath)
templatePath = paths.AddLeadingSlash(templatePath)
return s.templatesByPath.Contains(templatePath)
}
func (t *TemplateStore) TextLookup(name string) *TemplInfo {
templ := t.tns.standaloneText.Lookup(name)
if templ == nil {
return nil
}
return &TemplInfo{
Template: templ,
}
}
func (t *TemplateStore) TextParse(name, tpl string) (*TemplInfo, error) {
templ, err := t.tns.standaloneText.New(name).Parse(tpl)
if err != nil {
return nil, err
}
return &TemplInfo{
Template: templ,
}, nil
}
func (t *TemplateStore) UnusedTemplates() []*TemplInfo {
var unused []*TemplInfo
for vv := range t.templates() {
if vv.subCategory != SubCategoryMain || vv.isLegacyMapped {
// Skip inline partials and internal templates.
continue
}
if vv.executionCounter.Load() == 0 {
unused = append(unused, vv)
}
}
sort.Sort(byPath(unused))
return unused
}
// WithSiteOpts creates a new store with the given site options.
// This is used to create per site template store, all sharing the same templates,
// but with a different template function execution context.
func (s TemplateStore) WithSiteOpts(opts SiteOptions) *TemplateStore {
s.siteOpts = opts
s.storeSite = configureSiteStorage(opts, s.opts.Watching)
return &s
}
func (s *TemplateStore) findBestMatchGet(key string, category Category,
consider func(candidate *TemplInfo) bool, d1 TemplateDescriptor, dims1 sitesmatrix.VectorProvider, best *bestMatch,
) {
key = strings.ToLower(key)
v := s.treeMain.Get(key)
if v == nil {
return
}
for k, vv := range v {
if vv.category != category {
continue
}
if consider != nil && !consider(vv) {
continue
}
weight := s.dh.compareDescriptors(category, d1, k.d, dims1, vv.matrix)
if best.isBetter(weight, vv) {
best.updateValues(weight, key, k.d, vv)
}
}
}
func (s *TemplateStore) inPath(k1, k2 string) bool {
if k1 != k2 && !strings.HasPrefix(k1, k2+"/") {
return false
}
return true
}
func (s *TemplateStore) findBestMatchWalkPath(q TemplateQuery, k1 string, slashCountK1 int, best *bestMatch) {
s.treeMain.WalkPath(k1, func(k2 string, v map[nodeKey]*TemplInfo) (bool, error) {
if !s.inPath(k1, k2) {
return false, nil
}
slashCountK2 := strings.Count(k2, "/")
distance := slashCountK1 - slashCountK2
for k, vv := range v {
if vv.category != q.Category {
continue
}
if !q.Consider(vv) {
continue
}
weight := s.dh.compareDescriptors(q.Category, q.Desc, k.d, q.Sites, vv.matrix)
weight.distance = distance
isBetter := best.isBetter(weight, vv)
if isBetter {
best.updateValues(weight, k2, k.d, vv)
}
}
return false, nil
})
}
func (t *TemplateStore) addDeferredTemplate(owner *TemplInfo, name string, n *parse.ListNode) error {
if _, found := t.templatesByPath.Get(name); found {
return nil
}
var templ tpl.Template
if owner.D.IsPlainText {
prototype := t.tns.parseText
tt, err := prototype.New(name).Parse("")
if err != nil {
return fmt.Errorf("failed to parse empty text template %q: %w", name, err)
}
tt.Tree.Root = n
templ = tt
} else {
prototype := t.tns.parseHTML
tt, err := prototype.New(name).Parse("")
if err != nil {
return fmt.Errorf("failed to parse empty HTML template %q: %w", name, err)
}
tt.Tree.Root = n
templ = tt
}
t.templatesByPath.Set(name, &TemplInfo{
Fi: owner.Fi,
PathInfo: owner.PathInfo,
D: owner.D,
Template: templ,
})
return nil
}
func (s *TemplateStore) addFileContext(ti *TemplInfo, what string, inerr error) error {
if ti.Fi == nil {
return inerr
}
identifiers := s.extractIdentifiers(inerr.Error())
checkFilename := func(fi hugofs.FileMetaInfo, inErr error) (int, error) {
var matchWeight int
lineMatcher := func(m herrors.LineMatcher) int {
if m.Position.LineNumber != m.LineNumber {
return -1
}
matchWeight++
for _, id := range identifiers {
if strings.Contains(m.Line, id) {
// We found the line, but return a 0 to signal to
// use the column from the error message.
matchWeight++
return 0
}
}
return 0
}
f, err := fi.Meta().Open()
if err != nil {
return -1, inErr
}
defer f.Close()
fe := herrors.NewFileErrorFromName(inErr, fi.Meta().Filename)
fe.UpdateContent(f, lineMatcher)
return matchWeight, fe
}
inerr = fmt.Errorf("%s: %w", what, inerr)
var (
err1 error
weight1 int
err2 error
weight2 int
)
weight1, err1 = checkFilename(ti.Fi, inerr)
if ti.base != nil {
weight2, err2 = checkFilename(ti.base.Fi, inerr)
}
if err2 != nil && weight2 > weight1 {
return err2
}
return err1
}
func (s *TemplateStore) extractIdentifiers(line string) []string {
m := identifiersRe.FindAllStringSubmatch(line, -1)
identifiers := make([]string, len(m))
for i := range m {
identifiers[i] = m[i][1]
}
return identifiers
}
func (s *TemplateStore) extractInlinePartials(rebuild bool) error {
isPartialName := func(s string) bool {
return strings.HasPrefix(s, "partials/") || strings.HasPrefix(s, "_partials/")
}
// We may find both inline and external partials in the current template namespaces,
// so only add the ones we have not seen before.
for templ := range s.allRawTemplates() {
if templ.Name() == "" || !isPartialName(templ.Name()) {
continue
}
if rebuild && s.templatesSnapshotSet.Contains(getParseTree(templ)) {
// This partial was not created during this build.
continue
}
name := templ.Name()
if !paths.HasExt(name) {
// Assume HTML. This in line with how the lookup works.
name = name + s.htmlFormat.MediaType.FirstSuffix.FullSuffix
}
if !strings.HasPrefix(name, "_") {
name = "_" + name
}
pi := s.opts.PathParser.Parse(files.ComponentFolderLayouts, name)
ti, err := s.insertTemplate(pi, nil, SubCategoryInline, false, s.treeMain)
if err != nil {
return err
}
if ti != nil {
ti.Template = templ
ti.noBaseOf = true
ti.subCategory = SubCategoryInline
ti.D.IsPlainText = isText(templ)
}
}
return nil
}
func (s *TemplateStore) allRawTemplates() iter.Seq[tpl.Template] {
p := s.tns
return func(yield func(tpl.Template) bool) {
for t := range p.templatesIn(p.parseHTML) {
if !yield(t) {
return
}
}
for t := range p.templatesIn(p.parseText) {
if !yield(t) {
return
}
}
for _, tt := range p.baseofHtmlClones {
for t := range p.templatesIn(tt) {
if !yield(t) {
return
}
}
}
for _, tt := range p.baseofTextClones {
for t := range p.templatesIn(tt) {
if !yield(t) {
return
}
}
}
}
}
func (s *TemplateStore) insertEmbedded() error {
return fs.WalkDir(embeddedTemplatesFs, ".", func(tpath string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d == nil || d.IsDir() || strings.HasPrefix(d.Name(), ".") {
return nil
}
templb, err := embeddedTemplatesFs.ReadFile(tpath)
if err != nil {
return err
}
// Get the newlines on Windows in line with how we had it back when we used Go Generate
// to write the templates to Go files.
templ := string(bytes.ReplaceAll(templb, []byte("\r\n"), []byte("\n")))
name := strings.TrimPrefix(filepath.ToSlash(tpath), "embedded/templates/")
insertOne := func(name, content string) error {
pi := s.opts.PathParser.Parse(files.ComponentFolderLayouts, name)
var (
ti *TemplInfo
err error
)
if pi.Section() == containerShortcodes {
ti, err = s.insertShortcode(pi, nil, false, s.treeShortcodes)
if err != nil {
return err
}
} else {
ti, err = s.insertTemplate(pi, nil, SubCategoryEmbedded, false, s.treeMain)
if err != nil {
return err
}
}
if ti != nil {
// Currently none of the embedded templates need a baseof template.
ti.noBaseOf = true
ti.content = content
ti.subCategory = SubCategoryEmbedded
}
return nil
}
// Copy the embedded HTML table render hook to each output format.
// See https://github.com/gohugoio/hugo/issues/13351.
if name == path.Join(containerMarkup, "render-table.html") {
for _, of := range s.opts.OutputFormats {
path := paths.TrimExt(name) + "." + of.Name + of.MediaType.FirstSuffix.FullSuffix
if err := insertOne(path, templ); err != nil {
return err
}
}
return nil
}
if err := insertOne(name, templ); err != nil {
return err
}
if aliases, found := embeddedTemplatesAliases[name]; found {
for _, alias := range aliases {
if err := insertOne(alias, templ); err != nil {
return err
}
}
}
return nil
})
}
func (s *TemplateStore) setTemplateByPath(p string, ti *TemplInfo) {
s.templatesByPath.Set(p, ti)
}
func (s *TemplateStore) insertShortcode(pi *paths.Path, fi hugofs.FileMetaInfo, replace bool, tree doctree.Tree[map[string]map[TemplateDescriptor]*TemplInfo]) (*TemplInfo, error) {
k1, k2, _, d, matrix, err := s.toKeyCategoryAndDescriptor(pi, fi)
if err != nil {
return nil, err
}
m := tree.Get(k1)
if m == nil {
m = make(map[string]map[TemplateDescriptor]*TemplInfo)
tree.Insert(k1, m)
}
m1, found := m[k2]
if found {
if _, found := m1[d]; found {
if !replace {
return nil, nil
}
}
} else {
m1 = make(map[TemplateDescriptor]*TemplInfo)
m[k2] = m1
}
ti := &TemplInfo{
PathInfo: pi,
Fi: fi,
D: d,
matrix: matrix,
category: CategoryShortcode,
noBaseOf: true,
}
m1[d] = ti
s.shortcodesByName.Set(k2, ti)
s.setTemplateByPath(pi.Path(), ti)
if fi != nil {
if pi2 := fi.Meta().PathInfo; pi2 != pi {
s.setTemplateByPath(pi2.Path(), ti)
}
}
return ti, nil
}
func (s *TemplateStore) insertTemplate(pi *paths.Path, fi hugofs.FileMetaInfo, subCategory SubCategory, replace bool, tree doctree.Tree[map[nodeKey]*TemplInfo]) (*TemplInfo, error) {
key, _, category, d, matrix, err := s.toKeyCategoryAndDescriptor(pi, fi)
// See #13577. Warn for now.
if err != nil {
var loc string
if fi != nil {
loc = fmt.Sprintf("file %q", fi.Meta().Filename)
} else {
loc = fmt.Sprintf("path %q", pi.Path())
}
s.opts.Log.Warnf("skipping template %s: %s", loc, err)
return nil, nil
}
return s.insertTemplate2(pi, fi, key, category, subCategory, d, matrix, replace, false, tree)
}
func (s *TemplateStore) insertTemplate2(
pi *paths.Path,
fi hugofs.FileMetaInfo,
key string,
category Category,
subCategory SubCategory,
d TemplateDescriptor,
matrix sitesmatrix.VectorStore,
replace, isLegacyMapped bool,
tree doctree.Tree[map[nodeKey]*TemplInfo],
) (*TemplInfo, error) {
if category == 0 {
panic("category not set")
}
if category == CategoryPartial && d.OutputFormat == "" && d.MediaType == "" {
// See issue #13601.
d.OutputFormat = s.htmlFormat.Name
d.MediaType = s.htmlFormat.MediaType.Type
}
m := tree.Get(key)
nk := nodeKey{c: category, d: d}
if m == nil {
m = make(map[nodeKey]*TemplInfo)
tree.Insert(key, m)
}
var (
nkExisting *TemplInfo
existingFound bool
)
if d.SitesHash == 0 {
// inline partials.
for k, v := range m {
d2 := v.D
d2.SitesHash = 0
if d == d2 {
nkExisting = v
nk = k
existingFound = true
break
}
}
} else {
nkExisting, existingFound = m[nk]
}
if !replace && existingFound && fi != nil && nkExisting.Fi != nil {
// See issue #13715.
// We do the merge on the file system level, but from Hugo v0.146.0 we have a situation where
// the project may well have a different layouts layout compared to the theme(s) it uses.
// We could possibly have fixed that on a lower (file system) level, but since this is just
// a temporary situation (until all projects are updated),
// do a replace here if the file comes from higher up in the module chain.
replace = fi.Meta().ModuleOrdinal < nkExisting.Fi.Meta().ModuleOrdinal
}
if !replace && existingFound {
// Always replace inline partials to allow for reloading.
replace = subCategory == SubCategoryInline && nkExisting.subCategory == SubCategoryInline
}
if !replace && existingFound {
if len(pi.Identifiers()) >= len(nkExisting.PathInfo.Identifiers()) {
// e.g. /pages/home.foo.html and /pages/home.html where foo may be a valid language name in another site.
return nil, nil
}
}
ti := &TemplInfo{
PathInfo: pi,
Fi: fi,
D: d,
matrix: matrix,
category: category,
subCategory: subCategory,
noBaseOf: category > CategoryLayout,
isLegacyMapped: isLegacyMapped,
}
m[nk] = ti
if !isLegacyMapped {
s.setTemplateByPath(pi.Path(), ti)
if fi != nil {
if pi2 := fi.Meta().PathInfo; pi2 != pi {
s.setTemplateByPath(pi2.Path(), ti)
}
}
}
return ti, nil
}
func (s *TemplateStore) insertTemplates(include func(fi hugofs.FileMetaInfo) bool, partialRebuild bool) error {
if include == nil {
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | true |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/templatestore_legacy1_integration_test.go | tpl/tplimpl/templatestore_legacy1_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 tplimpl_test
import (
"testing"
"github.com/gohugoio/hugo/hugolib"
)
// Old as in before Hugo v0.146.0.
func TestLayoutsOldSetup(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
[languages]
[languages.en]
title = "Title in English"
weight = 1
[languages.nn]
title = "Tittel på nynorsk"
weight = 2
-- layouts/index.html --
Home.
{{ template "_internal/twitter_cards.html" . }}
-- layouts/_default/single.html --
Single.
-- layouts/_default/single.nn.html --
Single NN.
-- layouts/_default/list.html --
List HTML.
-- layouts/docs/list-baseof.html --
Docs Baseof List HTML.
{{ block "main" . }}Docs Baseof List HTML main block.{{ end }}
-- layouts/docs/list.section.html --
{{ define "main" }}
Docs List HTML.
{{ end }}
-- layouts/_default/list.json --
List JSON.
-- layouts/_default/list.rss.xml --
List RSS.
-- layouts/_default/list.nn.rss.xml --
List NN RSS.
-- layouts/_default/baseof.html --
Base.
-- layouts/partials/mypartial.html --
Partial.
-- layouts/shortcodes/myshortcode.html --
Shortcode.
-- content/docs/p1.md --
---
title: "P1"
---
`
b := hugolib.Test(t, files)
// b.DebugPrint("", tplimpl.CategoryBaseof)
b.AssertFileContent("public/en/docs/index.html", "Docs Baseof List HTML.\n\nDocs List HTML.")
}
func TestLayoutsOldSetupBaseofPrefix(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/_default/layout1-baseof.html --
Baseof layout1. {{ block "main" . }}{{ end }}
-- layouts/_default/layout2-baseof.html --
Baseof layout2. {{ block "main" . }}{{ end }}
-- layouts/_default/layout1.html --
{{ define "main" }}Layout1. {{ .Title }}{{ end }}
-- layouts/_default/layout2.html --
{{ define "main" }}Layout2. {{ .Title }}{{ end }}
-- content/p1.md --
---
title: "P1"
layout: "layout1"
---
-- content/p2.md --
---
title: "P2"
layout: "layout2"
---
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "Baseof layout1. Layout1. P1")
b.AssertFileContent("public/p2/index.html", "Baseof layout2. Layout2. P2")
}
func TestLayoutsOldSetupTaxonomyAndTerm(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
[taxonomies]
cat = 'cats'
dog = 'dogs'
# Templates for term taxonomy, old setup.
-- layouts/dogs/terms.html --
Dogs Terms. Most specific taxonomy template.
-- layouts/taxonomy/terms.html --
Taxonomy Terms. Down the list.
# Templates for term term, old setup.
-- layouts/dogs/term.html --
Dogs Term. Most specific term template.
-- layouts/term/term.html --
Term Term. Down the list.
-- layouts/dogs/max/list.html --
max: {{ .Title }}
-- layouts/_default/list.html --
Default list.
-- layouts/_default/single.html --
Default single.
-- content/p1.md --
---
title: "P1"
dogs: ["luna", "daisy", "max"]
---
`
b := hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertLogContains("! WARN")
b.AssertFileContent("public/dogs/index.html", "Dogs Terms. Most specific taxonomy template.")
b.AssertFileContent("public/dogs/luna/index.html", "Dogs Term. Most specific term template.")
b.AssertFileContent("public/dogs/max/index.html", "max: Max") // layouts/dogs/max/list.html wins over layouts/term/term.html because of distance.
}
func TestLayoutsOldSetupCustomRSS(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term", "page"]
[outputs]
home = ["rss"]
-- layouts/_default/list.rss.xml --
List RSS.
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.xml", "List RSS.")
}
func TestLayoutWithLanguagesLegacy(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term", "sitemap", "rss"]
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
[languages]
[languages.en]
weight = 1
[languages.nn]
weight = 2
[languages.sv]
weight = 3
-- layouts/_default/single.en.html --
layouts/_default/single.html
-- layouts/_default/single.nn.html --
layouts/_default/single.nn.html
-- layouts/_default/single.sv.html --
layouts/_default/single.sv.html
-- content/p1.md --
---
title: "P1"
---
-- content/p1.nn.md --
---
title: "P1 NN"
---
-- content/p1.sv.md --
---
title: "P1 SV"
---
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/en/p1/index.html", "layouts/_default/single.html")
b.AssertFileContent("public/nn/p1/index.html", "layouts/_default/single.nn.html")
b.AssertFileContent("public/sv/p1/index.html", "layouts/_default/single.sv.html")
}
func TestLayoutWithLanguagesLegacyMounts(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term", "sitemap", "rss"]
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
[languages]
[languages.en]
weight = 1
[languages.nn]
weight = 2
[languages.sv]
weight = 3
[[module.mounts]]
source = 'layouts/en'
target = 'layouts'
lang = 'en'
[[module.mounts]]
source = 'layouts/nn'
target = 'layouts'
lang = 'nn'
[[module.mounts]]
source = 'layouts/sv'
target = 'layouts'
lang = 'sv'
-- layouts/en/_default/single.html --
layouts/en/_default/single.html
-- layouts/nn/_default/single.html --
layouts/nn/_default/single.html
-- layouts/sv/_default/single.html --
layouts/sv/_default/single.html
-- content/p1.md --
---
title: "P1"
---
-- content/p1.nn.md --
---
title: "P1 NN"
---
-- content/p1.sv.md --
---
title: "P1 SV"
---
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/en/p1/index.html", "layouts/en/_default/single.html")
b.AssertFileContent("public/nn/p1/index.html", "layouts/nn/_default/single.html")
b.AssertFileContent("public/sv/p1/index.html", "layouts/sv/_default/single.html")
}
func TestLegacyPartialIssue13599(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/partials/mypartial.html --
Mypartial.
-- layouts/index.html --
mypartial: {{ template "partials/mypartial.html" . }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "Mypartial.")
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/category_string.go | tpl/tplimpl/category_string.go | // Code generated by "stringer -type Category"; DO NOT EDIT.
package tplimpl
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[CategoryLayout-1]
_ = x[CategoryBaseof-2]
_ = x[CategoryMarkup-3]
_ = x[CategoryShortcode-4]
_ = x[CategoryPartial-5]
_ = x[CategoryServer-6]
_ = x[CategoryHugo-7]
}
const _Category_name = "CategoryLayoutCategoryBaseofCategoryMarkupCategoryShortcodeCategoryPartialCategoryServerCategoryHugo"
var _Category_index = [...]uint8{0, 14, 28, 42, 59, 74, 88, 100}
func (i Category) String() string {
i -= 1
if i < 0 || i >= Category(len(_Category_index)-1) {
return "Category(" + strconv.FormatInt(int64(i+1), 10) + ")"
}
return _Category_name[_Category_index[i]:_Category_index[i+1]]
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/template_info.go | tpl/tplimpl/template_info.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 tplimpl
// Increments on breaking changes.
const TemplateVersion = 2
// ParseInfo holds information about a parsed ntemplate.
type ParseInfo struct {
// Set for shortcode templates with any {{ .Inner }}
IsInner bool
// Set for partial templates with any {{ inner }} or {{ templates.Inner }}
HasPartialInner bool
// Set for partials with a return statement.
HasReturn bool
// Config extracted from template.
Config ParseConfig
}
func (info ParseInfo) IsZero() bool {
return info.Config.Version == 0
}
// ParseConfig holds configuration extracted from the template.
type ParseConfig struct {
Version int
}
var defaultParseConfig = ParseConfig{
Version: TemplateVersion,
}
var defaultParseInfo = ParseInfo{
Config: defaultParseConfig,
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/template_funcs_test.go | tpl/tplimpl/template_funcs_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 tplimpl_test
import (
"fmt"
"runtime"
"strings"
"testing"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/tpl/internal"
)
func TestTemplateFuncsExamples(t *testing.T) {
if runtime.GOARCH == "s390x" {
t.Skip("Skip on s390x, see https://github.com/gohugoio/hugo/issues/13204")
}
t.Parallel()
files := `
-- hugo.toml --
disableKinds=["home", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
ignoreErrors = ["my-err-id"]
[outputs]
home=["HTML"]
-- layouts/_partials/header.html --
<title>Hugo Rocks!</title>
-- files/README.txt --
Hugo Rocks!
-- content/blog/hugo-rocks.md --
---
title: "**BatMan**"
---
`
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
NeedsOsFS: true,
},
).Build()
d := b.H.Sites[0].Deps
var (
templates []string
expected []string
)
for _, nsf := range internal.TemplateFuncsNamespaceRegistry {
ns := nsf(d)
for _, mm := range ns.MethodMappings {
for _, example := range mm.Examples {
// These will fail the build, so skip.
if strings.Contains(example[0], "errorf") ||
strings.Contains(example[0], "transform.XMLEscape") ||
strings.Contains(example[0], "math.Rand") {
continue
}
templates = append(templates, example[0])
expected = append(expected, example[1])
}
}
}
files += fmt.Sprintf("-- layouts/single.html --\n%s\n", strings.Join(templates, "\n"))
b = hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
NeedsOsFS: true,
},
).Build()
b.AssertFileContent("public/blog/hugo-rocks/index.html", expected...)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/shortcodes_integration_test.go | tpl/tplimpl/shortcodes_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 tplimpl_test
import (
"strings"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/htesting/hqt"
"github.com/gohugoio/hugo/hugolib"
)
func TestCommentShortcode(t *testing.T) {
// This cannot be parallel as it depends on output from the global logger.
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- layouts/home.html --
{{ .Content }}
-- content/_index.md --
---
title: home
---
a{{< comment >}}b{{< /comment >}}c
`
b := hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertFileContent("public/index.html", "<p>ac</p>")
b.AssertLogContains(`WARN The "comment" shortcode was deprecated in v0.143.0 and will be removed in a future release. Please use HTML comments instead.`)
}
func TestDetailsShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- layouts/home.html --
{{ .Content }}
-- content/_index.md --
---
title: home
---
{{< details >}}
A: An _emphasized_ word.
{{< /details >}}
{{< details
class="my-class"
name="my-name"
open=true
summary="A **bold** word"
title="my-title"
>}}
B: An _emphasized_ word.
{{< /details >}}
{{< details open=false >}}
C: An _emphasized_ word.
{{< /details >}}
{{< details open="false" >}}
D: An _emphasized_ word.
{{< /details >}}
{{< details open=0 >}}
E: An _emphasized_ word.
{{< /details >}}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html",
"<details>\n <summary>Details</summary>\n <p>A: An <em>emphasized</em> word.</p>\n</details>",
"<details class=\"my-class\" name=\"my-name\" open title=\"my-title\">\n <summary>A <strong>bold</strong> word</summary>\n <p>B: An <em>emphasized</em> word.</p>\n</details>",
"<details>\n <summary>Details</summary>\n <p>C: An <em>emphasized</em> word.</p>\n</details>",
"<details>\n <summary>Details</summary>\n <p>D: An <em>emphasized</em> word.</p>\n</details>",
"<details>\n <summary>Details</summary>\n <p>D: An <em>emphasized</em> word.</p>\n</details>",
)
}
func TestFigureShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- content/_index.md --
---
title: home
---
{{< figure
src="a.jpg"
alt="alternate text"
width=600
height=400
loading="lazy"
class="my-class"
link="https://example.org"
target="_blank"
rel="noopener"
title="my-title"
caption="a **bold** word"
attr="an _emphasized_ word"
attrlink="https://example.org/foo"
>}}
-- layouts/home.html --
Hash: {{ .Content | hash.XxHash }}
Content: {{ .Content }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "35b077dcb9887a84")
}
func TestGistShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- layouts/home.html --
{{ .Content }}
-- content/_index.md --
---
title: home
---
{{< gist jmooring 23932424365401ffa5e9d9810102a477 >}}
`
b := hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertFileContent("public/index.html", `<script src="https://gist.github.com/jmooring/23932424365401ffa5e9d9810102a477.js"></script>`)
b.AssertLogContains(`WARN The "gist" shortcode was deprecated in v0.143.0 and will be removed in a future release. See https://gohugo.io/shortcodes/gist for instructions to create a replacement.`)
}
func TestHighlightShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','rss','section','sitemap','taxonomy','term']
-- layouts/single.html --
Hash: {{ .Content | hash.XxHash }}
Content: {{ .Content }}
-- content/p1.md --
---
title: p1
---
{{< highlight go >}}
func main() {
for i := 0; i < 3; i++ {
fmt.Println("Value of i:", i)
}
}
{{< /highlight >}}
-- content/p2.md --
---
title: p2
---
{{< highlight go "noClasses=false" >}}
func main() {
for i := 0; i < 3; i++ {
fmt.Println("Value of i:", i)
}
}
{{< /highlight >}}
-- content/p3.md --
---
title: p3
---
{{< highlight go "lineNos=inline" >}}
func main() {
for i := 0; i < 3; i++ {
fmt.Println("Value of i:", i)
}
}
{{< /highlight >}}
-- content/p4.md --
---
title: p4
---
{{< highlight go "lineNos=table" >}}
func main() {
for i := 0; i < 3; i++ {
fmt.Println("Value of i:", i)
}
}
{{< /highlight >}}
-- content/p5.md --
---
title: p5
---
{{< highlight go "anchorLineNos=true, hl_Lines=2-4, lineAnchors=foo, lineNoStart=42, lineNos=true, lineNumbersInTable=false, style=emacs, wrapperClass=my-class" >}}
func main() {
for i := 0; i < 3; i++ {
fmt.Println("Value of i:", i)
}
}
{{< /highlight >}}
-- content/p6.md --
---
title: p6
---
{{< highlight go "anchorlinenos=true, hl_lines=2-4, lineanchors=foo, linenostart=42, linenos=true, linenumbersintable=false, style=emacs, wrapperclass=my-class" >}}
func main() {
for i := 0; i < 3; i++ {
fmt.Println("Value of i:", i)
}
}
{{< /highlight >}}
-- content/p7.md --
---
title: p7
---
An inline {{< highlight go "hl_inline=true" >}}fmt.Println("Value of i:", i)Hello world!{{< /highlight >}} statement.
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "576ee13be18ddba2")
b.AssertFileContent("public/p2/index.html", "3f97c98e654f23a2")
b.AssertFileContent("public/p3/index.html", "7634b47df1859f58")
b.AssertFileContent("public/p4/index.html", "385a15e400df4e39")
b.AssertFileContent("public/p5/index.html", "f26685017f358cd8")
b.AssertFileContent("public/p6/index.html", "f26685017f358cd8")
b.AssertFileContent("public/p7/index.html", "f12eeaa4d6d9c7ac")
}
func TestInstagramShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
privacy.instagram.simple = false
-- content/_index.md --
---
title: home
---
{{< instagram CxOWiQNP2MO >}}
-- layouts/home.html --
Hash: {{ .Content | hash.XxHash }}
Content: {{ .Content }}
`
// Regular mode
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "6e93404b93277876")
// Simple mode
files = strings.ReplaceAll(files, "privacy.instagram.simple = false", "privacy.instagram.simple = true")
b = hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "2c1dce3881be0513")
}
func TestParamShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
[params]
b = 2
-- layouts/home.html --
{{ .Content }}
-- content/_index.md --
---
title: home
params:
a: 1
---
A: {{% param "a" %}}
B: {{% param "b" %}}
`
b := hugolib.Test(t, files)
b.AssertFileExists("public/index.html", true)
b.AssertFileContent("public/index.html",
"A: 1",
"B: 2",
)
}
func TestQRShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- layouts/home.html --
{{ .Content }}
-- content/_index.md --
---
title: home
---
{{< qr
text="https://gohugo.io"
level="high"
scale=4
targetDir="codes"
alt="QR code linking to https://gohugo.io"
class="my-class"
id="my-id"
title="My Title"
/>}}
{{< qr >}}
https://gohugo.io"
{{< /qr >}}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html",
`<img src="/codes/qr_be5d263c2671bcbd.png" width="148" height="148" alt="QR code linking to https://gohugo.io" class="my-class" id="my-id" title="My Title">`,
`<img src="/qr_472aab57ec7a6e3d.png" width="132" height="132">`,
)
}
func TestRefShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = 'https://example.org/'
disableKinds = ['rss','section','sitemap','taxonomy','term']
defaultContentLanguageInSubdir = true
[markup.goldmark.extensions]
linkify = false
[languages.en]
weight = 1
[languages.de]
weight = 2
[outputs]
page = ['html','json']
-- layouts/home.html --
{{ .Content }}
-- layouts/single.html.html --
{{ .Title }}
-- layouts/single.json.json --
{{ .Title }}
-- content/_index.en.md --
---
title: home
---
A: {{% ref "/s1/p1.md" %}}
B: {{% ref path="/s1/p1.md" %}}
C: {{% ref path="/s1/p1.md" lang="en" %}}
D: {{% ref path="/s1/p1.md" lang="de" %}}
E: {{% ref path="/s1/p1.md" lang="en" outputFormat="html" %}}
F: {{% ref path="/s1/p1.md" lang="de" outputFormat="html" %}}
G: {{% ref path="/s1/p1.md" lang="en" outputFormat="json" %}}
H: {{% ref path="/s1/p1.md" lang="de" outputFormat="json" %}}
-- content/s1/p1.en.md --
---
title: p1 (en)
---
-- content/s1/p1.de.md --
---
title: p1 (de)
---
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/en/index.html",
`p>A: https://example.org/en/s1/p1/</p>`,
`p>B: https://example.org/en/s1/p1/</p>`,
`p>C: https://example.org/en/s1/p1/</p>`,
`p>D: https://example.org/de/s1/p1/</p>`,
`p>E: https://example.org/en/s1/p1/</p>`,
`p>F: https://example.org/de/s1/p1/</p>`,
`p>G: https://example.org/en/s1/p1/index.json</p>`,
`p>H: https://example.org/de/s1/p1/index.json</p>`,
)
}
func TestRelRefShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = 'https://example.org/'
disableKinds = ['rss','section','sitemap','taxonomy','term']
defaultContentLanguageInSubdir = true
[markup.goldmark.extensions]
linkify = false
[languages.en]
weight = 1
[languages.de]
weight = 2
[outputs]
page = ['html','json']
-- layouts/home.html --
{{ .Content }}
-- layouts/single.html.html --
{{ .Title }}
-- layouts/single.json.json --
{{ .Title }}
-- content/_index.en.md --
---
title: home
---
A: {{% relref "/s1/p1.md" %}}
B: {{% relref path="/s1/p1.md" %}}
C: {{% relref path="/s1/p1.md" lang="en" %}}
D: {{% relref path="/s1/p1.md" lang="de" %}}
E: {{% relref path="/s1/p1.md" lang="en" outputFormat="html" %}}
F: {{% relref path="/s1/p1.md" lang="de" outputFormat="html" %}}
G: {{% relref path="/s1/p1.md" lang="en" outputFormat="json" %}}
H: {{% relref path="/s1/p1.md" lang="de" outputFormat="json" %}}
-- content/s1/p1.en.md --
---
title: p1 (en)
---
-- content/s1/p1.de.md --
---
title: p1 (de)
---
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/en/index.html",
`p>A: /en/s1/p1/</p>`,
`p>B: /en/s1/p1/</p>`,
`p>C: /en/s1/p1/</p>`,
`p>D: /de/s1/p1/</p>`,
`p>E: /en/s1/p1/</p>`,
`p>F: /de/s1/p1/</p>`,
`p>G: /en/s1/p1/index.json</p>`,
`p>H: /de/s1/p1/index.json</p>`,
)
}
func TestVimeoShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','rss','section','sitemap','taxonomy','term']
privacy.vimeo.simple = false
-- content/p1.md --
---
title: p1
---
{{< vimeo 55073825 >}}
-- content/p2.md --
---
title: p2
---
{{< vimeo id=55073825 allowFullScreen=true >}}
-- content/p3.md --
---
title: p3
---
{{< vimeo id=55073825 allowFullScreen=false >}}
-- layouts/single.html --
Hash: {{ .Content | hash.XxHash }}
Content: {{ .Content }}
`
// Regular mode
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "82566e6b8d04b53e")
b.AssertFileContent("public/p2/index.html", "82566e6b8d04b53e")
b.AssertFileContent("public/p3/index.html", "2b5f9cc3167d1336")
// Simple mode
files = strings.ReplaceAll(files, "privacy.vimeo.simple = false", "privacy.vimeo.simple = true")
b = hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "04d861fc957ee638")
// Simple mode with non-existent id
files = strings.ReplaceAll(files, "{{< vimeo 55073825 >}}", "{{< vimeo __id_does_not_exist__ >}}")
b = hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertLogContains(`WARN The "vimeo" shortcode was unable to retrieve the remote data.`)
}
// Issue 13214
// We deprecated the twitter, tweet (alias of twitter), and twitter_simple
// shortcodes in v0.141.0, replacing them with x and x_simple.
func TestXShortcodes(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','rss','section','sitemap','taxonomy','term']
#CONFIG
-- content/p1.md --
---
title: p1
---
{{< x user="SanDiegoZoo" id="1453110110599868418" >}}
-- content/p2.md --
---
title: p2
---
{{< twitter user="SanDiegoZoo" id="1453110110599868418" >}}
-- content/p3.md --
---
title: p3
---
{{< tweet user="SanDiegoZoo" id="1453110110599868418" >}}
-- content/p4.md --
---
title: p4
---
{{< x_simple user="SanDiegoZoo" id="1453110110599868418" >}}
-- content/p5.md --
---
title: p5
---
{{< twitter_simple user="SanDiegoZoo" id="1453110110599868418" >}}
-- layouts/single.html --
{{ .Content | strings.TrimSpace | safeHTML }}
--
`
b := hugolib.Test(t, files)
// Test x, twitter, and tweet shortcodes
want := `<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Owl bet you'll lose this staring contest 🦉 <a href="https://t.co/eJh4f2zncC">pic.twitter.com/eJh4f2zncC</a></p>— San Diego Zoo Wildlife Alliance (@sandiegozoo) <a href="https://twitter.com/sandiegozoo/status/1453110110599868418?ref_src=twsrc%5Etfw">October 26, 2021</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>`
b.AssertFileContent("public/p1/index.html", want)
htmlFiles := []string{
b.FileContent("public/p1/index.html"),
b.FileContent("public/p2/index.html"),
b.FileContent("public/p3/index.html"),
}
b.Assert(htmlFiles, hqt.IsAllElementsEqual)
// Test x_simple and twitter_simple shortcodes
wantSimple := "<style type=\"text/css\">\n .twitter-tweet {\n font:\n 14px/1.45 -apple-system,\n BlinkMacSystemFont,\n \"Segoe UI\",\n Roboto,\n Oxygen-Sans,\n Ubuntu,\n Cantarell,\n \"Helvetica Neue\",\n sans-serif;\n border-left: 4px solid #2b7bb9;\n padding-left: 1.5em;\n color: #555;\n }\n .twitter-tweet a {\n color: #2b7bb9;\n text-decoration: none;\n }\n blockquote.twitter-tweet a:hover,\n blockquote.twitter-tweet a:focus {\n text-decoration: underline;\n }\n </style><blockquote class=\"twitter-tweet\"><p lang=\"en\" dir=\"ltr\">Owl bet you'll lose this staring contest 🦉 <a href=\"https://t.co/eJh4f2zncC\">pic.twitter.com/eJh4f2zncC</a></p>— San Diego Zoo Wildlife Alliance (@sandiegozoo) <a href=\"https://twitter.com/sandiegozoo/status/1453110110599868418?ref_src=twsrc%5Etfw\">October 26, 2021</a></blockquote>\n--"
b.AssertFileContent("public/p4/index.html", wantSimple)
htmlFiles = []string{
b.FileContent("public/p4/index.html"),
b.FileContent("public/p5/index.html"),
}
b.Assert(htmlFiles, hqt.IsAllElementsEqual)
filesOriginal := files
// Test privacy.twitter.simple
files = strings.ReplaceAll(filesOriginal, "#CONFIG", "privacy.twitter.simple=true")
b = hugolib.Test(t, files)
htmlFiles = []string{
b.FileContent("public/p2/index.html"),
b.FileContent("public/p3/index.html"),
b.FileContent("public/p5/index.html"),
}
b.Assert(htmlFiles, hqt.IsAllElementsEqual)
// Test privacy.x.simple
files = strings.ReplaceAll(filesOriginal, "#CONFIG", "privacy.x.simple=true")
b = hugolib.Test(t, files)
htmlFiles = []string{
b.FileContent("public/p1/index.html"),
b.FileContent("public/p4/index.html"),
b.FileContent("public/p4/index.html"),
}
b.Assert(htmlFiles, hqt.IsAllElementsEqual)
htmlFiles = []string{
b.FileContent("public/p2/index.html"),
b.FileContent("public/p3/index.html"),
}
b.Assert(htmlFiles, hqt.IsAllElementsEqual)
// Test privacy.twitter.disable
files = strings.ReplaceAll(filesOriginal, "#CONFIG", "privacy.twitter.disable = true")
b = hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "")
htmlFiles = []string{
b.FileContent("public/p1/index.html"),
b.FileContent("public/p2/index.html"),
b.FileContent("public/p3/index.html"),
b.FileContent("public/p4/index.html"),
b.FileContent("public/p4/index.html"),
}
b.Assert(htmlFiles, hqt.IsAllElementsEqual)
// Test privacy.x.disable
files = strings.ReplaceAll(filesOriginal, "#CONFIG", "privacy.x.disable = true")
b = hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "")
htmlFiles = []string{
b.FileContent("public/p1/index.html"),
b.FileContent("public/p4/index.html"),
}
b.Assert(htmlFiles, hqt.IsAllElementsEqual)
htmlFiles = []string{
b.FileContent("public/p2/index.html"),
b.FileContent("public/p3/index.html"),
}
b.Assert(htmlFiles, hqt.IsAllElementsEqual)
// Test warnings
files = `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- content/_index.md --
---
title: home
---
{{< x user="__user_does_not_exist__" id="__id_does_not_exist__" >}}
{{< x_simple user="__user_does_not_exist__" id="__id_does_not_exist__" >}}
{{< twitter user="__user_does_not_exist__" id="__id_does_not_exist__" >}}
{{< twitter_simple user="__user_does_not_exist__" id="__id_does_not_exist__" >}}
-- layouts/home.html --
{{ .Content }}
`
b = hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertLogContains(
`WARN The "x" shortcode was unable to retrieve the remote data.`,
`WARN The "x_simple" shortcode was unable to retrieve the remote data.`,
`WARN The "twitter", "tweet", and "twitter_simple" shortcodes were deprecated in v0.142.0 and will be removed in a future release.`,
`WARN The "twitter" shortcode was unable to retrieve the remote data.`,
`WARN The "twitter_simple" shortcode was unable to retrieve the remote data.`,
)
}
func TestYouTubeShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','rss','section','sitemap','taxonomy','term']
privacy.youtube.privacyEnhanced = false
-- layouts/single.html --
Hash: {{ .Content | hash.XxHash }}
Content: {{ .Content }}
-- content/p1.md --
---
title: p1
---
{{< youtube 0RKpf3rK57I >}}
-- content/p2.md --
---
title: p2
---
{{< youtube
id="0RKpf3rK57I"
allowFullScreen=false
autoplay=true
class="my-class"
controls="false"
end=42
loading="lazy"
loop=true
mute=true
start=6
title="my title"
>}}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "4b54bf9bd03946ec")
b.AssertFileContent("public/p2/index.html", "289c655e727e596c")
files = strings.ReplaceAll(files, "privacy.youtube.privacyEnhanced = false", "privacy.youtube.privacyEnhanced = true")
b = hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "78eb19b5c6f3768f")
b.AssertFileContent("public/p2/index.html", "a6db910a9cf54bc1")
}
func TestShortcodePlainTextVsHTMLTemplateIssue13698(t *testing.T) {
t.Parallel()
filesTemplate := `
-- hugo.toml --
markup.goldmark.renderer.unsafe = true
-- layouts/all.html --
Content: {{ .Content }}|
-- layouts/_shortcodes/mymarkdown.md --
<div>Foo bar</div>
-- content/p1.md --
---
title: p1
---
## A shortcode
SHORTCODE
`
files := strings.ReplaceAll(filesTemplate, "SHORTCODE", "{{% mymarkdown %}}")
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "<div>Foo bar</div>")
files = strings.ReplaceAll(filesTemplate, "SHORTCODE", "{{< mymarkdown >}}")
var err error
b, err = hugolib.TestE(t, files)
b.Assert(err, qt.IsNotNil)
b.Assert(err.Error(), qt.Contains, `no compatible template found for shortcode "mymarkdown" in [/_shortcodes/mymarkdown.md]; note that to use plain text template shortcodes in HTML you need to use the shortcode {{% delimiter`)
}
func TestShortcodeOnlyLanguageInBaseIssue13699And13740(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = 'https://example.org/'
disableLanguages = ['de']
[languages]
[languages.en]
weight = 1
[languages.de]
weight = 2
-- layouts/_shortcodes/de.html --
de.html
-- layouts/all.html --
{{ .Content }}
-- content/_index.md --
---
title: home
---
{{< de >}}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "de.html")
}
func TestShortcodeLanguage13767(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
defaultContentLanguage = 'pl'
defaultContentLanguageInSubdir = true
[languages.pl]
weight = 1
[languages.en]
weight = 2
-- content/_index.md --
---
title: dom
---
{{< myshortcode >}}
-- content/_index.en.md --
---
title: home
---
{{< myshortcode >}}
-- layouts/_shortcodes/myshortcode.html --
myshortcode.html
-- layouts/_shortcodes/myshortcode.en.html --
myshortcode.en.html
-- layouts/all.html --
{{ .Content }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/pl/index.html", "myshortcode.html")
b.AssertFileContent("public/en/index.html", "myshortcode.en.html")
}
func TestHasShortcodeSamePageSourceDifferentShortcodes(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','rss','section','sitemap','taxonomy','term', '404']
defaultContentLanguage = 'en'
defaultContentLanguageInSubdir = true
markup.goldmark.renderer.unsafe = true
[languages]
[languages.en]
weight = 1
[languages.sv]
weight = 2
-- content/inc/i1.md --
---
headless: true
sites:
matrix:
languages:
- '**'
---
{{% sc1 %}}
-- content/inc/i2.md --
---
headless: true
sites:
matrix:
languages:
- '**'
---
{{% sc2 %}}
-- content/p1.md --
---
title: p1
---
P1.
{{% inc %}}
-- content/p1.sv.md --
---
title: p1 sv
---
P1.
{{% inc %}}
-- layouts/_shortcodes/sc1.html --
sc1
-- layouts/_shortcodes/sc2.html --
sc2
-- layouts/_shortcodes/inc.html --
{{ with site.GetPage "inc/i1.md" }}i1.RenderShortcodes: {{ .RenderShortcodes }}{{ end }}
-- layouts/_shortcodes/inc.sv.html --
{{ with site.GetPage "inc/i2.md" }}i1.RenderShortcodes: {{ .RenderShortcodes }}{{ end }}
-- layouts/all.html --
Content: {{ .Content }}|sc1: {{ .HasShortcode "sc1" }}|sc2: {{ .HasShortcode "sc2" }}|inc: {{ .HasShortcode "inc" }}|
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/en/p1/index.html", " |sc1: true|sc2: false|inc: true|")
b.AssertFileContent("public/sv/p1/index.html", " |sc1: false|sc2: true|inc: true|")
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/render_hook_integration_test.go | tpl/tplimpl/render_hook_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 tplimpl_test
import (
"strings"
"testing"
"github.com/gohugoio/hugo/hugolib"
)
func TestEmbeddedLinkRenderHook(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['rss','sitemap','taxonomy','term']
[markup.goldmark.renderHooks.link]
enableDefault = true
-- layouts/list.html --
{{ .Content }}
-- layouts/single.html --
{{ .Content }}
-- assets/a.txt --
irrelevant
-- content/_index.md --
---
title: home
---
-- content/s1/_index.md --
---
title: s1
---
-- content/s1/p1.md --
---
title: s1/p1
---
-- content/s1/p2/index.md --
---
title: s1/p2
---
[500](a.txt) // global resource
[510](b.txt) // page resource
[520](./b.txt) // page resource
-- content/s1/p2/b.txt --
irrelevant
-- content/s1/p3.md --
---
title: s1/p3
---
// Remote
[10](https://a.org)
// fragment
[100](/#foo)
[110](#foo)
[120](p1#foo)
[130](p1/#foo)
// section page
[200](s1)
[210](/s1)
[220](../s1)
[230](s1/)
[240](/s1/)
[250](../s1/)
// regular page
[300](p1)
[310](/s1/p1)
[320](../s1/p1)
[330](p1/)
[340](/s1/p1/)
[350](../s1/p1/)
// leaf bundle
[400](p2)
[410](/s1/p2)
[420](../s1/p2)
[430](p2/)
[440](/s1/p2/)
[450](../s1/p2/)
// empty
[]()
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/s1/p3/index.html",
`<a href="https://a.org">10</a>`,
`<a href="/#foo">100</a>`,
`<a href="/s1/p3/#foo">110</a>`,
`<a href="/s1/p1/#foo">120</a>`,
`<a href="/s1/p1/#foo">130</a>`,
`<a href="/s1/">200</a>`,
`<a href="/s1/">210</a>`,
`<a href="/s1/">220</a>`,
`<a href="/s1/">230</a>`,
`<a href="/s1/">240</a>`,
`<a href="/s1/">250</a>`,
`<a href="/s1/p1/">300</a>`,
`<a href="/s1/p1/">310</a>`,
`<a href="/s1/p1/">320</a>`,
`<a href="/s1/p1/">330</a>`,
`<a href="/s1/p1/">340</a>`,
`<a href="/s1/p1/">350</a>`,
`<a href="/s1/p2/">400</a>`,
`<a href="/s1/p2/">410</a>`,
`<a href="/s1/p2/">420</a>`,
`<a href="/s1/p2/">430</a>`,
`<a href="/s1/p2/">440</a>`,
`<a href="/s1/p2/">450</a>`,
`<a href=""></a>`,
)
b.AssertFileContent("public/s1/p2/index.html",
`<a href="/a.txt">500</a>`,
`<a href="/s1/p2/b.txt">510</a>`,
`<a href="/s1/p2/b.txt">520</a>`,
)
}
// Issue 12203
// Issue 12468
// Issue 12514
func TestEmbeddedImageRenderHook(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = 'https://example.org/dir/'
disableKinds = ['home','rss','section','sitemap','taxonomy','term']
[markup.goldmark.extensions.typographer]
disable = true
[markup.goldmark.parser]
wrapStandAloneImageWithinParagraph = false
[markup.goldmark.parser.attribute]
block = false
[markup.goldmark.renderHooks.image]
enableDefault = true
-- content/p1/index.md --
![]()



{.foo #bar}

{id="\"><script>alert()</script>"}
-- content/p1/pixel.png --
iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==
-- layouts/single.html --
{{ .Content }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html",
`<img src="" alt="">`,
`<img src="/dir/p1/pixel.png" alt="alt1">`,
`<img src="/dir/p1/pixel.png" alt="alt2-&<>'" title="&<>'">`,
`<img src="/dir/p1/pixel.png?a=b&c=d#fragment" alt="alt3">`,
`<img src="/dir/p1/pixel.png" alt="alt4">`,
)
files = strings.Replace(files, "block = false", "block = true", -1)
b = hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html",
`<img src="" alt="">`,
`<img src="/dir/p1/pixel.png" alt="alt1">`,
`<img src="/dir/p1/pixel.png" alt="alt2-&<>'" title="&<>'">`,
`<img src="/dir/p1/pixel.png?a=b&c=d#fragment" alt="alt3" class="foo" id="bar">`,
`<img src="/dir/p1/pixel.png" alt="alt4" id=""><script>alert()</script>">`,
)
}
// Issue 13535
func TestEmbeddedLinkAndImageRenderHookConfig(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','rss','section','sitemap','taxonomy','term']
[markup.goldmark]
duplicateResourceFiles = false
[markup.goldmark.renderHooks.image]
#KEY_VALUE
[markup.goldmark.renderHooks.link]
#KEY_VALUE
#LANGUAGES
-- content/s1/p1/index.md --
---
title: p1
---
[p2](p2)
[a](a.txt)

-- content/s1/p1/a.txt --
-- content/s1/p1/b.jpg --
-- content/s1/p2.md --
---
title: p2
---
-- layouts/all.html --
{{ .Content }}
`
const customHooks string = `
-- layouts/s1/_markup/render-link.html --
custom link render hook: {{ .Text }}|{{ .Destination }}
-- layouts/s1/_markup/render-image.html --
custom image render hook: {{ .Text }}|{{ .Destination }}
`
const languages string = `
[languages.en]
[languages.fr]
`
const (
fileToCheck = "public/s1/p1/index.html"
wantCustom string = "<p>custom link render hook: p2|p2</p>\n<p>custom link render hook: a|a.txt</p>\n<p>custom image render hook: b|b.jpg</p>"
wantEmbedded string = "<p><a href=\"/s1/p2/\">p2</a></p>\n<p><a href=\"/s1/p1/a.txt\">a</a></p>\n<p><img src=\"/s1/p1/b.jpg\" alt=\"b\"></p>"
wantGoldmark string = "<p><a href=\"p2\">p2</a></p>\n<p><a href=\"a.txt\">a</a></p>\n<p><img src=\"b.jpg\" alt=\"b\"></p>"
)
tests := []struct {
id string // the test id
isMultilingual bool // whether the site is multilingual single-host
hasCustomHooks bool // whether the site has custom link and image render hooks
keyValuePair string // the enableDefault (deprecated in v0.148.0) or useEmbedded key-value pair
want string // the expected content of public/s1/p1/index.html
}{
{"01", false, false, "", wantGoldmark}, // monolingual
{"02", false, false, "enableDefault = false", wantGoldmark}, // monolingual, enableDefault = false
{"03", false, false, "enableDefault = true", wantEmbedded}, // monolingual, enableDefault = true
{"04", false, false, "useEmbedded = 'always'", wantEmbedded}, // monolingual, useEmbedded = 'always'
{"05", false, false, "useEmbedded = 'auto'", wantGoldmark}, // monolingual, useEmbedded = 'auto'
{"06", false, false, "useEmbedded = 'fallback'", wantEmbedded}, // monolingual, useEmbedded = 'fallback'
{"07", false, false, "useEmbedded = 'never'", wantGoldmark}, // monolingual, useEmbedded = 'never'
{"08", false, true, "", wantCustom}, // monolingual, with custom hooks
{"09", false, true, "enableDefault = false", wantCustom}, // monolingual, with custom hooks, enableDefault = false
{"10", false, true, "enableDefault = true", wantCustom}, // monolingual, with custom hooks, enableDefault = true
{"11", false, true, "useEmbedded = 'always'", wantEmbedded}, // monolingual, with custom hooks, useEmbedded = 'always'
{"12", false, true, "useEmbedded = 'auto'", wantCustom}, // monolingual, with custom hooks, useEmbedded = 'auto'
{"13", false, true, "useEmbedded = 'fallback'", wantCustom}, // monolingual, with custom hooks, useEmbedded = 'fallback'
{"14", false, true, "useEmbedded = 'never'", wantCustom}, // monolingual, with custom hooks, useEmbedded = 'never'
{"15", true, false, "", wantEmbedded}, // multilingual
{"16", true, false, "enableDefault = false", wantGoldmark}, // multilingual, enableDefault = false
{"17", true, false, "enableDefault = true", wantEmbedded}, // multilingual, enableDefault = true
{"18", true, false, "useEmbedded = 'always'", wantEmbedded}, // multilingual, useEmbedded = 'always'
{"19", true, false, "useEmbedded = 'auto'", wantEmbedded}, // multilingual, useEmbedded = 'auto'
{"20", true, false, "useEmbedded = 'fallback'", wantEmbedded}, // multilingual, useEmbedded = 'fallback'
{"21", true, false, "useEmbedded = 'never'", wantGoldmark}, // multilingual, useEmbedded = 'never'
{"22", true, true, "", wantCustom}, // multilingual, with custom hooks
{"23", true, true, "enableDefault = false", wantCustom}, // multilingual, with custom hooks, enableDefault = false
{"24", true, true, "enableDefault = true", wantCustom}, // multilingual, with custom hooks, enableDefault = true
{"25", true, true, "useEmbedded = 'always'", wantEmbedded}, // multilingual, with custom hooks, useEmbedded = 'always'
{"26", true, true, "useEmbedded = 'auto'", wantCustom}, // multilingual, with custom hooks, useEmbedded = 'auto'
{"27", true, true, "useEmbedded = 'fallback'", wantCustom}, // multilingual, with custom hooks, useEmbedded = 'fallback'
{"28", true, true, "useEmbedded = 'never'", wantCustom}, // multilingual, with custom hooks, useEmbedded = 'never'
}
for _, tt := range tests {
t.Run(tt.id, func(t *testing.T) {
t.Parallel()
f := files
if tt.isMultilingual {
f = strings.ReplaceAll(f, "#LANGUAGES", languages)
}
if tt.hasCustomHooks {
f = f + customHooks
}
f = strings.ReplaceAll(f, "#KEY_VALUE", tt.keyValuePair)
b := hugolib.Test(t, f)
b.AssertFileContent(fileToCheck, tt.want)
})
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/templatedescriptor.go | tpl/tplimpl/templatedescriptor.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 tplimpl
import (
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/hugolib/sitesmatrix"
"github.com/gohugoio/hugo/resources/kinds"
)
const baseNameBaseof = "baseof"
// This is used both as a key and in lookups.
type TemplateDescriptor struct {
// Group 1.
Kind string // page, home, section, taxonomy, term (and only those)
LayoutFromTemplate string // list, single, all,mycustomlayout
LayoutFromUser string // custom layout set in front matter, e.g. list, single, all, mycustomlayout
// Group 2.
OutputFormat string // rss, csv ...
MediaType string // text/html, text/plain, ...
SitesHash uint64
Variant1 string // contextual variant, e.g. "link" in render hooks."
Variant2 string // contextual variant, e.g. "id" in render.
// Misc.
LayoutFromUserMustMatch bool // If set, we only look for the exact layout.
IsPlainText bool // Whether this is a plain text template.
AlwaysAllowPlainText bool // Whether to e.g. allow plain text templates to be rendered in HTML.
}
func (d *TemplateDescriptor) normalizeFromFile() {
if d.LayoutFromTemplate == d.OutputFormat {
d.LayoutFromTemplate = ""
}
if d.Kind == kinds.KindTemporary {
d.Kind = ""
}
if d.LayoutFromTemplate == d.Kind {
d.LayoutFromTemplate = ""
}
}
type descriptorHandler struct {
opts StoreOptions
}
// Note that this in this setup is usually a descriptor constructed from a page,
// so we want to find the best match for that page.
func (s descriptorHandler) compareDescriptors(category Category, this, other TemplateDescriptor, sitesMatrixThis, sitesMatrixOther sitesmatrix.VectorProvider) weight {
if this.LayoutFromUserMustMatch && this.LayoutFromUser != other.LayoutFromTemplate {
return weightNoMatch
}
w := this.doCompare(category, other, sitesMatrixThis, sitesMatrixOther)
if w.w1 <= 0 {
if category == CategoryMarkup && (this.Variant1 == other.Variant1) && (this.Variant2 == other.Variant2 || this.Variant2 != "" && other.Variant2 == "") {
// See issue 13242.
if this.OutputFormat != other.OutputFormat && this.OutputFormat == s.opts.DefaultOutputFormat {
return w
}
w.w1 = 1
}
if category == CategoryShortcode {
if (this.IsPlainText == other.IsPlainText || !other.IsPlainText) || this.AlwaysAllowPlainText {
w.w1 = 1
}
}
}
return w
}
//lint:ignore ST1006 this vs other makes it easier to reason about.
func (this TemplateDescriptor) doCompare(category Category, other TemplateDescriptor, sitesMatrixThis, sitesMatrixOther sitesmatrix.VectorProvider) weight {
w := weightNoMatch
if !this.AlwaysAllowPlainText {
// HTML in plain text is OK, but not the other way around.
if other.IsPlainText && !this.IsPlainText {
return w
}
}
if other.Kind != "" && other.Kind != this.Kind {
return w
}
if other.LayoutFromTemplate != "" && other.LayoutFromTemplate != layoutAll {
if this.LayoutFromUser == "" || this.LayoutFromUser != other.LayoutFromTemplate {
if other.LayoutFromTemplate != this.LayoutFromTemplate {
return w
}
}
}
if sitesMatrixOther != nil {
// sitesMatrixThis is usually a single Site.
// But we also use this method to find all base template variants for a given template,
// and in that case we may get multiple vectors (e.g. multiple languages).
if sitesMatrixThis == nil || !sitesMatrixOther.HasAnyVector(sitesMatrixThis) {
return w
}
}
if other.OutputFormat != "" && other.OutputFormat != this.OutputFormat {
if this.MediaType != other.MediaType {
return w
}
// We want e.g. home page in amp output format (media type text/html) to
// find a template even if one isn't specified for that output format,
// when one exist for the html output format (same media type).
skip := category != CategoryBaseof && (this.Kind == "" || (this.Kind != other.Kind && (this.LayoutFromTemplate != other.LayoutFromTemplate && other.LayoutFromTemplate != layoutAll)))
if this.LayoutFromUser != "" {
skip = skip && (this.LayoutFromUser != other.LayoutFromTemplate)
}
if skip {
return w
}
// Continue.
}
if other.MediaType != this.MediaType {
return w
}
// One example of variant1 and 2 is for render codeblocks:
// variant1=codeblock, variant2=go (language).
if other.Variant1 != "" {
if other.Variant1 != this.Variant1 {
return w
}
if other.Variant2 != "" && other.Variant2 != this.Variant2 {
return w
}
}
const (
weightKind = 5 // page, home, section, taxonomy, term (and only those)
weightcustomLayout = 6 // custom layout (mylayout, set in e.g. front matter)
weightLayoutStandard = 4 // standard layouts (single,list)
weightLayoutAll = 2 // the "all" layout
weightOutputFormat = 4 // a configured output format (e.g. rss, html, json)
weightMediaType = 1 // a configured media type (e.g. text/html, text/plain)
weightSitesMatrix = 1 // a configured language (e.g. en, nn, fr, ...)
weightVariant1 = 6 // currently used for render hooks, e.g. "link", "image"
weightVariant2 = 4 // currently used for render hooks, e.g. the language "go" in code blocks.
// We will use the values for group 2 and 3
// if the distance up to the template is shorter than
// the one we're comparing with.
// E.g for a page in /posts/mypage.md with the
// two templates /layouts/posts/single.html and /layouts/page.html,
// the first one is the best match even if the second one
// has a higher w1 value.
weight2Group1 = 1 // kind, standardl layout (single,list,all)
weight2Group2 = 2 // custom layout (mylayout)
weight3 = 1 // for media type, output format, and dimensions (if not provided).
)
// Now we now know that the other descriptor is a subset of this.
// Now calculate the weights.
w.w1++
if other.Kind != "" && other.Kind == this.Kind {
w.w1 += weightKind
w.w2 = weight2Group1
}
if other.LayoutFromTemplate != "" && (other.LayoutFromTemplate == this.LayoutFromTemplate) {
w.w1 += weightLayoutStandard
w.w2 = weight2Group1
} else if other.LayoutFromTemplate == layoutAll {
w.w1 += weightLayoutAll
w.w2 = weight2Group1
}
// LayoutCustom is only set in this (usually from Page.Layout).
if this.LayoutFromUser != "" && this.LayoutFromUser == other.LayoutFromTemplate {
w.w1 += weightcustomLayout
w.w2 = weight2Group2
}
if sitesMatrixOther != nil {
// sitesMatrixThis is usually a single Site.
if sitesMatrixThis != nil && sitesMatrixOther.HasAnyVector(sitesMatrixThis) {
w.w1 += weightSitesMatrix
if wp, ok := sitesMatrixOther.(types.WeightProvider); ok {
w.wsm = wp.Weight()
} else {
w.wsm = weight3
}
}
}
if other.OutputFormat != "" && other.OutputFormat == this.OutputFormat {
w.w1 += weightOutputFormat
w.w3 += weight3
}
if other.MediaType != "" && other.MediaType == this.MediaType {
w.w1 += weightMediaType
w.w3 += weight3
}
if other.Variant1 != "" && other.Variant1 == this.Variant1 {
w.w1 += weightVariant1
}
if other.Variant1 != "" && other.Variant2 == this.Variant2 {
w.w1 += weightVariant2
}
return w
}
func (d TemplateDescriptor) IsZero() bool {
return d == TemplateDescriptor{}
}
//lint:ignore ST1006 this vs other makes it easier to reason about.
func (this TemplateDescriptor) isKindInLayout(layout string) bool {
if this.Kind == "" {
return true
}
if this.Kind != kinds.KindPage {
return layout != layoutSingle
}
return layout != layoutList
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/legacy.go | tpl/tplimpl/legacy.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 tplimpl
import (
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/resources/kinds"
)
type layoutLegacyMapping struct {
sourcePath string
target layoutLegacyMappingTarget
}
type layoutLegacyMappingTarget struct {
targetPath string
targetDesc TemplateDescriptor
targetCategory Category
}
var (
ltermPlural = layoutLegacyMappingTarget{
targetPath: "/PLURAL",
targetDesc: TemplateDescriptor{Kind: kinds.KindTerm},
targetCategory: CategoryLayout,
}
ltermBase = layoutLegacyMappingTarget{
targetPath: "",
targetDesc: TemplateDescriptor{Kind: kinds.KindTerm},
targetCategory: CategoryLayout,
}
ltaxPlural = layoutLegacyMappingTarget{
targetPath: "/PLURAL",
targetDesc: TemplateDescriptor{Kind: kinds.KindTaxonomy},
targetCategory: CategoryLayout,
}
ltaxBase = layoutLegacyMappingTarget{
targetPath: "",
targetDesc: TemplateDescriptor{Kind: kinds.KindTaxonomy},
targetCategory: CategoryLayout,
}
lsectBase = layoutLegacyMappingTarget{
targetPath: "",
targetDesc: TemplateDescriptor{Kind: kinds.KindSection},
targetCategory: CategoryLayout,
}
lsectTheSection = layoutLegacyMappingTarget{
targetPath: "/THESECTION",
targetDesc: TemplateDescriptor{Kind: kinds.KindSection},
targetCategory: CategoryLayout,
}
)
type legacyTargetPathIdentifiers struct {
targetPath string
targetCategory Category
kind string
outputFormat string
ext string
}
type legacyOrdinalMapping struct {
ordinal int
mapping layoutLegacyMappingTarget
}
type legacyOrdinalMappingFi struct {
m legacyOrdinalMapping
fi hugofs.FileMetaInfo
}
var legacyTermMappings = []layoutLegacyMapping{
{sourcePath: "/PLURAL/term", target: ltermPlural},
{sourcePath: "/PLURAL/SINGULAR", target: ltermPlural},
{sourcePath: "/term/term", target: ltermBase},
{sourcePath: "/term/SINGULAR", target: ltermPlural},
{sourcePath: "/term/taxonomy", target: ltermPlural},
{sourcePath: "/term/list", target: ltermBase},
{sourcePath: "/taxonomy/term", target: ltermBase},
{sourcePath: "/taxonomy/SINGULAR", target: ltermPlural},
{sourcePath: "/SINGULAR/term", target: ltermPlural},
{sourcePath: "/SINGULAR/SINGULAR", target: ltermPlural},
{sourcePath: "/_default/SINGULAR", target: ltermPlural},
{sourcePath: "/_default/taxonomy", target: ltermBase},
}
var legacyTaxonomyMappings = []layoutLegacyMapping{
{sourcePath: "/PLURAL/SINGULAR.terms", target: ltaxPlural},
{sourcePath: "/PLURAL/terms", target: ltaxPlural},
{sourcePath: "/PLURAL/taxonomy", target: ltaxPlural},
{sourcePath: "/PLURAL/list", target: ltaxPlural},
{sourcePath: "/SINGULAR/SINGULAR.terms", target: ltaxPlural},
{sourcePath: "/SINGULAR/terms", target: ltaxPlural},
{sourcePath: "/SINGULAR/taxonomy", target: ltaxPlural},
{sourcePath: "/SINGULAR/list", target: ltaxPlural},
{sourcePath: "/taxonomy/SINGULAR.terms", target: ltaxPlural},
{sourcePath: "/taxonomy/terms", target: ltaxBase},
{sourcePath: "/taxonomy/taxonomy", target: ltaxBase},
{sourcePath: "/taxonomy/list", target: ltaxBase},
{sourcePath: "/_default/SINGULAR.terms", target: ltaxBase},
{sourcePath: "/_default/terms", target: ltaxBase},
{sourcePath: "/_default/taxonomy", target: ltaxBase},
}
var legacySectionMappings = []layoutLegacyMapping{
// E.g. /mysection/mysection.html
{sourcePath: "/THESECTION/THESECTION", target: lsectTheSection},
// E.g. /section/mysection.html
{sourcePath: "/SECTIONKIND/THESECTION", target: lsectTheSection},
// E.g. /section/section.html
{sourcePath: "/SECTIONKIND/SECTIONKIND", target: lsectBase},
// E.g. /section/list.html
{sourcePath: "/SECTIONKIND/list", target: lsectBase},
// E.g. /_default/mysection.html
{sourcePath: "/_default/THESECTION", target: lsectTheSection},
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/templatetransform.go | tpl/tplimpl/templatetransform.go | package tplimpl
import (
"errors"
"fmt"
"regexp"
"slices"
"strings"
"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"
texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
"github.com/gohugoio/hugo/common/hashing"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/tpl"
"github.com/mitchellh/mapstructure"
)
type templateTransformContext struct {
visited map[string]bool
templateNotFound map[string]bool
deferNodes map[string]*parse.ListNode
lookupFn func(name string, in *TemplInfo) *TemplInfo
store *TemplateStore
// The last error encountered.
err error
// Set when we're done checking for config header.
configChecked bool
t *TemplInfo
// Store away the return node in partials.
returnNode *parse.CommandNode
}
func (c templateTransformContext) getIfNotVisited(name string) *TemplInfo {
if c.visited[name] {
return nil
}
c.visited[name] = true
templ := c.lookupFn(name, c.t)
if templ == nil {
// This may be a inline template defined outside of this file
// and not yet parsed. Unusual, but it happens.
// Store the name to try again later.
c.templateNotFound[name] = true
}
return templ
}
func newTemplateTransformContext(
t *TemplInfo,
store *TemplateStore,
lookupFn func(name string, in *TemplInfo) *TemplInfo,
) *templateTransformContext {
return &templateTransformContext{
t: t,
lookupFn: lookupFn,
store: store,
visited: make(map[string]bool),
templateNotFound: make(map[string]bool),
deferNodes: make(map[string]*parse.ListNode),
}
}
func applyTemplateTransformers(
t *TemplInfo,
store *TemplateStore,
lookupFn func(name string, in *TemplInfo) *TemplInfo,
) (*templateTransformContext, error) {
if t == nil {
return nil, errors.New("expected template, but none provided")
}
c := newTemplateTransformContext(t, store, lookupFn)
c.t.ParseInfo = defaultParseInfo
tree := getParseTree(t.Template)
if tree == nil {
panic(fmt.Errorf("template %s not parsed", t))
}
if err := c.applyTransformationsAndSetReturnWrapper(tree); err != nil {
return c, fmt.Errorf("failed to transform template %q: %w", t.Name(), err)
}
return c, c.err
}
func getParseTree(templ tpl.Template) *parse.Tree {
if text, ok := templ.(*texttemplate.Template); ok {
return text.Tree
}
return templ.(*htmltemplate.Template).Tree
}
const (
// We parse this template and modify the nodes in order to assign
// the return value of a partial to a contextWrapper via Set. We use
// "range" over a one-element slice so we can shift dot to the
// partial's argument, Arg, while allowing Arg to be falsy.
partialReturnWrapperTempl = `{{ $_hugo_dot := $ }}{{ $ := .Arg }}{{ range (slice .Arg) }}{{ $_hugo_dot.Set ("PLACEHOLDER") }}{{ end }}`
doDeferTempl = `{{ doDefer ("PLACEHOLDER1") ("PLACEHOLDER2") }}`
// _pushPartialDecorator is always falsy.
pushPartialDecoratorTempl = `{{ if or (_pushPartialDecorator ("PLACEHOLDER")) }}{{ end }}`
popPartialDecoratorTempl = `{{ if (_popPartialDecorator ("PLACEHOLDER1")) }}{{ . }}{{ else }}("PLACEHOLDER2"){{ end }}`
)
var (
partialReturnWrapper *parse.ListNode
doDefer *parse.ListNode
popPartialDecorator *parse.ListNode
pushPartialDecorator *parse.ListNode
)
func init() {
templ, err := texttemplate.New("").Parse(partialReturnWrapperTempl)
if err != nil {
panic(err)
}
partialReturnWrapper = templ.Tree.Root
templ, err = texttemplate.New("").Funcs(texttemplate.FuncMap{"doDefer": func(string, string) string { return "" }}).Parse(doDeferTempl)
if err != nil {
panic(err)
}
doDefer = templ.Tree.Root
templ, err = texttemplate.New("").Funcs(texttemplate.FuncMap{"_popPartialDecorator": func(string) string { return "" }}).Parse(popPartialDecoratorTempl)
if err != nil {
panic(err)
}
popPartialDecorator = templ.Tree.Root
templ, err = texttemplate.New("").Funcs(texttemplate.FuncMap{"_pushPartialDecorator": func(string) string { return "" }}).Parse(pushPartialDecoratorTempl)
if err != nil {
panic(err)
}
pushPartialDecorator = templ.Tree.Root
}
// wrapInPartialReturnWrapper copies and modifies the parsed nodes of a
// predefined partial return wrapper to insert those of a user-defined partial.
func (c *templateTransformContext) wrapInPartialReturnWrapper(n *parse.ListNode) *parse.ListNode {
wrapper := partialReturnWrapper.CopyList()
rangeNode := wrapper.Nodes[2].(*parse.RangeNode)
retn := rangeNode.List.Nodes[0]
setCmd := retn.(*parse.ActionNode).Pipe.Cmds[0]
setPipe := setCmd.Args[1].(*parse.PipeNode)
// Replace PLACEHOLDER with the real return value.
// Note that this is a PipeNode, so it will be wrapped in parens.
setPipe.Cmds = []*parse.CommandNode{c.returnNode}
rangeNode.List.Nodes = append(n.Nodes, retn)
return wrapper
}
func (c *templateTransformContext) applyTransformationsAndSetReturnWrapper(tree *parse.Tree) error {
_, err := c.applyTransformations(tree.Root)
if err != nil {
return err
}
if c.returnNode != nil {
// This is a partial with a return statement.
c.t.ParseInfo.HasReturn = true
tree.Root = c.wrapInPartialReturnWrapper(tree.Root)
}
return nil
}
// applyTransformations does 2 things:
// 1) Parses partial return statement.
// 2) Tracks template (partial) dependencies and some other info.
func (c *templateTransformContext) applyTransformations(n parse.Node) (bool, error) {
switch x := n.(type) {
case *parse.ListNode:
if x != nil {
c.applyTransformationsToNodes(x.Nodes...)
}
case *parse.ActionNode:
c.applyTransformationsToNodes(x.Pipe)
case *parse.IfNode:
c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList)
case *parse.WithNode:
c.handleWith(x)
c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList)
case *parse.RangeNode:
c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList)
case *parse.TemplateNode:
subTempl := c.getIfNotVisited(x.Name)
if subTempl != nil {
c.applyTransformationsToNodes(getParseTree(subTempl.Template).Root)
}
case *parse.PipeNode:
c.collectConfig(x)
for i, cmd := range x.Cmds {
keep, _ := c.applyTransformations(cmd)
if !keep {
x.Cmds = slices.Delete(x.Cmds, i, i+1)
}
}
case *parse.CommandNode:
if x == nil {
return true, nil
}
c.collectInnerInShortcode(x)
c.collectInnerInPartial(x)
keep := c.collectReturnNode(x)
for _, elem := range x.Args {
switch an := elem.(type) {
case *parse.PipeNode:
c.applyTransformations(an)
}
}
return keep, c.err
}
return true, c.err
}
func (c *templateTransformContext) isWithPartial(args []parse.Node) bool {
if len(args) == 0 {
return false
}
first := args[0]
if pn, ok := first.(*parse.PipeNode); ok {
if len(pn.Cmds) == 0 || pn.Cmds[0] == nil {
return false
}
return c.isWithPartial(pn.Cmds[0].Args)
}
if id1, ok := first.(*parse.IdentifierNode); ok && (id1.Ident == "partial" || id1.Ident == "partialCached") {
return true
}
if chain, ok := first.(*parse.ChainNode); ok {
if id2, ok := chain.Node.(*parse.IdentifierNode); !ok || (id2.Ident != "partials") {
return false
}
if len(chain.Field) != 1 {
return false
}
if chain.Field[0] != "Include" && chain.Field[0] != "IncludeCached" {
return false
}
return true
}
return false
}
func (c *templateTransformContext) isWithDefer(idArg parse.Node) bool {
id, ok := idArg.(*parse.ChainNode)
if !ok || len(id.Field) != 1 || id.Field[0] != "Defer" {
return false
}
if id2, ok := id.Node.(*parse.IdentifierNode); !ok || id2.Ident != "templates" {
return false
}
return true
}
// PartialDecoratorPrefix is the prefix used for internal partial decorator templates.
const PartialDecoratorPrefix = "_internal/decorator_"
var templatesInnerRe = regexp.MustCompile(`{{\s*(templates\.Inner\b|inner\b)`)
// hasBreakOrContinueOutsideRange returns true if the given list node contains a break or continue statement without being nested in a range.
func (c *templateTransformContext) hasBreakOrContinueOutsideRange(n *parse.ListNode) bool {
if n == nil {
return false
}
for _, node := range n.Nodes {
switch x := node.(type) {
case *parse.ListNode:
if c.hasBreakOrContinueOutsideRange(x) {
return true
}
case *parse.RangeNode:
// skip
case *parse.IfNode:
if c.hasBreakOrContinueOutsideRange(x.List) {
return true
}
if c.hasBreakOrContinueOutsideRange(x.ElseList) {
return true
}
case *parse.WithNode:
if c.hasBreakOrContinueOutsideRange(x.List) {
return true
}
if c.hasBreakOrContinueOutsideRange(x.ElseList) {
return true
}
case *parse.BreakNode, *parse.ContinueNode:
return true
}
}
return false
}
func (c *templateTransformContext) handleWithPartial(withNode *parse.WithNode) {
withNodeInnerString := withNode.List.String()
if templatesInnerRe.MatchString(withNodeInnerString) {
c.err = fmt.Errorf("inner cannot be used inside a with block that wraps a partial decorator")
return
}
// See #14333. That is a very odd construct, but we need to guard against it.
if c.hasBreakOrContinueOutsideRange(withNode.List) {
return
}
innerHash := hashing.XxHashFromStringHexEncoded(c.t.Name() + withNodeInnerString)
internalPartialName := fmt.Sprintf("_partials/%s%s", PartialDecoratorPrefix, innerHash)
if c.lookupFn(internalPartialName, c.t) == nil {
innerCopy := withNode.List.CopyList()
ti, err := c.store.addTransformedTemplateInsert(internalPartialName, SubCategoryInline)
if err != nil {
c.err = fmt.Errorf("failed to create internal partial decorator template %q: %w", internalPartialName, err)
return
}
if ti == nil {
c.err = fmt.Errorf("failed to find internal partial decorator template %q after insertion", internalPartialName)
return
}
cc := newTemplateTransformContext(ti, c.store, c.lookupFn)
tree, err := c.store.addTransformedTemplateSetTree(ti, innerCopy)
if err != nil {
c.err = fmt.Errorf("failed to add internal partial decorator template %q: %w", internalPartialName, err)
return
}
if err := cc.applyTransformationsAndSetReturnWrapper(tree); err != nil {
c.err = fmt.Errorf("failed to transform internal partial decorator template %q: %w", internalPartialName, err)
return
}
}
newInner := popPartialDecorator.CopyList()
ifNode := newInner.Nodes[0].(*parse.IfNode)
placeholderPipe := ifNode.Pipe.Cmds[0].Args[0].(*parse.PipeNode)
// Set PLACEHOLDER1 to the unique ID for this partial decorator.
sn1 := placeholderPipe.Cmds[0].Args[1].(*parse.PipeNode).Cmds[0].Args[0].(*parse.StringNode)
sn1.Text = innerHash
sn1.Quoted = fmt.Sprintf("%q", sn1.Text)
ifNode.ElseList = withNode.List.CopyList()
newPipe := pushPartialDecorator.CopyList()
orNode := newPipe.Nodes[0].(*parse.IfNode)
setContext := orNode.Pipe.Cmds[0].Args[1]
// Replace PLACEHOLDER with the unique ID for this partial decorator.
sn2 := setContext.(*parse.PipeNode).Cmds[0].Args[1].(*parse.PipeNode).Cmds[0].Args[0].(*parse.StringNode)
sn2.Text = innerHash
sn2.Quoted = fmt.Sprintf("%q", sn2.Text)
if pn, ok := withNode.Pipe.Cmds[0].Args[0].(*parse.PipeNode); ok {
withNode.Pipe.Cmds[0].Args = pn.Cmds[0].Args
}
withNode.Pipe.Cmds = append(orNode.Pipe.Cmds, withNode.Pipe.Cmds...)
withNode.List = newInner
}
func (c *templateTransformContext) handleWith(withNode *parse.WithNode) {
if len(withNode.Pipe.Cmds) != 1 {
return
}
if c.isWithPartial(withNode.Pipe.Cmds[0].Args) {
c.handleWithPartial(withNode)
return
}
cmd := withNode.Pipe.Cmds[0]
idArg := cmd.Args[0]
p, ok := idArg.(*parse.PipeNode)
if !ok {
return
}
if len(p.Cmds) != 1 {
return
}
cmd = p.Cmds[0]
if len(cmd.Args) != 2 {
return
}
idArg = cmd.Args[0]
if !c.isWithDefer(idArg) {
return
}
deferArg := cmd.Args[1]
cmd.Args = []parse.Node{idArg}
l := doDefer.CopyList()
n := l.Nodes[0].(*parse.ActionNode)
inner := withNode.List.CopyList()
s := inner.String()
if strings.Contains(s, "resources.PostProcess") {
c.err = errors.New("resources.PostProcess cannot be used in a deferred template")
return
}
innerHash := hashing.XxHashFromStringHexEncoded(s)
deferredID := tpl.HugoDeferredTemplatePrefix + innerHash
c.deferNodes[deferredID] = inner
withNode.List = l
n.Pipe.Cmds[0].Args[1].(*parse.PipeNode).Cmds[0].Args[0].(*parse.StringNode).Text = deferredID
n.Pipe.Cmds[0].Args[2] = deferArg
}
func (c *templateTransformContext) applyTransformationsToNodes(nodes ...parse.Node) {
for _, node := range nodes {
c.applyTransformations(node)
}
}
func (c *templateTransformContext) hasIdent(idents []string, ident string) bool {
return slices.Contains(idents, ident)
}
// collectConfig collects and parses any leading template config variable declaration.
// This will be the first PipeNode in the template, and will be a variable declaration
// on the form:
//
// {{ $_hugo_config:= `{ "version": 1 }` }}
func (c *templateTransformContext) collectConfig(n *parse.PipeNode) {
if c.t.category != CategoryShortcode {
return
}
if c.configChecked {
return
}
c.configChecked = true
if len(n.Decl) != 1 || len(n.Cmds) != 1 {
// This cannot be a config declaration
return
}
v := n.Decl[0]
if len(v.Ident) == 0 || v.Ident[0] != "$_hugo_config" {
return
}
cmd := n.Cmds[0]
if len(cmd.Args) == 0 {
return
}
if s, ok := cmd.Args[0].(*parse.StringNode); ok {
errMsg := "failed to decode $_hugo_config in template: %w"
m, err := maps.ToStringMapE(s.Text)
if err != nil {
c.err = fmt.Errorf(errMsg, err)
return
}
if err := mapstructure.WeakDecode(m, &c.t.ParseInfo.Config); err != nil {
c.err = fmt.Errorf(errMsg, err)
}
}
}
// collectInnerInShortcode determines if the given CommandNode represents a
// shortcode call to its .Inner.
func (c *templateTransformContext) collectInnerInShortcode(n *parse.CommandNode) {
if c.t.category != CategoryShortcode {
return
}
if c.t.ParseInfo.IsInner || len(n.Args) == 0 {
return
}
for _, arg := range n.Args {
var idents []string
switch nt := arg.(type) {
case *parse.FieldNode:
idents = nt.Ident
case *parse.VariableNode:
idents = nt.Ident
}
if c.hasIdent(idents, "Inner") || c.hasIdent(idents, "InnerDeindent") {
c.t.ParseInfo.IsInner = true
break
}
}
}
func (c *templateTransformContext) collectInnerInPartial(n *parse.CommandNode) {
if c.t.category != CategoryPartial {
return
}
if c.t.ParseInfo.HasPartialInner || len(n.Args) == 0 {
return
}
switch v := n.Args[0].(type) {
case *parse.IdentifierNode:
if v.Ident == "inner" {
c.t.ParseInfo.HasPartialInner = true
}
case *parse.ChainNode:
if v.Field[0] == "Inner" {
if id, ok := v.Node.(*parse.IdentifierNode); ok && id.Ident == "templates" {
c.t.ParseInfo.HasPartialInner = true
}
}
}
}
func (c *templateTransformContext) collectReturnNode(n *parse.CommandNode) bool {
if c.t.category != CategoryPartial || c.returnNode != nil {
return true
}
if len(n.Args) < 2 {
return true
}
ident, ok := n.Args[0].(*parse.IdentifierNode)
if !ok || ident.Ident != "return" {
return true
}
c.returnNode = n
// Remove the "return" identifiers
c.returnNode.Args = c.returnNode.Args[1:]
return false
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/subcategory_string.go | tpl/tplimpl/subcategory_string.go | // Code generated by "stringer -type SubCategory"; DO NOT EDIT.
package tplimpl
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[SubCategoryMain-0]
_ = x[SubCategoryEmbedded-1]
_ = x[SubCategoryInline-2]
}
const _SubCategory_name = "SubCategoryMainSubCategoryEmbeddedSubCategoryInline"
var _SubCategory_index = [...]uint8{0, 15, 34, 51}
func (i SubCategory) String() string {
if i < 0 || i >= SubCategory(len(_SubCategory_index)-1) {
return "SubCategory(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _SubCategory_name[_SubCategory_index[i]:_SubCategory_index[i+1]]
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/tplimpl/templatestore_integration_test.go | tpl/tplimpl/templatestore_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 tplimpl_test
import (
"context"
"io"
"strings"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/resources/kinds"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/tpl/tplimpl"
)
var newSetupTestSites = `
-- hugo.toml --
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
[languages]
[languages.en]
title = "Title in English"
weight = 1
[languages.nn]
title = "Tittel på nynorsk"
weight = 2
[languages.fr]
title = "Titre en français"
weight = 3
[outputs]
home = ["html", "rss", "redir"]
[outputFormats]
[outputFormats.redir]
mediatype = "text/plain"
baseName = "_redirects"
isPlainText = true
-- layouts/404.html --
{{ define "main" }}
404.
{{ end }}
-- layouts/home.html --
{{ define "main" }}
Home: {{ .Title }}|{{ .Content }}|
Inline Partial: {{ partial "my-inline-partial.html" . }}
{{ end }}
{{ define "hero" }}
Home hero.
{{ end }}
{{ define "partials/my-inline-partial.html" }}
{{ $value := 32 }}
{{ return $value }}
{{ end }}
-- layouts/index.redir --
Redir.
-- layouts/single.html --
{{ define "main" }}
Single needs base.
{{ end }}
-- layouts/foo/bar/single.html --
{{ define "main" }}
Single sub path.
{{ end }}
-- layouts/_markup/render-codeblock.html --
Render codeblock.
-- layouts/_markup/render-blockquote.html --
Render blockquote.
-- layouts/_markup/render-codeblock-go.html --
Render codeblock go.
-- layouts/_markup/render-link.html --
Link: {{ .Destination | safeURL }}
-- layouts/foo/baseof.html --
Base sub path.{{ block "main" . }}{{ end }}
-- layouts/foo/bar/baseof.page.html --
Base sub path.{{ block "main" . }}{{ end }}
-- layouts/list.html --
{{ define "main" }}
List needs base.
{{ end }}
-- layouts/section.html --
Section.
-- layouts/mysectionlayout.section.fr.amp.html --
Section with layout.
-- layouts/baseof.html --
Base.{{ block "main" . }}{{ end }}
Hero:{{ block "hero" . }}{{ end }}:
{{ with (templates.Defer (dict "key" "global")) }}
Defer Block.
{{ end }}
-- layouts/baseof.fr.html --
Base fr.{{ block "main" . }}{{ end }}
-- layouts/baseof.term.html --
Base term.
-- layouts/baseof.section.fr.amp.html --
Base with identifiers.{{ block "main" . }}{{ end }}
-- layouts/_partials/mypartial.html --
Partial. {{ partial "_inline/my-inline-partial-in-partial-with-no-ext" . }}
{{ define "partials/_inline/my-inline-partial-in-partial-with-no-ext" }}
Partial in partial.
{{ end }}
-- layouts/_partials/returnfoo.html --
{{ $v := "foo" }}
{{ return $v }}
-- layouts/_shortcodes/myshortcode.html --
Shortcode. {{ partial "mypartial.html" . }}|return:{{ partial "returnfoo.html" . }}|
-- content/_index.md --
---
title: Home sweet home!
---
{{< myshortcode >}}
> My blockquote.
Markdown link: [Foo](/foo)
-- content/p1.md --
---
title: "P1"
---
-- content/foo/bar/index.md --
---
title: "Foo Bar"
---
{{< myshortcode >}}
-- content/single-list.md --
---
title: "Single List"
layout: "list"
---
`
func TestLayoutsType(t *testing.T) {
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term"]
-- layouts/list.html --
List.
-- layouts/mysection/single.html --
mysection/single|{{ .Title }}
-- layouts/mytype/single.html --
mytype/single|{{ .Title }}
-- content/mysection/_index.md --
-- content/mysection/mysubsection/_index.md --
-- content/mysection/mysubsection/p1.md --
---
title: "P1"
---
-- content/mysection/mysubsection/p2.md --
---
title: "P2"
type: "mytype"
---
`
b := hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertLogContains("! WARN")
b.AssertFileContent("public/mysection/mysubsection/p1/index.html", "mysection/single|P1")
b.AssertFileContent("public/mysection/mysubsection/p2/index.html", "mytype/single|P2")
}
// New, as in from Hugo v0.146.0.
func TestLayoutsNewSetup(t *testing.T) {
const numIterations = 1
for range numIterations {
b := hugolib.Test(t, newSetupTestSites, hugolib.TestOptWarn())
b.AssertLogContains("! WARN")
b.AssertFileContent("public/en/index.html",
"Base.\nHome: Home sweet home!|",
"|Shortcode.\n|",
"<p>Markdown link: Link: /foo</p>",
"|return:foo|",
"Defer Block.",
"Home hero.",
"Render blockquote.",
)
b.AssertFileContent("public/en/p1/index.html", "Base.\nSingle needs base.\n\nHero::\n\nDefer Block.")
b.AssertFileContent("public/en/404.html", "404.")
b.AssertFileContent("public/nn/404.html", "404.")
b.AssertFileContent("public/fr/404.html", "404.")
}
}
func TestHomeRSSAndHTMLWithHTMLOnlyShortcode(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term"]
[outputs]
home = ["html", "rss"]
-- layouts/home.html --
Home: {{ .Title }}|{{ .Content }}|
-- layouts/single.html --
Single: {{ .Title }}|{{ .Content }}|
-- layouts/_shortcodes/myshortcode.html --
Myshortcode: Count: {{ math.Counter }}|
-- content/p1.md --
---
title: "P1"
---
{{< myshortcode >}}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "Single: P1|Myshortcode: Count: 1|")
b.AssertFileContent("public/index.xml", "Myshortcode: Count: 1")
}
func TestHomeRSSAndHTMLWithHTMLOnlyRenderHook(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term"]
[outputs]
home = ["html", "rss"]
-- layouts/home.html --
Home: {{ .Title }}|{{ .Content }}|
-- layouts/single.html --
Single: {{ .Title }}|{{ .Content }}|
-- layouts/_markup/render-link.html --
Render Link: {{ math.Counter }}|
-- content/p1.md --
---
title: "P1"
---
Link: [Foo](/foo)
`
for range 2 {
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.xml", "Link: Render Link: 1|")
b.AssertFileContent("public/p1/index.html", "Single: P1|<p>Link: Render Link: 1|<")
}
}
func TestCodeblockIssue13864(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- content/_index.md --
---
title: home
---
~~~
LANG: none
~~~
~~~go
LANG: go
~~~
~~~go-html-template
LANG: go-html-template
~~~
~~~xy
LANG: xy
~~~
~~~x-y
LANG: x-y
~~~
-- layouts/home.html --
{{ .Content }}
-- layouts/_markup/render-codeblock.html --
{{ .Inner }} LAYOUT: render-codeblock.html|
-- layouts/_markup/render-codeblock-go.html --
{{ .Inner }} LAYOUT: render-codeblock-go.html|
-- layouts/_markup/render-codeblock-go-html-template.html --
{{ .Inner }} LAYOUT: render-codeblock-go-html-template.html|
-- layouts/_markup/render-codeblock-xy.html --
{{ .Inner }} LAYOUT: render-codeblock-xy.html|
-- layouts/_markup/render-codeblock-x-y.html.html --
{{ .Inner }} LAYOUT: render-codeblock-x-y.html|
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html",
"LANG: none LAYOUT: render-codeblock.html|", // pass
"LANG: go LAYOUT: render-codeblock-go.html|", // fail: uses render-codeblock-go-html-template.html
"LANG: go-html-template LAYOUT: render-codeblock-go-html-template.html|", // fail: uses render-codeblock.html
"LANG: xy LAYOUT: render-codeblock-xy.html|", // pass
"LANG: x-y LAYOUT: render-codeblock-x-y.html|", // fail: uses render-codeblock.html
)
}
func TestRenderCodeblockSpecificity(t *testing.T) {
files := `
-- hugo.toml --
-- layouts/_markup/render-codeblock.html --
Render codeblock.|{{ .Inner }}|
-- layouts/_markup/render-codeblock-go.html --
Render codeblock go.|{{ .Inner }}|
-- layouts/single.html --
{{ .Title }}|{{ .Content }}|
-- content/p1.md --
---
title: "P1"
---
§§§
Basic
§§§
§§§ go
Go
§§§
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "P1|Render codeblock.|Basic|Render codeblock go.|Go|")
}
func TestPrintUnusedTemplates(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = 'http://example.com/'
printUnusedTemplates=true
-- content/p1.md --
---
title: "P1"
---
{{< usedshortcode >}}
-- layouts/baseof.html --
{{ block "main" . }}{{ end }}
-- layouts/baseof.json --
{{ block "main" . }}{{ end }}
-- layouts/home.html --
{{ define "main" }}FOO{{ end }}
-- layouts/single.json --
-- layouts/single.html --
{{ define "main" }}MAIN /_default/single.html{{ end }}
-- layouts/post/single.html --
{{ define "main" }}MAIN{{ end }}
-- layouts/_partials/usedpartial.html --
-- layouts/_partials/unusedpartial.html --
-- layouts/_shortcodes/usedshortcode.html --
{{ partial "usedpartial.html" }}
-- layouts/_shortcodes/unusedshortcode.html --
`
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
NeedsOsFS: true,
},
)
b.Build()
b.AssertFileContent("public/p1/index.html", "MAIN /_default/single.html")
unused := b.H.GetTemplateStore().UnusedTemplates()
var names []string
for _, tmpl := range unused {
if fi := tmpl.Fi; fi != nil {
names = append(names, fi.Meta().PathInfo.PathNoLeadingSlash())
}
}
b.Assert(names, qt.DeepEquals, []string{"_partials/unusedpartial.html", "_shortcodes/unusedshortcode.html", "baseof.json", "post/single.html", "single.json"})
b.Assert(len(unused), qt.Equals, 5, qt.Commentf("%#v", names))
}
func TestCreateManyTemplateStores(t *testing.T) {
t.Parallel()
b := hugolib.Test(t, newSetupTestSites)
store := b.H.TemplateStore
for range 70 {
newStore, err := store.NewFromOpts()
b.Assert(err, qt.IsNil)
b.Assert(newStore, qt.Not(qt.IsNil))
}
}
func TestLayoutWithLanguagesVersionsAndRoles(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term", "sitemap", "rss"]
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
defaultContentVersion = "v2.0.0"
defaultContentVersionInSubdir = true
defaultContentRole = "admin"
defaultContentRoleInSubdir = true
[languages]
[languages.en]
weight = 1
[languages.nn]
weight = 2
[versions."v2.0.0"]
[versions."v1.0.0"]
[roles.admin]
weight = 1
[roles.user]
weight = 2
[[module.mounts]]
source = 'content/en'
target = 'content'
[module.mounts.sites.matrix]
languages = ['en']
versions = ['**']
[[module.mounts]]
source = 'content/nn'
target = 'content'
[module.mounts.sites.matrix]
languages = ['nn']
versions = ['**']
[[module.mounts]]
source = 'layouts/v1'
target = 'layouts'
[module.mounts.sites.matrix]
weight = 10
versions = ['v1**']
languages = ['**']
[[module.mounts]]
source = 'layouts/en'
target = 'layouts'
[module.mounts.sites.matrix]
languages = ['en']
versions = ['**']
[[module.mounts]]
source = 'layouts/nn'
target = 'layouts'
[module.mounts.sites.matrix]
languages = ['nn']
versions = ['**']
-- layouts/v1/all.html --
layouts/v1/all.html
-- layouts/en/all.html --
layouts/en/all.html
-- layouts/nn/all.html --
layouts/nn/all.html
`
b := hugolib.Test(t, files)
// b.AssertPublishDir("asdf")
b.AssertFileContent("public/admin/v2.0.0/en/index.html", "layouts/en/all.html")
b.AssertFileContent("public/admin/v2.0.0/nn/index.html", "layouts/nn/all.html")
b.AssertFileContent("public/admin/v1.0.0/nn/index.html", "layouts/v1/all.html")
b.AssertFileContent("public/admin/v1.0.0/en/index.html", "layouts/v1/all.html")
}
func BenchmarkLookupPagesLayout(b *testing.B) {
files := `
-- hugo.toml --
-- layouts/single.html --
{{ define "main" }}
Main.
{{ end }}
-- layouts/baseof.html --
baseof: {{ block "main" . }}{{ end }}
-- layouts/foo/bar/single.html --
{{ define "main" }}
Main.
{{ end }}
`
bb := hugolib.Test(b, files)
store := bb.H.TemplateStore
b.ResetTimer()
b.Run("Single root", func(b *testing.B) {
q := tplimpl.TemplateQuery{
Path: "/baz",
Category: tplimpl.CategoryLayout,
Desc: tplimpl.TemplateDescriptor{Kind: kinds.KindPage, LayoutFromTemplate: "single", OutputFormat: "html"},
}
for b.Loop() {
store.LookupPagesLayout(q)
}
})
b.Run("Single sub folder", func(b *testing.B) {
q := tplimpl.TemplateQuery{
Path: "/foo/bar",
Category: tplimpl.CategoryLayout,
Desc: tplimpl.TemplateDescriptor{Kind: kinds.KindPage, LayoutFromTemplate: "single", OutputFormat: "html"},
}
for b.Loop() {
store.LookupPagesLayout(q)
}
})
}
func BenchmarkNewTemplateStore(b *testing.B) {
bb := hugolib.Test(b, newSetupTestSites)
store := bb.H.TemplateStore
for b.Loop() {
newStore, err := store.NewFromOpts()
if err != nil {
b.Fatal(err)
}
if newStore == nil {
b.Fatal("newStore is nil")
}
}
}
func TestLayoutsLookupVariants(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
[outputs]
home = ["html", "rss"]
page = ["html", "rss", "amp"]
section = ["html", "rss"]
[languages]
[languages.en]
title = "Title in English"
weight = 1
[languages.nn]
title = "Tittel på nynorsk"
weight = 2
-- layouts/list.xml --
layouts/list.xml
-- layouts/_shortcodes/myshortcode.html --
layouts/_shortcodes/myshortcode.html
-- layouts/foo/bar/_shortcodes/myshortcode.html --
layouts/foo/bar/_shortcodes/myshortcode.html
-- layouts/_markup/render-codeblock.html --
layouts/_markup/render-codeblock.html|{{ .Type }}|
-- layouts/_markup/render-codeblock-go.html --
layouts/_markup/render-codeblock-go.html|{{ .Type }}|
-- layouts/single.xml --
layouts/single.xml
-- layouts/single.rss.xml --
layouts/single.rss.xml
-- layouts/single.nn.rss.xml --
layouts/single.nn.rss.xml
-- layouts/list.html --
layouts/list.html
-- layouts/single.html --
layouts/single.html
{{ .Content }}
-- layouts/mylayout.html --
layouts/mylayout.html
-- layouts/mylayout.nn.html --
layouts/mylayout.nn.html
-- layouts/foo/single.rss.xml --
layouts/foo/single.rss.xml
-- layouts/foo/single.amp.html --
layouts/foo/single.amp.html
-- layouts/foo/bar/page.html --
layouts/foo/bar/page.html
-- layouts/foo/bar/baz/single.html --
layouts/foo/bar/baz/single.html
{{ .Content }}
-- layouts/qux/mylayout.html --
layouts/qux/mylayout.html
-- layouts/qux/single.xml --
layouts/qux/single.xml
-- layouts/qux/mylayout.section.html --
layouts/qux/mylayout.section.html
-- content/p.md --
---
---
§§§
code
§§§
§§§ go
code
§§§
{{< myshortcode >}}
-- content/foo/p.md --
-- content/foo/p.nn.md --
-- content/foo/bar/p.md --
-- content/foo/bar/withmylayout.md --
---
layout: mylayout
---
-- content/foo/bar/_index.md --
-- content/foo/bar/baz/p.md --
---
---
{{< myshortcode >}}
-- content/qux/p.md --
-- content/qux/_index.md --
---
layout: mylayout
---
-- content/qux/quux/p.md --
-- content/qux/quux/withmylayout.md --
---
layout: mylayout
---
-- content/qux/quux/withmylayout.nn.md --
---
layout: mylayout
---
`
for range 2 {
b := hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertLogContains("! WARN")
// Single pages.
// output format: html.
b.AssertFileContent("public/en/p/index.html", "layouts/single.html",
"layouts/_markup/render-codeblock.html|",
"layouts/_markup/render-codeblock-go.html|go|",
"layouts/_shortcodes/myshortcode.html",
)
b.AssertFileContent("public/en/foo/p/index.html", "layouts/single.html")
b.AssertFileContent("public/en/foo/bar/p/index.html", "layouts/foo/bar/page.html")
b.AssertFileContent("public/en/foo/bar/withmylayout/index.html", "layouts/mylayout.html")
b.AssertFileContent("public/en/foo/bar/baz/p/index.html", "layouts/foo/bar/baz/single.html", "layouts/foo/bar/_shortcodes/myshortcode.html")
b.AssertFileContent("public/en/qux/quux/withmylayout/index.html", "layouts/qux/mylayout.html")
// output format: amp.
b.AssertFileContent("public/en/amp/p/index.html", "layouts/single.html")
b.AssertFileContent("public/en/amp/foo/p/index.html", "layouts/foo/single.amp.html")
// output format: rss.
b.AssertFileContent("public/en/p/index.xml", "layouts/single.rss.xml")
b.AssertFileContent("public/en/foo/p/index.xml", "layouts/foo/single.rss.xml")
// Note: THere is layouts/foo/single.rss.xml, but we use the root because of a better language match.
b.AssertFileContent("public/nn/foo/p/index.xml", "layouts/single.nn.rss.xml")
// Note: There is qux/single.xml that's closer, but the one in the root is used because of the output format match.
b.AssertFileContent("public/en/qux/p/index.xml", "layouts/single.rss.xml")
// Note.
b.AssertFileContent("public/nn/qux/quux/withmylayout/index.html", "layouts/mylayout.nn.html")
// Section pages.
// output format: html.
b.AssertFileContent("public/en/foo/index.html", "layouts/list.html")
b.AssertFileContent("public/en/qux/index.html", "layouts/qux/mylayout.section.html")
// output format: rss.
b.AssertFileContent("public/en/foo/index.xml", "layouts/list.xml")
}
}
func TestLookupOrderIssue13636(t *testing.T) {
t.Parallel()
filesTemplate := `
-- hugo.toml --
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
[languages]
[languages.en]
weight = 1
[languages.nn]
weight = 2
-- content/s1/p1.en.md --
---
outputs: ["html", "amp", "json"]
---
-- content/s1/p1.nn.md --
---
outputs: ["html", "amp", "json"]
---
-- layouts/L1 --
L1
-- layouts/L2 --
L2
-- layouts/L3 --
L3
`
tests := []struct {
Lang string
L1 string
L2 string
L3 string
ExpectHTML string
ExpectAmp string
ExpectJSON string
}{
{"en", "all.en.html", "all.html", "single.html", "single.html", "single.html", ""},
{"en", "all.amp.html", "all.html", "page.html", "page.html", "all.amp.html", ""},
{"en", "all.amp.html", "all.html", "list.html", "all.html", "all.amp.html", ""},
{"en", "all.en.html", "all.json", "single.html", "single.html", "single.html", "all.json"},
{"en", "all.en.html", "single.json", "single.html", "single.html", "single.html", "single.json"},
{"en", "all.en.html", "all.html", "list.html", "all.en.html", "all.en.html", ""},
{"en", "list.en.html", "list.html", "list.en.html", "", "", ""},
{"nn", "all.en.html", "all.html", "single.html", "single.html", "single.html", ""},
{"nn", "all.en.html", "all.nn.html", "single.html", "single.html", "single.html", ""},
{"nn", "all.en.html", "all.nn.html", "single.nn.html", "single.nn.html", "single.nn.html", ""},
{"nn", "single.json", "single.nn.json", "all.json", "", "", "single.nn.json"},
{"nn", "single.json", "single.en.json", "all.nn.json", "", "", "single.json"},
}
for i, test := range tests {
if i != 10 {
// continue
}
files := strings.ReplaceAll(filesTemplate, "L1", test.L1)
files = strings.ReplaceAll(files, "L2", test.L2)
files = strings.ReplaceAll(files, "L3", test.L3)
t.Logf("Test %d: %s %s %s %s", i, test.Lang, test.L1, test.L2, test.L3)
for range 1 {
b := hugolib.Test(t, files)
b.Assert(len(b.H.Sites), qt.Equals, 2)
var (
pubhHTML = "public/LANG/s1/p1/index.html"
pubhAmp = "public/LANG/amp/s1/p1/index.html"
pubhJSON = "public/LANG/s1/p1/index.json"
)
pubhHTML = strings.ReplaceAll(pubhHTML, "LANG", test.Lang)
pubhAmp = strings.ReplaceAll(pubhAmp, "LANG", test.Lang)
pubhJSON = strings.ReplaceAll(pubhJSON, "LANG", test.Lang)
if test.ExpectHTML != "" {
b.AssertFileContent(pubhHTML, test.ExpectHTML)
} else {
b.AssertFileExists(pubhHTML, false)
}
if test.ExpectAmp != "" {
b.AssertFileContent(pubhAmp, test.ExpectAmp)
} else {
b.AssertFileExists(pubhAmp, false)
}
if test.ExpectJSON != "" {
b.AssertFileContent(pubhJSON, test.ExpectJSON)
} else {
b.AssertFileExists(pubhJSON, false)
}
}
}
}
func TestLookupShortcodeDepth(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/_shortcodes/myshortcode.html --
layouts/_shortcodes/myshortcode.html
-- layouts/foo/_shortcodes/myshortcode.html --
layouts/foo/_shortcodes/myshortcode.html
-- layouts/single.html --
{{ .Content }}|
-- content/p.md --
---
---
{{< myshortcode >}}
-- content/foo/p.md --
---
---
{{< myshortcode >}}
-- content/foo/bar/p.md --
---
---
{{< myshortcode >}}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p/index.html", "layouts/_shortcodes/myshortcode.html")
b.AssertFileContent("public/foo/p/index.html", "layouts/foo/_shortcodes/myshortcode.html")
b.AssertFileContent("public/foo/bar/p/index.html", "layouts/foo/_shortcodes/myshortcode.html")
}
func TestLookupShortcodeLayout(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/_shortcodes/myshortcode.single.html --
layouts/_shortcodes/myshortcode.single.html
-- layouts/_shortcodes/myshortcode.list.html --
layouts/_shortcodes/myshortcode.list.html
-- layouts/single.html --
{{ .Content }}|
-- layouts/list.html --
{{ .Content }}|
-- content/_index.md --
---
---
{{< myshortcode >}}
-- content/p.md --
---
---
{{< myshortcode >}}
-- content/foo/p.md --
---
---
{{< myshortcode >}}
-- content/foo/bar/p.md --
---
---
{{< myshortcode >}}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p/index.html", "layouts/_shortcodes/myshortcode.single.html")
b.AssertFileContent("public/index.html", "layouts/_shortcodes/myshortcode.list.html")
}
func TestLayoutAll(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/single.html --
Single.
-- layouts/all.html --
All.
-- content/p1.md --
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "Single.")
b.AssertFileContent("public/index.html", "All.")
}
func TestLayoutAllNested(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['rss','sitemap','taxonomy','term']
-- content/s1/p1.md --
---
title: p1
---
-- content/s2/p2.md --
---
title: p2
---
-- layouts/single.html --
layouts/single.html
-- layouts/list.html --
layouts/list.html
-- layouts/s1/all.html --
layouts/s1/all.html
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "layouts/list.html")
b.AssertFileContent("public/s1/index.html", "layouts/s1/all.html")
b.AssertFileContent("public/s1/p1/index.html", "layouts/s1/all.html")
b.AssertFileContent("public/s2/index.html", "layouts/list.html")
b.AssertFileContent("public/s2/p2/index.html", "layouts/single.html")
}
func TestPartialHTML(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/all.html --
<html>
<head>
{{ partial "css.html" .}}
</head>
</html>
-- layouts/_partials/css.html --
<link rel="stylesheet" href="/css/style.css">
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "<link rel=\"stylesheet\" href=\"/css/style.css\">")
}
func TestPartialPlainTextInHTML(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/all.html --
<html>
<head>
{{ partial "mypartial.txt" . }}
</head>
</html>
-- layouts/_partials/mypartial.txt --
My <div>partial</div>.
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "My <div>partial</div>.")
}
// Issue #13593.
func TestGoatAndNoGoat(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- content/_index.md --
---
title: "Home"
---
§§§
printf "Hello, world!"
§§§
§§§ goat
.---. .-. .-. .-. .---.
| A +--->| 1 |<--->| 2 |<--->| 3 |<---+ B |
'---' '-' '+' '+' '---'
§§§
-- layouts/all.html --
{{ .Content }}
`
b := hugolib.Test(t, files)
// Basic code block.
b.AssertFileContent("public/index.html", "<code>printf "Hello, world!"\n</code>")
// Goat code block.
b.AssertFileContent("public/index.html", "Menlo,Lucida")
}
// Issue #13595.
func TestGoatAndNoGoatCustomTemplate(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- content/_index.md --
---
title: "Home"
---
§§§
printf "Hello, world!"
§§§
§§§ goat
.---. .-. .-. .-. .---.
| A +--->| 1 |<--->| 2 |<--->| 3 |<---+ B |
'---' '-' '+' '+' '---'
§§§
-- layouts/_markup/render-codeblock.html --
_markup/render-codeblock.html
-- layouts/all.html --
{{ .Content }}
`
b := hugolib.Test(t, files)
// Basic code block.
b.AssertFileContent("public/index.html", "_markup/render-codeblock.html")
// Goat code block.
b.AssertFileContent("public/index.html", "Menlo,Lucida")
}
func TestGoatcustom(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- content/_index.md --
---
title: "Home"
---
§§§
printf "Hello, world!"
§§§
§§§ goat
.---. .-. .-. .-. .---.
| A +--->| 1 |<--->| 2 |<--->| 3 |<---+ B |
'---' '-' '+' '+' '---'
§§§
-- layouts/_markup/render-codeblock.html --
_markup/render-codeblock.html
-- layouts/_markup/render-codeblock-goat.html --
_markup/render-codeblock-goat.html
-- layouts/all.html --
{{ .Content }}
`
b := hugolib.Test(t, files)
// Basic code block.
b.AssertFileContent("public/index.html", "_markup/render-codeblock.html")
// Custom Goat code block.
b.AssertFileContent("public/index.html", "_markup/render-codeblock.html_markup/render-codeblock-goat.html")
}
func TestLookupCodeblockIssue13651(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/all.html --
{{ .Content }}|
-- layouts/_markup/render-codeblock-foo.html --
render-codeblock-foo.html
-- content/_index.md --
---
---
§§§
printf "Hello, world!"
§§§
§§§ foo
printf "Hello, world again!"
§§§
`
b := hugolib.Test(t, files)
content := b.FileContent("public/index.html")
fooCount := strings.Count(content, "render-codeblock-foo.html")
b.Assert(fooCount, qt.Equals, 1)
}
// Issue #13515
func TestPrintPathWarningOnDotRemoval(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = "https://example.com"
printPathWarnings = true
-- content/v0.124.0.md --
-- content/v0.123.0.md --
-- layouts/all.html --
All.
-- layouts/single.html --
{{ .Title }}|
`
b := hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertLogContains("! Duplicate content path")
}
// Issue #13577.
func TestPrintPathWarningOnInvalidMarkupFilename(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/all.html --
All.
-- layouts/_markup/sitemap.xml --
`
b := hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertLogContains("unrecognized render hook")
}
func TestLayoutNotFound(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/single.html --
Single.
`
b := hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertLogContains("WARN found no layout file for \"html\" for kind \"home\"")
}
func TestLayoutOverrideThemeWhenThemeOnOldFormatIssue13715(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
theme = "mytheme"
-- layouts/list.html --
layouts/list.html
-- themes/mytheme/layouts/_default/list.html --
mytheme/layouts/_default/list.html
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "layouts/list.html")
}
func BenchmarkExecuteWithContext(b *testing.B) {
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term", "home"]
-- layouts/all.html --
{{ .Title }}|
{{ partial "p1.html" . }}
-- layouts/_partials/p1.html --
p1.
{{ partial "p2.html" . }}
{{ partial "p2.html" . }}
{{ partial "p3.html" . }}
{{ partial "p2.html" . }}
{{ partial "p2.html" . }}
{{ partial "p2.html" . }}
{{ partial "p3.html" . }}
-- layouts/_partials/p2.html --
{{ partial "p3.html" . }}
-- layouts/_partials/p3.html --
p3
-- content/p1.md --
`
bb := hugolib.Test(b, files)
store := bb.H.TemplateStore
ti := store.LookupByPath("/all.html")
bb.Assert(ti, qt.Not(qt.IsNil))
p := bb.H.Sites[0].RegularPages()[0]
bb.Assert(p, qt.Not(qt.IsNil))
for b.Loop() {
err := store.ExecuteWithContext(context.Background(), ti, io.Discard, p)
if err != nil {
b.Fatal(err)
}
}
}
func BenchmarkLookupPartial(b *testing.B) {
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term", "home"]
-- layouts/all.html --
{{ .Title }}|
-- layouts/_partials/p1.html --
-- layouts/_partials/p2.html --
-- layouts/_partials/p2.json --
-- layouts/_partials/p3.html --
`
bb := hugolib.Test(b, files)
store := bb.H.TemplateStore
for b.Loop() {
fi := store.LookupPartial("p3.html")
if fi == nil {
b.Fatal("not found")
}
}
}
// Implemented by pageOutput.
type getDescriptorProvider interface {
GetInternalTemplateBasePathAndDescriptor() (string, tplimpl.TemplateDescriptor)
}
func BenchmarkLookupShortcode(b *testing.B) {
files := `
-- hugo.toml --
disableKinds = ["taxonomy", "term", "home"]
-- content/toplevelpage.md --
-- content/a/b/c/nested.md --
-- layouts/all.html --
{{ .Title }}|
-- layouts/_shortcodes/s.html --
s1.
-- layouts/_shortcodes/a/b/s.html --
s2.
`
bb := hugolib.Test(b, files)
store := bb.H.TemplateStore
runOne := func(p page.Page) {
pth, desc := p.(getDescriptorProvider).GetInternalTemplateBasePathAndDescriptor()
q := tplimpl.TemplateQuery{
Path: pth,
Name: "s",
Category: tplimpl.CategoryShortcode,
Desc: desc,
}
v, err := store.LookupShortcode(q)
if v == nil || err != nil {
b.Fatal("not found")
}
}
b.Run("toplevelpage", func(b *testing.B) {
toplevelpage, _ := bb.H.Sites[0].GetPage("/toplevelpage")
for b.Loop() {
runOne(toplevelpage)
}
})
b.Run("nestedpage", func(b *testing.B) {
toplevelpage, _ := bb.H.Sites[0].GetPage("/a/b/c/nested")
for b.Loop() {
runOne(toplevelpage)
}
})
}
func TestStandardLayoutInFrontMatter13588(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','page','rss','sitemap','taxonomy','term']
-- content/s1/_index.md --
---
title: s1
---
-- content/s2/_index.md --
---
title: s2
layout: list
---
-- content/s3/_index.md --
---
title: s3
layout: single
---
-- layouts/list.html --
list.html
-- layouts/section.html --
section.html
-- layouts/single.html --
single.html
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/s1/index.html", "section.html")
b.AssertFileContent("public/s2/index.html", "list.html") // fail
b.AssertFileContent("public/s3/index.html", "single.html") // fail
}
func TestIssue13605(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','rss','section','sitemap','taxonomy','term']
-- content/s1/p1.md --
---
title: p1
---
{{< sc >}}
-- layouts/s1/_shortcodes/sc.html --
layouts/s1/_shortcodes/sc.html
-- layouts/single.html --
{{ .Content }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/s1/p1/index.html", "layouts/s1/_shortcodes/sc.html")
}
func TestSkipDotFiles(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/all.html --
All.
-- layouts/.DS_Store --
{{ foo }}
`
// Just make sure it doesn't fail.
hugolib.Test(t, files)
}
func TestPartialsLangIssue13612(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','section','sitemap','taxonomy','term']
defaultContentLanguage = 'ru'
defaultContentLanguageInSubdir = true
[languages.ru]
weight = 1
[languages.en]
weight = 2
[outputs]
home = ['html','rss']
-- layouts/_partials/comment.en.html --
layouts/_partials/comment.en.html
-- layouts/_partials/comment.en.xml --
layouts/_partials/comment.en.xml
-- layouts/_partials/comment.ru.html --
layouts/_partials/comment.ru.html
-- layouts/_partials/comment.ru.xml --
layouts/_partials/comment.ru.xml
-- layouts/home.html --
{{ partial (print "comment." (default "ru" .Lang) ".html") . }}
-- layouts/home.rss.xml --
{{ partial (print "comment." (default "ru" .Lang) ".xml") . }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/en/index.html", "layouts/_partials/comment.en.html")
b.AssertFileContent("public/en/index.xml", "layouts/_partials/comment.en.xml") // fail
b.AssertFileContent("public/ru/index.html", "layouts/_partials/comment.ru.html") // fail
b.AssertFileContent("public/ru/index.xml", "layouts/_partials/comment.ru.xml") // fail
}
func TestLayoutIssue13628(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['home','rss','sitemap','taxonomy','term']
-- content/p1.md --
---
title: p1
layout: foo
---
-- layouts/single.html --
layouts/single.html
-- layouts/list.html --
layouts/list.html
`
for range 5 {
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "layouts/single.html")
}
}
func TestTemplateLoop(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/_partials/p.html --
p: {{ partial "p.html" . }}
-- layouts/all.html --
{{ partial "p.html" . }}
`
b, err := hugolib.TestE(t, files)
b.Assert(err, qt.IsNotNil)
b.Assert(err.Error(), qt.Contains, "error calling partial: maximum template call stack size exceeded")
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | true |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/urls/init.go | tpl/urls/init.go | // Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package urls
import (
"context"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/internal"
)
const name = "urls"
func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
ctx := New(d)
ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },
}
ns.AddMethodMapping(ctx.AbsLangURL,
[]string{"absLangURL"},
[][2]string{},
)
ns.AddMethodMapping(ctx.AbsURL,
[]string{"absURL"},
[][2]string{},
)
ns.AddMethodMapping(ctx.Anchorize,
[]string{"anchorize"},
[][2]string{
{`{{ "This is a title" | anchorize }}`, `this-is-a-title`},
},
)
ns.AddMethodMapping(ctx.JoinPath,
nil,
[][2]string{
{`{{ urls.JoinPath "https://example.org" "foo" }}`, `https://example.org/foo`},
{`{{ urls.JoinPath (slice "a" "b") }}`, `a/b`},
},
)
ns.AddMethodMapping(ctx.Parse,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.PathEscape,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.PathUnescape,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Ref,
[]string{"ref"},
[][2]string{},
)
ns.AddMethodMapping(ctx.RelLangURL,
[]string{"relLangURL"},
[][2]string{},
)
ns.AddMethodMapping(ctx.RelRef,
[]string{"relref"},
[][2]string{},
)
ns.AddMethodMapping(ctx.RelURL,
[]string{"relURL"},
[][2]string{},
)
ns.AddMethodMapping(ctx.URLize,
[]string{"urlize"},
[][2]string{},
)
return ns
}
internal.AddTemplateFuncsNamespace(f)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/urls/urls.go | tpl/urls/urls.go | // Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package urls provides template functions to deal with URLs.
package urls
import (
"errors"
"fmt"
"net/url"
"github.com/gohugoio/hugo/common/urls"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/cast"
)
// New returns a new instance of the urls-namespaced template functions.
func New(deps *deps.Deps) *Namespace {
return &Namespace{
deps: deps,
multihost: deps.Conf.IsMultihost(),
}
}
// Namespace provides template functions for the "urls" namespace.
type Namespace struct {
deps *deps.Deps
multihost bool
}
// AbsURL takes the string s and converts it to an absolute URL.
func (ns *Namespace) AbsURL(s any) (string, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
return ns.deps.PathSpec.AbsURL(ss, false), nil
}
// Parse parses rawurl into a URL structure. The rawurl may be relative or
// absolute.
func (ns *Namespace) Parse(rawurl any) (*url.URL, error) {
s, err := cast.ToStringE(rawurl)
if err != nil {
return nil, fmt.Errorf("error in Parse: %w", err)
}
return url.Parse(s)
}
// RelURL takes the string s and prepends the relative path according to a
// page's position in the project directory structure.
func (ns *Namespace) RelURL(s any) (string, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
return ns.deps.PathSpec.RelURL(ss, false), nil
}
// URLize returns the strings s formatted as an URL.
func (ns *Namespace) URLize(s any) (string, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
return ns.deps.PathSpec.URLize(ss), nil
}
// Anchorize creates sanitized anchor name version of the string s that is compatible
// with how your configured markdown renderer does it.
func (ns *Namespace) Anchorize(s any) (string, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
return ns.deps.ContentSpec.SanitizeAnchorName(ss), nil
}
// Ref returns the absolute URL path to a given content item from Page p.
func (ns *Namespace) Ref(p any, args any) (string, error) {
pp, ok := p.(urls.RefLinker)
if !ok {
return "", errors.New("invalid Page received in Ref")
}
argsm, err := ns.refArgsToMap(args)
if err != nil {
return "", err
}
s, err := pp.Ref(argsm)
return s, err
}
// RelRef returns the relative URL path to a given content item from Page p.
func (ns *Namespace) RelRef(p any, args any) (string, error) {
pp, ok := p.(urls.RefLinker)
if !ok {
return "", errors.New("invalid Page received in RelRef")
}
argsm, err := ns.refArgsToMap(args)
if err != nil {
return "", err
}
s, err := pp.RelRef(argsm)
return s, err
}
func (ns *Namespace) refArgsToMap(args any) (map[string]any, error) {
var (
s string
of string
)
v := args
if _, ok := v.([]any); ok {
v = cast.ToStringSlice(v)
}
switch v := v.(type) {
case map[string]any:
return v, nil
case map[string]string:
m := make(map[string]any)
for k, v := range v {
m[k] = v
}
return m, nil
case []string:
if len(v) == 0 || len(v) > 2 {
return nil, fmt.Errorf("invalid number of arguments to ref")
}
// These were the options before we introduced the map type:
s = v[0]
if len(v) == 2 {
of = v[1]
}
default:
var err error
s, err = cast.ToStringE(args)
if err != nil {
return nil, err
}
}
return map[string]any{
"path": s,
"outputFormat": of,
}, nil
}
// RelLangURL takes the string s and prepends the relative path according to a
// page's position in the project directory structure and the current language.
func (ns *Namespace) RelLangURL(s any) (string, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
return ns.deps.PathSpec.RelURL(ss, !ns.multihost), nil
}
// AbsLangURL the string s and converts it to an absolute URL according
// to a page's position in the project directory structure and the current
// language.
func (ns *Namespace) AbsLangURL(s any) (string, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
return ns.deps.PathSpec.AbsURL(ss, !ns.multihost), nil
}
// JoinPath joins the provided elements into a URL string and cleans the result
// of any ./ or ../ elements. If the argument list is empty, JoinPath returns
// an empty string.
func (ns *Namespace) JoinPath(elements ...any) (string, error) {
if len(elements) == 0 {
return "", nil
}
var selements []string
for _, e := range elements {
switch v := e.(type) {
case []string:
selements = append(selements, v...)
case []any:
for _, e := range v {
se, err := cast.ToStringE(e)
if err != nil {
return "", err
}
selements = append(selements, se)
}
default:
se, err := cast.ToStringE(e)
if err != nil {
return "", err
}
selements = append(selements, se)
}
}
result, err := url.JoinPath(selements[0], selements[1:]...)
if err != nil {
return "", err
}
return result, nil
}
// PathEscape returns the given string, applying percent-encoding to special
// characters and reserved delimiters so it can be safely used as a segment
// within a URL path.
func (ns *Namespace) PathEscape(s any) (string, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
return url.PathEscape(ss), nil
}
// PathUnescape returns the given string, replacing all percent-encoded
// sequences with the corresponding unescaped characters.
func (ns *Namespace) PathUnescape(s any) (string, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
return url.PathUnescape(ss)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/urls/urls_test.go | tpl/urls/urls_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 urls
import (
"net/url"
"regexp"
"testing"
"github.com/gohugoio/hugo/config/testconfig"
"github.com/gohugoio/hugo/htesting/hqt"
qt "github.com/frankban/quicktest"
)
func newNs() *Namespace {
return New(testconfig.GetTestDeps(nil, nil))
}
type tstNoStringer struct{}
func TestParse(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
for _, test := range []struct {
rawurl any
expect any
}{
{
"http://www.google.com",
&url.URL{
Scheme: "http",
Host: "www.google.com",
},
},
{
"http://j@ne:password@google.com",
&url.URL{
Scheme: "http",
User: url.UserPassword("j@ne", "password"),
Host: "google.com",
},
},
// errors
{tstNoStringer{}, false},
} {
result, err := ns.Parse(test.rawurl)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}
c.Assert(err, qt.IsNil)
c.Assert(result,
qt.CmpEquals(hqt.DeepAllowUnexported(&url.URL{}, url.Userinfo{})), test.expect)
}
}
func TestJoinPath(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
for _, test := range []struct {
elements any
expect any
}{
{"", `/`},
{"a", `a`},
{"/a/b", `/a/b`},
{"./../a/b", `a/b`},
{[]any{""}, `/`},
{[]any{"a"}, `a`},
{[]any{"/a", "b"}, `/a/b`},
{[]any{".", "..", "/a", "b"}, `a/b`},
{[]any{"https://example.org", "a"}, `https://example.org/a`},
{[]any{nil}, `/`},
// errors
{tstNoStringer{}, false},
{[]any{tstNoStringer{}}, false},
} {
result, err := ns.JoinPath(test.elements)
if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}
c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
}
}
func TestPathEscape(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
tests := []struct {
name string
input any
want string
wantErr bool
errCheck string
}{
{"string", "A/b/c?d=é&f=g+h", "A%2Fb%2Fc%3Fd=%C3%A9&f=g+h", false, ""},
{"empty string", "", "", false, ""},
{"integer", 6, "6", false, ""},
{"float", 7.42, "7.42", false, ""},
{"nil", nil, "", false, ""},
{"slice", []int{}, "", true, "unable to cast"},
{"map", map[string]string{}, "", true, "unable to cast"},
{"struct", tstNoStringer{}, "", true, "unable to cast"},
}
for _, tt := range tests {
c.Run(tt.name, func(c *qt.C) {
got, err := ns.PathEscape(tt.input)
if tt.wantErr {
c.Assert(err, qt.IsNotNil, qt.Commentf("PathEscape(%v) should have failed", tt.input))
if tt.errCheck != "" {
c.Assert(err, qt.ErrorMatches, ".*"+regexp.QuoteMeta(tt.errCheck)+".*")
}
} else {
c.Assert(err, qt.IsNil)
c.Assert(got, qt.Equals, tt.want)
}
})
}
}
func TestPathUnescape(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := newNs()
tests := []struct {
name string
input any
want string
wantErr bool
errCheck string
}{
{"string", "A%2Fb%2Fc%3Fd=%C3%A9&f=g+h", "A/b/c?d=é&f=g+h", false, ""},
{"empty string", "", "", false, ""},
{"integer", 6, "6", false, ""},
{"float", 7.42, "7.42", false, ""},
{"nil", nil, "", false, ""},
{"slice", []int{}, "", true, "unable to cast"},
{"map", map[string]string{}, "", true, "unable to cast"},
{"struct", tstNoStringer{}, "", true, "unable to cast"},
{"malformed hex", "bad%g0escape", "", true, "invalid URL escape"},
{"incomplete hex", "trailing%", "", true, "invalid URL escape"},
{"single hex digit", "trail%1", "", true, "invalid URL escape"},
}
for _, tt := range tests {
c.Run(tt.name, func(c *qt.C) {
got, err := ns.PathUnescape(tt.input)
if tt.wantErr {
c.Assert(err, qt.Not(qt.IsNil), qt.Commentf("PathUnescape(%v) should have failed", tt.input))
if tt.errCheck != "" {
c.Assert(err, qt.ErrorMatches, ".*"+regexp.QuoteMeta(tt.errCheck)+".*")
}
} else {
c.Assert(err, qt.IsNil)
c.Assert(got, qt.Equals, tt.want)
}
})
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/resources/resources_integration_test.go | tpl/resources/resources_integration_test.go | // Copyright 2022s The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package resources_test
import (
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass"
"github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss"
)
func TestCopy(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = "http://example.com/blog"
-- assets/images/pixel.png --
iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==
-- layouts/home.html --
{{/* Image resources */}}
{{ $img := resources.Get "images/pixel.png" }}
{{ $imgCopy1 := $img | resources.Copy "images/copy.png" }}
{{ $imgCopy1 = $imgCopy1.Resize "3x4"}}
{{ $imgCopy2 := $imgCopy1 | resources.Copy "images/copy2.png" }}
{{ $imgCopy3 := $imgCopy1 | resources.Copy "images/copy3.png" }}
Image Orig: {{ $img.RelPermalink}}|{{ $img.MediaType }}|{{ $img.Width }}|{{ $img.Height }}|
Image Copy1: {{ $imgCopy1.RelPermalink}}|{{ $imgCopy1.MediaType }}|{{ $imgCopy1.Width }}|{{ $imgCopy1.Height }}|
Image Copy2: {{ $imgCopy2.RelPermalink}}|{{ $imgCopy2.MediaType }}|{{ $imgCopy2.Width }}|{{ $imgCopy2.Height }}|
Image Copy3: {{ $imgCopy3.MediaType }}|{{ $imgCopy3.Width }}|{{ $imgCopy3.Height }}|
{{/* Generic resources */}}
{{ $targetPath := "js/vars.js" }}
{{ $orig := "let foo;" | resources.FromString "js/foo.js" }}
{{ $copy1 := $orig | resources.Copy "js/copies/bar.js" }}
{{ $copy2 := $orig | resources.Copy "js/copies/baz.js" | fingerprint "md5" }}
{{ $copy3 := $copy2 | resources.Copy "js/copies/moo.js" | minify }}
Orig: {{ $orig.RelPermalink}}|{{ $orig.MediaType }}|{{ $orig.Content | safeJS }}|
Copy1: {{ $copy1.RelPermalink}}|{{ $copy1.MediaType }}|{{ $copy1.Content | safeJS }}|
Copy2: {{ $copy2.RelPermalink}}|{{ $copy2.MediaType }}|{{ $copy2.Content | safeJS }}|
Copy3: {{ $copy3.RelPermalink}}|{{ $copy3.MediaType }}|{{ $copy3.Content | safeJS }}|
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", `
Image Orig: /blog/images/pixel.png|image/png|1|1|
Image Copy1: /blog/images/copy_hu_ef85c36d9b9eff0.png|image/png|3|4|
Image Copy2: /blog/images/copy2.png|image/png|3|4|
Image Copy3: image/png|3|4|
Orig: /blog/js/foo.js|text/javascript|let foo;|
Copy1: /blog/js/copies/bar.js|text/javascript|let foo;|
Copy2: /blog/js/copies/baz.a677329fc6c4ad947e0c7116d91f37a2.js|text/javascript|let foo;|
Copy3: /blog/js/copies/moo.a677329fc6c4ad947e0c7116d91f37a2.min.js|text/javascript|let foo|
`)
b.AssertFileExists("public/images/copy2.png", true)
// No permalink used.
b.AssertFileExists("public/images/copy3.png", false)
}
func TestCopyPageShouldFail(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/home.html --
{{/* This is currently not supported. */}}
{{ $copy := .Copy "copy.md" }}
`
b, err := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
}).BuildE()
b.Assert(err, qt.IsNotNil)
}
func TestGet(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = "http://example.com/blog"
-- assets/images/pixel.png --
iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==
-- layouts/home.html --
{{ with resources.Get "images/pixel.png" }}Image OK{{ else }}Image not found{{ end }}
{{ with resources.Get "" }}Failed{{ else }}Empty string not found{{ end }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", `
Image OK
Empty string not found
`)
}
func TestResourcesGettersShouldNotNormalizePermalinks(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
baseURL = "http://example.com/"
-- assets/401K Prospectus.txt --
Prospectus.
-- layouts/home.html --
{{ $name := "401K Prospectus.txt" }}
Get: {{ with resources.Get $name }}{{ .RelPermalink }}|{{ .Permalink }}|{{ end }}
GetMatch: {{ with resources.GetMatch $name }}{{ .RelPermalink }}|{{ .Permalink }}|{{ end }}
Match: {{ with (index (resources.Match $name) 0) }}{{ .RelPermalink }}|{{ .Permalink }}|{{ end }}
ByType: {{ with (index (resources.ByType "text") 0) }}{{ .RelPermalink }}|{{ .Permalink }}|{{ end }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", `
Get: /401K%20Prospectus.txt|http://example.com/401K%20Prospectus.txt|
GetMatch: /401K%20Prospectus.txt|http://example.com/401K%20Prospectus.txt|
Match: /401K%20Prospectus.txt|http://example.com/401K%20Prospectus.txt|
ByType: /401K%20Prospectus.txt|http://example.com/401K%20Prospectus.txt|
`)
}
func TestGlobalResourcesNotPublishedRegressionIssue12190(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- assets/a.txt --
I am a.txt
-- assets/b.txt --
I am b.txt
-- layouts/home.html --
Home.
{{ with resources.ByType "text" }}
{{ with .Get "a.txt" }}
{{ .Publish }}
{{ end }}
{{ with .GetMatch "*b*" }}
{{ .Publish }}
{{ end }}
{{ end }}
`
b := hugolib.Test(t, files)
b.AssertFileExists("public/a.txt", true) // failing test
b.AssertFileExists("public/b.txt", true) // failing test
}
func TestGlobalResourcesNotPublishedRegressionIssue12214(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['page','rss','section','sitemap','taxonomy','term']
-- assets/files/a.txt --
I am a.txt
-- assets/files/b.txt --
I am b.txt
-- assets/files/c.txt --
I am c.txt
-- assets/files/C.txt --
I am C.txt
-- layouts/home.html --
Home.
{{ with resources.ByType "text" }}
{{ with .Get "files/a.txt" }}
{{ .Publish }}
files/a.txt: {{ .Name }}
{{ end }}
{{ with .Get "/files/a.txt" }}
/files/a.txt: {{ .Name }}
{{ end }}
{{ with .GetMatch "files/*b*" }}
{{ .Publish }}
files/*b*: {{ .Name }}
{{ end }}
{{ with .GetMatch "files/C*" }}
{{ .Publish }}
files/C*: {{ .Name }}
{{ end }}
{{ with .GetMatch "files/c*" }}
{{ .Publish }}
files/c*: {{ .Name }}
{{ end }}
{{ with .GetMatch "/files/c*" }}
/files/c*: {{ .Name }}
{{ end }}
{{ with .Match "files/C*" }}
match files/C*: {{ len . }}|
{{ end }}
{{ with .Match "/files/C*" }}
match /files/C*: {{ len . }}|
{{ end }}
{{ end }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", `
files/a.txt: /files/a.txt
# There are both C.txt and c.txt in the assets, but the Glob matching is case insensitive, so GetMatch returns the first.
files/C*: /files/C.txt
files/c*: /files/C.txt
files/*b*: /files/b.txt
/files/c*: /files/C.txt
/files/a.txt: /files/a.txt
match files/C*: 2|
match /files/C*: 2|
`)
b.AssertFileContent("public/files/a.txt", "I am a.txt")
b.AssertFileContent("public/files/b.txt", "I am b.txt")
b.AssertFileContent("public/files/C.txt", "I am C.txt")
}
// Issue #12961
func TestDartSassVars(t *testing.T) {
t.Parallel()
if !scss.Supports() || !dartsass.Supports() {
t.Skip()
}
files := `
-- hugo.toml --
disableKinds = ['page','section','rss','sitemap','taxonomy','term']
-- layouts/home.html --
{{ $opts := dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" (dict "color" "red") }}
{{ with resources.Get "dartsass.scss" | css.Sass $opts }}
{{ .Content }}
{{ end }}
{{ $opts := dict "transpiler" "libsass" "outputStyle" "compressed" "vars" (dict "color" "blue") }}
{{ with resources.Get "libsass.scss" | css.Sass $opts }}
{{ .Content }}
{{ end }}
-- assets/dartsass.scss --
@use "hugo:vars" as v;
.dartsass {
color: v.$color;
}
-- assets/libsass.scss --
@import "hugo:vars";
.libsass {
color: $color;
}
`
b := hugolib.Test(t, files, hugolib.TestOptWarn())
b.AssertFileContent("public/index.html",
".dartsass{color:red}",
".libsass{color:blue}",
)
b.AssertLogContains("! WARN Dart Sass: hugo:vars")
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/resources/init.go | tpl/resources/init.go | // Copyright 2018 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package resources
import (
"context"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/css"
"github.com/gohugoio/hugo/tpl/internal"
"github.com/gohugoio/hugo/tpl/js"
)
const name = "resources"
func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
ctx, err := New(d)
if err != nil {
// TODO(bep) no panic.
panic(err)
}
ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },
OnCreated: func(m map[string]any) {
for _, v := range m {
switch v := v.(type) {
case *css.Namespace:
ctx.cssNs = v
case *js.Namespace:
ctx.jsNs = v
}
}
if ctx.cssNs == nil {
panic("css namespace not found")
}
if ctx.jsNs == nil {
panic("js namespace not found")
}
},
}
// Deprecated. Use js.Babel instead.
ns.AddMethodMapping(ctx.Babel,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.ByType,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Concat,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Copy,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.ExecuteAsTemplate,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Fingerprint,
[]string{"fingerprint"},
[][2]string{},
)
ns.AddMethodMapping(ctx.FromString,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Get,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Match,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.GetRemote,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Match,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Minify,
[]string{"minify"},
[][2]string{},
)
// Deprecated. Use css.PostCSS instead.
ns.AddMethodMapping(ctx.PostCSS,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.PostProcess,
nil,
[][2]string{},
)
// Deprecated. Use css.Sass instead.
ns.AddMethodMapping(ctx.ToCSS,
nil,
[][2]string{},
)
return ns
}
internal.AddTemplateFuncsNamespace(f)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/resources/resources.go | tpl/resources/resources.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 resources provides template functions for working with resources.
package resources
import (
"context"
"errors"
"fmt"
"github.com/gohugoio/hugo/common/hugo"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/tpl/css"
"github.com/gohugoio/hugo/tpl/js"
"github.com/gohugoio/hugo/resources/postpub"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/resources"
"github.com/gohugoio/hugo/resources/resource"
"github.com/gohugoio/hugo/resources/resource_factories/bundler"
"github.com/gohugoio/hugo/resources/resource_factories/create"
"github.com/gohugoio/hugo/resources/resource_transformers/integrity"
"github.com/gohugoio/hugo/resources/resource_transformers/minifier"
"github.com/gohugoio/hugo/resources/resource_transformers/templates"
"github.com/spf13/cast"
)
// New returns a new instance of the resources-namespaced template functions.
func New(deps *deps.Deps) (*Namespace, error) {
if deps.ResourceSpec == nil {
return &Namespace{}, nil
}
minifyClient, err := minifier.New(deps.ResourceSpec)
if err != nil {
return nil, err
}
return &Namespace{
deps: deps,
createClient: create.New(deps.ResourceSpec),
bundlerClient: bundler.New(deps.ResourceSpec),
integrityClient: integrity.New(deps.ResourceSpec),
minifyClient: minifyClient,
templatesClient: templates.New(deps.ResourceSpec, deps),
}, nil
}
var _ resource.ResourceFinder = (*Namespace)(nil)
// Namespace provides template functions for the "resources" namespace.
type Namespace struct {
deps *deps.Deps
createClient *create.Client
bundlerClient *bundler.Client
integrityClient *integrity.Client
minifyClient *minifier.Client
templatesClient *templates.Client
// We moved some CSS and JS related functions to the css and js package in Hugo 0.128.0.
// Keep this here until the deprecation period is over.
cssNs *css.Namespace
jsNs *js.Namespace
}
// Copy copies r to the new targetPath in s.
func (ns *Namespace) Copy(s any, r resource.Resource) (resource.Resource, error) {
targetPath, err := cast.ToStringE(s)
if err != nil {
panic(err)
}
return ns.createClient.Copy(r, targetPath)
}
// Get locates the filename given in Hugo's assets filesystem
// and creates a Resource object that can be used for further transformations.
func (ns *Namespace) Get(filename any) resource.Resource {
filenamestr, err := cast.ToStringE(filename)
if err != nil {
panic(err)
}
if filenamestr == "" {
return nil
}
r, err := ns.createClient.Get(filenamestr)
if err != nil {
panic(err)
}
return r
}
// GetRemote gets the URL (via HTTP(s)) in the first argument in args and creates Resource object that can be used for
// further transformations.
//
// A second argument may be provided with an option map.
//
// Note: This method does not return any error as a second return value,
// for any error situations the error can be checked in .Err.
func (ns *Namespace) GetRemote(args ...any) (resource.Resource, error) {
get := func(args ...any) (resource.Resource, error) {
if len(args) < 1 || len(args) > 2 {
return nil, errors.New("must provide an URL and optionally an options map")
}
urlstr, err := cast.ToStringE(args[0])
if err != nil {
return nil, err
}
var options map[string]any
if len(args) > 1 {
options, err = maps.ToStringMapE(args[1])
if err != nil {
return nil, err
}
}
return ns.createClient.FromRemote(urlstr, options)
}
r, err := get(args...)
if err != nil {
switch v := err.(type) {
case *create.HTTPError:
return nil, resource.NewResourceError(v, v.Data)
default:
return nil, resource.NewResourceError(err, nil)
}
}
return r, nil
}
// GetMatch finds the first Resource matching the given pattern, or nil if none found.
//
// It looks for files in the assets file system.
//
// See Match for a more complete explanation about the rules used.
func (ns *Namespace) GetMatch(pattern any) resource.Resource {
patternStr, err := cast.ToStringE(pattern)
if err != nil {
panic(err)
}
r, err := ns.createClient.GetMatch(patternStr)
if err != nil {
panic(err)
}
return r
}
// ByType returns resources of a given resource type (e.g. "image").
func (ns *Namespace) ByType(typ any) resource.Resources {
return ns.createClient.ByType(cast.ToString(typ))
}
// Match gets all resources matching the given base path prefix, e.g
// "*.png" will match all png files. The "*" does not match path delimiters (/),
// so if you organize your resources in sub-folders, you need to be explicit about it, e.g.:
// "images/*.png". To match any PNG image anywhere in the bundle you can do "**.png", and
// to match all PNG images below the images folder, use "images/**.jpg".
//
// The matching is case insensitive.
//
// Match matches by using the files name with path relative to the file system root
// with Unix style slashes (/) and no leading slash, e.g. "images/logo.png".
//
// See https://github.com/gobwas/glob for the full rules set.
//
// It looks for files in the assets file system.
//
// See Match for a more complete explanation about the rules used.
func (ns *Namespace) Match(pattern any) resource.Resources {
patternStr, err := cast.ToStringE(pattern)
if err != nil {
panic(err)
}
r, err := ns.createClient.Match(patternStr)
if err != nil {
panic(err)
}
return r
}
// Concat concatenates a slice of Resource objects. These resources must
// (currently) be of the same Media Type.
func (ns *Namespace) Concat(targetPathIn any, r any) (resource.Resource, error) {
targetPath, err := cast.ToStringE(targetPathIn)
if err != nil {
return nil, err
}
var rr resource.Resources
switch v := r.(type) {
case resource.Resources:
rr = v
case resource.ResourcesConverter:
rr = v.ToResources()
default:
return nil, fmt.Errorf("expected slice of Resource objects, received %T instead", r)
}
if len(rr) == 0 {
return nil, errors.New("must provide one or more Resource objects to concat")
}
return ns.bundlerClient.Concat(targetPath, rr)
}
// FromString creates a Resource from a string published to the relative target path.
func (ns *Namespace) FromString(targetPathIn, contentIn any) (resource.Resource, error) {
targetPath, err := cast.ToStringE(targetPathIn)
if err != nil {
return nil, err
}
content, err := cast.ToStringE(contentIn)
if err != nil {
return nil, err
}
return ns.createClient.FromString(targetPath, content)
}
// ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with
// the given data, and published to the relative target path.
func (ns *Namespace) ExecuteAsTemplate(ctx context.Context, args ...any) (resource.Resource, error) {
if len(args) != 3 {
return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object")
}
targetPath, err := cast.ToStringE(args[0])
if err != nil {
return nil, err
}
data := args[1]
r, ok := args[2].(resources.ResourceTransformer)
if !ok {
return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2])
}
return ns.templatesClient.ExecuteAsTemplate(ctx, r, targetPath, data)
}
// Fingerprint transforms the given Resource with a MD5 hash of the content in
// the RelPermalink and Permalink.
func (ns *Namespace) Fingerprint(args ...any) (resource.Resource, error) {
if len(args) < 1 {
return nil, errors.New("must provide a Resource object")
}
if len(args) > 2 {
return nil, errors.New("must not provide more arguments than Resource and hash algorithm")
}
var algo string
resIdx := 0
if len(args) == 2 {
resIdx = 1
var err error
algo, err = cast.ToStringE(args[0])
if err != nil {
return nil, err
}
}
r, ok := args[resIdx].(resources.ResourceTransformer)
if !ok {
return nil, fmt.Errorf("%T can not be transformed", args[resIdx])
}
return ns.integrityClient.Fingerprint(r, algo)
}
// Minify minifies the given Resource using the MediaType to pick the correct
// minifier.
func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) {
return ns.minifyClient.Minify(r)
}
// ToCSS converts the given Resource to CSS. You can optional provide an Options object
// as second argument. As an option, you can e.g. specify e.g. the target path (string)
// for the converted CSS resource.
// Deprecated: Moved to the css namespace in Hugo 0.128.0.
func (ns *Namespace) ToCSS(args ...any) (resource.Resource, error) {
hugo.Deprecate("resources.ToCSS", "Use css.Sass instead.", "v0.128.0")
return ns.cssNs.Sass(args...)
}
// PostCSS processes the given Resource with PostCSS.
// Deprecated: Moved to the css namespace in Hugo 0.128.0.
func (ns *Namespace) PostCSS(args ...any) (resource.Resource, error) {
hugo.Deprecate("resources.PostCSS", "Use css.PostCSS instead.", "v0.128.0")
return ns.cssNs.PostCSS(args...)
}
// PostProcess processes r after the build.
func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) {
return ns.deps.ResourceSpec.PostProcess(r)
}
// Babel processes the given Resource with Babel.
// Deprecated: Moved to the js namespace in Hugo 0.128.0.
func (ns *Namespace) Babel(args ...any) (resource.Resource, error) {
hugo.Deprecate("resources.Babel", "Use js.Babel.", "v0.128.0")
return ns.jsNs.Babel(args...)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/debug/init.go | tpl/debug/init.go | // Copyright 2020 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package debug
import (
"context"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/internal"
)
const name = "debug"
func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
ctx := New(d)
ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },
}
ns.AddMethodMapping(ctx.Dump,
nil,
[][2]string{
{`{{ $m := newScratch }}
{{ $m.Set "Hugo" "Rocks!" }}
{{ $m.Values | debug.Dump | safeHTML }}`, "{\n \"Hugo\": \"Rocks!\"\n}"},
},
)
// For internal use only. Used in tests.
ns.AddMethodMapping(ctx.TestDeprecationErr,
nil,
[][2]string{},
)
// For internal use only. Used in tests.
ns.AddMethodMapping(ctx.TestDeprecationInfo,
nil,
[][2]string{},
)
// For internal use only. Used in tests.
ns.AddMethodMapping(ctx.TestDeprecationWarn,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.Timer,
nil,
[][2]string{},
)
ns.AddMethodMapping(ctx.VisualizeSpaces,
nil,
[][2]string{},
)
return ns
}
internal.AddTemplateFuncsNamespace(f)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/debug/debug_integration_test.go | tpl/debug/debug_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 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 debug_test
import (
"testing"
"github.com/bep/logg"
"github.com/gohugoio/hugo/hugolib"
)
func TestTimer(t *testing.T) {
files := `
-- hugo.toml --
baseURL = "https://example.org/"
disableKinds = ["taxonomy", "term"]
-- layouts/home.html --
{{ range seq 5 }}
{{ $t := debug.Timer "foo" }}
{{ seq 1 1000 }}
{{ $t.Stop }}
{{ end }}
`
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
LogLevel: logg.LevelInfo,
},
).Build()
b.AssertLogContains("timer: name foo count 5 duration")
}
func TestDebugDumpPage(t *testing.T) {
files := `
-- hugo.toml --
baseURL = "https://example.org/"
disableLiveReload = true
[taxonomies]
tag = "tags"
-- content/_index.md --
---
title: "The Index"
date: 2012-03-15
---
-- content/p1.md --
---
title: "The First"
tags: ["a", "b"]
---
-- layouts/list.html --
Dump: {{ debug.Dump . | safeHTML }}
Dump Site: {{ debug.Dump site }}
Dum site.Taxonomies: {{ debug.Dump site.Taxonomies | safeHTML }}
-- layouts/single.html --
Dump: {{ debug.Dump . | safeHTML }}
`
b := hugolib.TestRunning(t, files)
b.AssertFileContent("public/index.html", "Dump: {\n \"Date\": \"2012-03-15T00:00:00Z\"")
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/debug/debug.go | tpl/debug/debug.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 debug provides template functions to help debugging templates.
package debug
import (
"encoding/json"
"sort"
"sync"
"time"
"github.com/bep/logg"
"github.com/spf13/cast"
"github.com/yuin/goldmark/util"
"github.com/gohugoio/hugo/common/hugo"
"github.com/gohugoio/hugo/deps"
)
// New returns a new instance of the debug-namespaced template functions.
func New(d *deps.Deps) *Namespace {
ns := &Namespace{}
if d.Log.Level() <= logg.LevelInfo {
ns.timers = make(map[string][]*timer)
}
if ns.timers == nil {
return ns
}
l := d.Log.InfoCommand("timer")
d.BuildEndListeners.Add(func(...any) bool {
type data struct {
Name string
Count int
Average time.Duration
Median time.Duration
Duration time.Duration
}
var timersSorted []data
for k, v := range ns.timers {
var total time.Duration
var median time.Duration
sort.Slice(v, func(i, j int) bool {
return v[i].elapsed < v[j].elapsed
})
if len(v) > 0 {
median = v[len(v)/2].elapsed
}
for _, t := range v {
// Stop any running timers.
t.Stop()
total += t.elapsed
}
average := total / time.Duration(len(v))
timersSorted = append(timersSorted, data{k, len(v), average, median, total})
}
sort.Slice(timersSorted, func(i, j int) bool {
// Sort it so the slowest gets printed last.
return timersSorted[i].Duration < timersSorted[j].Duration
})
for _, t := range timersSorted {
l.WithField("name", t.Name).WithField("count", t.Count).
WithField("duration", t.Duration).
WithField("average", t.Average).
WithField("median", t.Median).Logf("")
}
ns.timers = make(map[string][]*timer)
return false
})
return ns
}
// Namespace provides template functions for the "debug" namespace.
type Namespace struct {
timersMu sync.Mutex
timers map[string][]*timer
}
// Dump returns a object dump of val as a string.
// Note that not every value passed to Dump will print so nicely, but
// we'll improve on that.
//
// We recommend using the "go" Chroma lexer to format the output
// nicely.
//
// Also note that the output from Dump may change from Hugo version to the next,
// so don't depend on a specific output.
func (ns *Namespace) Dump(val any) string {
b, err := json.MarshalIndent(val, "", " ")
if err != nil {
return ""
}
return string(b)
}
// VisualizeSpaces returns a string with spaces replaced by a visible string.
func (ns *Namespace) VisualizeSpaces(val any) string {
s := cast.ToString(val)
return string(util.VisualizeSpaces([]byte(s)))
}
func (ns *Namespace) Timer(name string) Timer {
if ns.timers == nil {
return nopTimer
}
ns.timersMu.Lock()
defer ns.timersMu.Unlock()
t := &timer{start: time.Now()}
ns.timers[name] = append(ns.timers[name], t)
return t
}
var nopTimer = nopTimerImpl{}
type nopTimerImpl struct{}
func (nopTimerImpl) Stop() string {
return ""
}
// Timer is a timer that can be stopped.
type Timer interface {
// Stop stops the timer and returns an empty string.
// Stop can be called multiple times, but only the first call will stop the timer.
// If Stop is not called, the timer will be stopped when the build ends.
Stop() string
}
type timer struct {
start time.Time
elapsed time.Duration
stopOnce sync.Once
}
func (t *timer) Stop() string {
t.stopOnce.Do(func() {
t.elapsed = time.Since(t.start)
})
// This is used in templates, we need to return something.
return ""
}
// Internal template func, used in tests only.
func (ns *Namespace) TestDeprecationInfo(item, alternative string) string {
v := hugo.CurrentVersion
hugo.Deprecate(item, alternative, v.String())
return ""
}
// Internal template func, used in tests only.
func (ns *Namespace) TestDeprecationWarn(item, alternative string) string {
v := hugo.CurrentVersion
v.Minor -= 3
hugo.Deprecate(item, alternative, v.String())
return ""
}
// Internal template func, used in tests only.
func (ns *Namespace) TestDeprecationErr(item, alternative string) string {
v := hugo.CurrentVersion
v.Minor -= 15
hugo.Deprecate(item, alternative, v.String())
return ""
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/openapi/docs.go | tpl/openapi/docs.go | // Package openapi provides functions for generating OpenAPI (Swagger) documentation.
package openapi
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/openapi/openapi3/init.go | tpl/openapi/openapi3/init.go | // Copyright 2020 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package openapi3
import (
"context"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/internal"
resourcestpl "github.com/gohugoio/hugo/tpl/resources"
)
const name = "openapi3"
func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
ctx := New(d)
ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },
OnCreated: func(m map[string]any) {
for _, v := range m {
switch v := v.(type) {
case *resourcestpl.Namespace:
ctx.resourcesNs = v
}
}
if ctx.resourcesNs == nil {
panic("resources namespace not found")
}
},
}
ns.AddMethodMapping(ctx.Unmarshal,
nil,
[][2]string{},
)
return ns
}
internal.AddTemplateFuncsNamespace(f)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/openapi/openapi3/openapi3.go | tpl/openapi/openapi3/openapi3.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 openapi3 provides functions for generating OpenAPI v3 (Swagger) documentation.
package openapi3
import (
"context"
"errors"
"fmt"
"io"
"net/url"
"path"
"path/filepath"
"strings"
kopenapi3 "github.com/getkin/kin-openapi/openapi3"
"github.com/gohugoio/hugo/cache/dynacache"
"github.com/gohugoio/hugo/common/hashing"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/parser/metadecoders"
"github.com/gohugoio/hugo/resources"
"github.com/gohugoio/hugo/resources/resource"
resourcestpl "github.com/gohugoio/hugo/tpl/resources"
"github.com/mitchellh/mapstructure"
)
// New returns a new instance of the openapi3-namespaced template functions.
func New(deps *deps.Deps) *Namespace {
return &Namespace{
cache: dynacache.GetOrCreatePartition[string, *OpenAPIDocument](deps.MemCache, "/tmpl/openapi3", dynacache.OptionsPartition{Weight: 30, ClearWhen: dynacache.ClearOnChange}),
deps: deps,
}
}
// Namespace provides template functions for the "openapi3".
type Namespace struct {
cache *dynacache.Partition[string, *OpenAPIDocument]
deps *deps.Deps
resourcesNs *resourcestpl.Namespace
}
// OpenAPIDocument represents an OpenAPI 3 document.
type OpenAPIDocument struct {
*kopenapi3.T
identityGroup identity.Identity
}
func (o *OpenAPIDocument) GetIdentityGroup() identity.Identity {
return o.identityGroup
}
type unmarshalOptions struct {
// Options passed to resources.GetRemote when resolving remote $ref.
GetRemote map[string]any
}
// Unmarshal unmarshals the given resource into an OpenAPI 3 document.
func (ns *Namespace) Unmarshal(ctx context.Context, args ...any) (*OpenAPIDocument, error) {
if len(args) < 1 || len(args) > 2 {
return nil, errors.New("must provide a Resource and optionally an options map")
}
r := args[0].(resource.UnmarshableResource)
key := r.Key()
if key == "" {
return nil, errors.New("no Key set in Resource")
}
var opts unmarshalOptions
if len(args) > 1 {
optsm, err := maps.ToStringMapE(args[1])
if err != nil {
return nil, err
}
if err := mapstructure.WeakDecode(optsm, &opts); err != nil {
return nil, err
}
key += "_" + hashing.HashString(optsm)
}
v, err := ns.cache.GetOrCreate(key, func(string) (*OpenAPIDocument, error) {
f := metadecoders.FormatFromStrings(r.MediaType().Suffixes()...)
if f == "" {
return nil, fmt.Errorf("MIME %q not supported", r.MediaType())
}
reader, err := r.ReadSeekCloser()
if err != nil {
return nil, err
}
defer reader.Close()
b, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
s := &kopenapi3.T{}
switch f {
case metadecoders.YAML:
err = metadecoders.UnmarshalYaml(b, s)
default:
err = metadecoders.Default.UnmarshalTo(b, f, s)
}
if err != nil {
return nil, err
}
var resourcePath string
if res, ok := r.(resource.Resource); ok {
resourcePath = resources.InternalResourceSourcePath(res)
}
var relDir string
if resourcePath != "" {
if rel, ok := ns.deps.Assets.MakePathRelative(filepath.FromSlash(resourcePath), true); ok {
relDir = filepath.Dir(rel)
}
}
var idm identity.Manager = identity.NopManager
if v := identity.GetDependencyManager(r); v != nil {
idm = v
}
idg := identity.FirstIdentity(r)
resolver := &refResolver{
ctx: ctx,
idm: idm,
opts: opts,
relBase: filepath.ToSlash(relDir),
ns: ns,
}
loader := kopenapi3.NewLoader()
loader.IsExternalRefsAllowed = true
loader.ReadFromURIFunc = resolver.resolveExternalRef
err = loader.ResolveRefsIn(s, nil)
return &OpenAPIDocument{T: s, identityGroup: idg}, err
})
if err != nil {
return nil, err
}
return v, nil
}
type refResolver struct {
ctx context.Context
idm identity.Manager
opts unmarshalOptions
relBase string
ns *Namespace
}
// resolveExternalRef resolves external references in OpenAPI documents by either fetching
// remote URLs or loading local files from the assets directory, depending on the reference location.
func (r *refResolver) resolveExternalRef(loader *kopenapi3.Loader, loc *url.URL) ([]byte, error) {
if loc.Scheme != "" && loc.Host != "" {
res, err := r.ns.resourcesNs.GetRemote(loc.String(), r.opts.GetRemote)
if err != nil {
return nil, fmt.Errorf("failed to get remote ref %q: %w", loc.String(), err)
}
content, err := resources.InternalResourceSourceContent(r.ctx, res)
if err != nil {
return nil, fmt.Errorf("failed to read remote ref %q: %w", loc.String(), err)
}
r.idm.AddIdentity(identity.FirstIdentity(res))
return []byte(content), nil
}
var filename string
if strings.HasPrefix(loc.Path, "/") {
filename = loc.Path
} else {
filename = path.Join(r.relBase, loc.Path)
}
res := r.ns.resourcesNs.Get(filename)
if res == nil {
return nil, fmt.Errorf("local ref %q not found", loc.String())
}
content, err := resources.InternalResourceSourceContent(r.ctx, res)
if err != nil {
return nil, fmt.Errorf("failed to read local ref %q: %w", loc.String(), err)
}
r.idm.AddIdentity(identity.FirstIdentity(res))
return []byte(content), nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/tpl/openapi/openapi3/openapi3_integration_test.go | tpl/openapi/openapi3/openapi3_integration_test.go | // Copyright 2021 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package openapi3_test
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gohugoio/hugo/hugolib"
)
func TestUnmarshal(t *testing.T) {
t.Parallel()
files := `
-- assets/api/myapi.yaml --
openapi: 3.0.0
info:
title: Sample API
description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
version: 0.1.9
servers:
- url: http://api.example.com/v1
description: Optional server description, e.g. Main (production) server
- url: http://staging-api.example.com
description: Optional server description, e.g. Internal staging server for testing
paths:
/users:
get:
summary: Returns a list of users.
description: Optional extended description in CommonMark or HTML.
responses:
'200': # status code
description: A JSON array of user names
content:
application/json:
schema:
type: array
items:
type: string
-- hugo.toml --
baseURL = 'http://example.com/'
disableLiveReload = true
-- layouts/home.html --
{{ $api := resources.Get "api/myapi.yaml" | openapi3.Unmarshal }}
API: {{ $api.Info.Title | safeHTML }}
`
b := hugolib.TestRunning(t, files)
b.AssertFileContent("public/index.html", `API: Sample API`)
b.
EditFileReplaceFunc("assets/api/myapi.yaml", func(s string) string { return strings.ReplaceAll(s, "Sample API", "Hugo API") }).
Build()
b.AssertFileContent("public/index.html", `API: Hugo API`)
}
// Test data borrowed/adapted from https://github.com/getkin/kin-openapi/tree/master/openapi3/testdata/refInLocalRef
// The templates below would be simpler if kin-openapi's T would serialize to JSON better, see https://github.com/getkin/kin-openapi/issues/561
const refLocalTemplate = `
-- hugo.toml --
baseURL = 'http://example.com/'
disableKinds = ["page", "section", "taxonomy", "term", "sitemap", "robotsTXT", "404"]
disableLiveReload = true
[HTTPCache]
[HTTPCache.cache]
[HTTPCache.cache.for]
includes = ['**']
[[HTTPCache.polls]]
high = '100ms'
low = '50ms'
[HTTPCache.polls.for]
includes = ['**']
-- assets/api/myapi.json --
{
"openapi": "3.0.3",
"info": {
"title": "Reference in reference example",
"version": "1.0.0"
},
"paths": {
"/api/test/ref/in/ref": {
"post": {
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties" : {
"data": {
"$ref": "#/components/schemas/Request"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"$ref": "messages/response.json"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Request": {
"$ref": "messages/request.json"
}
}
}
}
-- assets/api/messages/request.json --
{
"type": "object",
"required": [
"definition_reference"
],
"properties": {
"definition_reference": {
"$ref": "./data.json"
}
}
}
-- assets/api/messages/response.json --
{
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "uint64"
}
}
}
-- assets/api/messages/data.json --
{
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int32"
},
"ref_prop_part": {
"$ref": "DATAPART_REF"
}
}
}
-- assets/api/messages/dataPart.json --
{
"type": "object",
"properties": {
"idPart": {
"type": "integer",
"format": "int64"
}
}
}
-- layouts/home.html --
{{ $getremote := dict
"method" "post"
"key" time.Now.UnixNano
}}
{{ $opts := dict
"getremote" $getremote
}}
{{ with resources.Get "api/myapi.json" }}
{{ with openapi3.Unmarshal . $opts }}
Title: {{ .Info.Title | safeHTML }}
{{ range $k, $v := .Paths.Map }}
{{ $post := index $v.Post }}
{{ with index $post.RequestBody.Value.Content }}
{{ $mt := (index . "application/json")}}
{{ $data := index $mt.Schema.Value.Properties "data" }}
RequestBody: {{ template "printschema" $mt.Schema.Value }}$
{{ end }}
{{ $response := index (index $post.Responses.Map "200").Value.Content "application/json" }}
Response: {{ template "printschema" $response.Schema.Value }}
{{ end }}
{{ end }}
{{ end }}
{{ define "printschema" }}{{ with .Format}}Format: {{ . }}|{{ end }}{{ with .Properties }} Properties: {{ range $k, $v := . }}{{ $k}}: {{ template "printitems" . -}}{{ end }}{{ end -}}${{ end }}
{{ define "printitems" }}{{ if eq (printf "%T" .) "*openapi3.SchemaRef" }}{{ template "printschema" .Value }}{{ else }}{{ template "printitem" . -}}{{ end -}}{{ end }}
{{ define "printitem" }}{{ printf "%T: %s" . (.|debug.Dump) | safeHTML }}{{ end }}
`
func TestUnmarshalRefLocal(t *testing.T) {
files := strings.ReplaceAll(refLocalTemplate, "DATAPART_REF", "./dataPart.json")
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html",
`Reference in reference example`,
"RequestBody: Properties: data: Properties: definition_reference: Properties: id: Format: int32|$ref_prop_part: Properties: idPart: Format: int64|$",
"Response: Properties: id: Format: uint64|$",
)
}
func TestUnmarshalRefLocalEdit(t *testing.T) {
files := strings.ReplaceAll(refLocalTemplate, "DATAPART_REF", "./dataPart.json")
b := hugolib.TestRunning(t, files)
b.AssertFileContent("public/index.html",
"RequestBody: Properties: data: Properties: definition_reference: Properties: id: Format: int32|$ref_prop_part: Properties: idPart: Format: int64|$",
)
b.EditFileReplaceAll("assets/api/messages/dataPart.json", "int64", "int8").Build()
b.AssertFileContent("public/index.html",
"RequestBody: Properties: data: Properties: definition_reference: Properties: id: Format: int32|$ref_prop_part: Properties: idPart: Format: int8|$",
)
}
func TestUnmarshalRefRemote(t *testing.T) {
createFiles := func(t *testing.T) string {
counter := 0
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && r.URL.Path == "/api/messages/dataPart.json" {
n := 8
// This endpoint will also be called by the poller, so we distinguish
// between the first and subsequent calls.
if counter > 0 {
n = 16
}
counter++
w.Header().Set("Content-Type", "application/json")
response := fmt.Sprintf(`{
"type": "object",
"properties": {
"idPart": {
"type": "integer",
"format": "int%d"
}
}
}`, n)
w.Write([]byte(response))
return
}
http.Error(w, "Not found", http.StatusNotFound)
}))
t.Cleanup(func() {
ts.Close()
})
dataPartRef := ts.URL + "/api/messages/dataPart.json"
return strings.ReplaceAll(refLocalTemplate, "DATAPART_REF", dataPartRef)
}
t.Run("Build", func(t *testing.T) {
b := hugolib.Test(t, createFiles(t))
b.AssertFileContent("public/index.html",
`Reference in reference example`,
"RequestBody: Properties: data: Properties: definition_reference: Properties: id: Format: int32|$ref_prop_part: Properties: idPart: Format: int8|$",
"Response: Properties: id: Format: uint64|$",
)
})
t.Run("Rebuild", func(t *testing.T) {
b := hugolib.TestRunning(t, createFiles(t))
b.AssertFileContent("public/index.html",
"idPart: Format: int8|$",
)
// Rebuild triggered by remote polling.
time.Sleep(800 * time.Millisecond)
b.AssertFileContent("public/index.html",
"idPart: Format: int16|$",
)
})
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/pathspec.go | helpers/pathspec.go | // Copyright 2016-present The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"strings"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugolib/filesystems"
"github.com/gohugoio/hugo/hugolib/paths"
)
// PathSpec holds methods that decides how paths in URLs and files in Hugo should look like.
type PathSpec struct {
*paths.Paths
*filesystems.BaseFs
ProcessingStats *ProcessingStats
// The file systems to use
Fs *hugofs.Fs
}
// NewPathSpec creates a new PathSpec from the given filesystems and language.
// If an existing BaseFs is provided, parts of that is reused.
func NewPathSpec(fs *hugofs.Fs, cfg config.AllProvider, logger loggers.Logger, baseBaseFs *filesystems.BaseFs) (*PathSpec, error) {
p, err := paths.New(fs, cfg)
if err != nil {
return nil, err
}
var options []func(*filesystems.BaseFs) error
if baseBaseFs != nil {
options = []func(*filesystems.BaseFs) error{
filesystems.WithBaseFs(baseBaseFs),
}
}
bfs, err := filesystems.NewBase(p, logger, options...)
if err != nil {
return nil, err
}
ps := &PathSpec{
Paths: p,
BaseFs: bfs,
Fs: fs,
ProcessingStats: NewProcessingStats(p.Lang()),
}
return ps, nil
}
// PermalinkForBaseURL creates a permalink from the given link and baseURL.
func (p *PathSpec) PermalinkForBaseURL(link, baseURL string) string {
return baseURL + strings.TrimPrefix(link, "/")
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/general.go | helpers/general.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 helpers
import (
"bytes"
"fmt"
"io"
"net"
"os"
"path/filepath"
"slices"
"strings"
"unicode"
"unicode/utf8"
bp "github.com/gohugoio/hugo/bufferpool"
"github.com/spf13/afero"
"github.com/jdkato/prose/transform"
)
// FilePathSeparator as defined by os.Separator.
const FilePathSeparator = string(filepath.Separator)
// TCPListen starts listening on a valid TCP port.
func TCPListen() (net.Listener, *net.TCPAddr, error) {
l, err := net.Listen("tcp", ":0")
if err != nil {
return nil, nil, err
}
addr := l.Addr()
if a, ok := addr.(*net.TCPAddr); ok {
return l, a, nil
}
l.Close()
return nil, nil, fmt.Errorf("unable to obtain a valid tcp port: %v", addr)
}
// FirstUpper returns a string with the first character as upper case.
func FirstUpper(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
}
// ReaderToBytes takes an io.Reader argument, reads from it
// and returns bytes.
func ReaderToBytes(lines io.Reader) []byte {
if lines == nil {
return []byte{}
}
b := bp.GetBuffer()
defer bp.PutBuffer(b)
b.ReadFrom(lines)
bc := make([]byte, b.Len())
copy(bc, b.Bytes())
return bc
}
// ReaderToString is the same as ReaderToBytes, but returns a string.
func ReaderToString(lines io.Reader) string {
if lines == nil {
return ""
}
b := bp.GetBuffer()
defer bp.PutBuffer(b)
b.ReadFrom(lines)
return b.String()
}
// ReaderContains reports whether subslice is within r.
func ReaderContains(r io.Reader, subslice []byte) bool {
if r == nil || len(subslice) == 0 {
return false
}
bufflen := len(subslice) * 4
halflen := bufflen / 2
buff := make([]byte, bufflen)
var err error
var n, i int
for {
i++
if i == 1 {
n, err = io.ReadAtLeast(r, buff[:halflen], halflen)
} else {
if i != 2 {
// shift left to catch overlapping matches
copy(buff[:], buff[halflen:])
}
n, err = io.ReadAtLeast(r, buff[halflen:], halflen)
}
if n > 0 && bytes.Contains(buff, subslice) {
return true
}
if err != nil {
break
}
}
return false
}
// GetTitleFunc returns a func that can be used to transform a string to
// title case.
//
// # The supported styles are
//
// - "Go" (strings.Title)
// - "AP" (see https://www.apstylebook.com/)
// - "Chicago" (see https://www.chicagomanualofstyle.org/home.html)
// - "FirstUpper" (only the first character is upper case)
// - "None" (no transformation)
//
// If an unknown or empty style is provided, AP style is what you get.
func GetTitleFunc(style string) func(s string) string {
switch strings.ToLower(style) {
case "go":
//lint:ignore SA1019 keep for now.
return strings.Title
case "chicago":
tc := transform.NewTitleConverter(transform.ChicagoStyle)
return tc.Title
case "none":
return func(s string) string { return s }
case "firstupper":
return FirstUpper
default:
tc := transform.NewTitleConverter(transform.APStyle)
return tc.Title
}
}
// HasStringsPrefix tests whether the string slice s begins with prefix slice s.
func HasStringsPrefix(s, prefix []string) bool {
return len(s) >= len(prefix) && compareStringSlices(s[0:len(prefix)], prefix)
}
// HasStringsSuffix tests whether the string slice s ends with suffix slice s.
func HasStringsSuffix(s, suffix []string) bool {
return len(s) >= len(suffix) && compareStringSlices(s[len(s)-len(suffix):], suffix)
}
func compareStringSlices(a, b []string) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return slices.Equal(a, b)
}
// SliceToLower goes through the source slice and lowers all values.
func SliceToLower(s []string) []string {
if s == nil {
return nil
}
l := make([]string, len(s))
for i, v := range s {
l[i] = strings.ToLower(v)
}
return l
}
// StringSliceToList formats a string slice into a human-readable list.
// It joins the elements of the slice s with commas, using an Oxford comma,
// and precedes the final element with the conjunction c.
func StringSliceToList(s []string, c string) string {
const defaultConjunction = "and"
if c == "" {
c = defaultConjunction
}
if len(s) == 0 {
return ""
}
if len(s) == 1 {
return s[0]
}
if len(s) == 2 {
return fmt.Sprintf("%s %s %s", s[0], c, s[1])
}
return fmt.Sprintf("%s, %s %s", strings.Join(s[:len(s)-1], ", "), c, s[len(s)-1])
}
// IsWhitespace determines if the given rune is whitespace.
func IsWhitespace(r rune) bool {
return r == ' ' || r == '\t' || r == '\n' || r == '\r'
}
// PrintFs prints the given filesystem to the given writer starting from the given path.
// This is useful for debugging.
func PrintFs(fs afero.Fs, path string, w io.Writer) {
if fs == nil {
return
}
afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error {
if err != nil {
panic(fmt.Sprintf("error: path %q: %s", path, err))
}
path = filepath.ToSlash(path)
if path == "" {
path = "."
}
fmt.Fprintln(w, path, info.IsDir())
return nil
})
}
// FormatByteCount pretty formats b.
func FormatByteCount(bc uint64) string {
const (
Gigabyte = 1 << 30
Megabyte = 1 << 20
Kilobyte = 1 << 10
)
switch {
case bc > Gigabyte || -bc > Gigabyte:
return fmt.Sprintf("%.2f GB", float64(bc)/Gigabyte)
case bc > Megabyte || -bc > Megabyte:
return fmt.Sprintf("%.2f MB", float64(bc)/Megabyte)
case bc > Kilobyte || -bc > Kilobyte:
return fmt.Sprintf("%.2f KB", float64(bc)/Kilobyte)
}
return fmt.Sprintf("%d B", bc)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/path.go | helpers/path.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 helpers
import (
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
"github.com/gohugoio/go-radix"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/common/text"
"github.com/gohugoio/hugo/htesting"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/common/hugio"
"github.com/spf13/afero"
)
// MakePath takes a string with any characters and replace it
// so the string could be used in a path.
// It does so by creating a Unicode-sanitized string, with the spaces replaced,
// whilst preserving the original casing of the string.
// E.g. Social Media -> Social-Media
func (p *PathSpec) MakePath(s string) string {
s = paths.Sanitize(s)
if p.Cfg.RemovePathAccents() {
s = text.RemoveAccentsString(s)
}
return s
}
// MakePathsSanitized applies MakePathSanitized on every item in the slice
func (p *PathSpec) MakePathsSanitized(paths []string) {
for i, path := range paths {
paths[i] = p.MakePathSanitized(path)
}
}
// MakePathSanitized creates a Unicode-sanitized string, with the spaces replaced
func (p *PathSpec) MakePathSanitized(s string) string {
if p.Cfg.DisablePathToLower() {
return p.MakePath(s)
}
return strings.ToLower(p.MakePath(s))
}
// MakeTitle converts the path given to a suitable title, trimming whitespace
// and replacing hyphens with whitespace.
func MakeTitle(inpath string) string {
return strings.Replace(strings.TrimSpace(inpath), "-", " ", -1)
}
// MakeTitleInPath converts the path given to a suitable title, trimming whitespace
func MakePathRelative(inPath string, possibleDirectories ...string) (string, error) {
for _, currentPath := range possibleDirectories {
if after, ok := strings.CutPrefix(inPath, currentPath); ok {
return after, nil
}
}
return inPath, errors.New("can't extract relative path, unknown prefix")
}
// Should be good enough for Hugo.
var isFileRe = regexp.MustCompile(`.*\..{1,6}$`)
// GetDottedRelativePath expects a relative path starting after the content directory.
// It returns a relative path with dots ("..") navigating up the path structure.
func GetDottedRelativePath(inPath string) string {
inPath = path.Clean(filepath.ToSlash(inPath))
if inPath == "." {
return "./"
}
if !isFileRe.MatchString(inPath) && !strings.HasSuffix(inPath, "/") {
inPath += "/"
}
if !strings.HasPrefix(inPath, "/") {
inPath = "/" + inPath
}
dir, _ := path.Split(inPath)
sectionCount := strings.Count(dir, "/")
if sectionCount == 0 || dir == "/" {
return "./"
}
var dottedPath string
for i := 1; i < sectionCount; i++ {
dottedPath += "../"
}
return dottedPath
}
type NamedSlice struct {
Name string
Slice []string
}
func (n NamedSlice) String() string {
if len(n.Slice) == 0 {
return n.Name
}
return fmt.Sprintf("%s%s{%s}", n.Name, FilePathSeparator, strings.Join(n.Slice, ","))
}
// ExtractAndGroupRootPaths extracts and groups root paths from the supplied list of paths.
// Note that the in slice will be sorted in place.
func ExtractAndGroupRootPaths(in []string) []string {
if len(in) == 0 {
return nil
}
const maxGroups = 5
const maxRootGroups = 10
sort.Strings(in)
var groups []string
tree := radix.New[[]string]()
LOOP:
for _, s := range in {
s = filepath.ToSlash(s)
if ss, g, found := tree.LongestPrefix(s); found {
if len(g) > maxGroups {
continue LOOP
}
parts := strings.Split(strings.TrimPrefix(strings.TrimPrefix(s, ss), "/"), "/")
if len(parts) > 0 && parts[0] != "" && !slices.Contains(g, parts[0]) {
g = append(g, parts[0])
tree.Insert(ss, g)
}
} else {
tree.Insert(s, []string{})
}
}
var collect radix.WalkFn[[]string] = func(s string, g []string) (radix.WalkFlag, []string, error) {
if len(g) == 0 {
groups = append(groups, s)
return radix.WalkContinue, nil, nil
}
if len(g) == 1 {
groups = append(groups, path.Join(s, g[0]))
return radix.WalkContinue, nil, nil
}
var sb strings.Builder
sb.WriteString(s)
// This is used to print "Watching for changes in /Users/bep/dev/sites/hugotestsites/60k/content/{section0,section1,section10..."
// Having too many groups here is not helpful.
if len(g) > maxGroups {
// This will modify the slice in the tree, but that is OK since we are done with it.
g = g[:maxGroups]
g = append(g, "...")
}
sb.WriteString("/{")
sb.WriteString(strings.Join(g, ","))
sb.WriteString("}")
groups = append(groups, sb.String())
return radix.WalkContinue, nil, nil
}
tree.Walk(collect)
// Limit the total number of root groups to keep output manageable
if len(groups) > maxRootGroups {
remaining := len(groups) - maxRootGroups
groups = groups[:maxRootGroups]
groups = append(groups, fmt.Sprintf("... and %d more", remaining))
}
return groups
}
// FindCWD returns the current working directory from where the Hugo
// executable is run.
func FindCWD() (string, error) {
serverFile, err := filepath.Abs(os.Args[0])
if err != nil {
return "", fmt.Errorf("can't get absolute path for executable: %v", err)
}
path := filepath.Dir(serverFile)
realFile, err := filepath.EvalSymlinks(serverFile)
if err != nil {
if _, err = os.Stat(serverFile + ".exe"); err == nil {
realFile = filepath.Clean(serverFile + ".exe")
}
}
if err == nil && realFile != serverFile {
path = filepath.Dir(realFile)
}
return path, nil
}
// Walk walks the file tree rooted at root, calling walkFn for each file or
// directory in the tree, including root.
func Walk(fs afero.Fs, root string, walker hugofs.WalkFunc) error {
if _, isOs := fs.(*afero.OsFs); isOs {
fs = hugofs.NewBaseFileDecorator(fs)
}
w := hugofs.NewWalkway(hugofs.WalkwayConfig{
Fs: fs,
Root: root,
WalkFn: walker,
})
return w.Walk()
}
// SafeWriteToDisk is the same as WriteToDisk
// but it also checks to see if file/directory already exists.
func SafeWriteToDisk(inpath string, r io.Reader, fs afero.Fs) (err error) {
return afero.SafeWriteReader(fs, inpath, r)
}
// WriteToDisk writes content to disk.
func WriteToDisk(inpath string, r io.Reader, fs afero.Fs) (err error) {
return afero.WriteReader(fs, inpath, r)
}
// OpenFilesForWriting opens all the given filenames for writing.
func OpenFilesForWriting(fs afero.Fs, filenames ...string) (io.WriteCloser, error) {
var writeClosers []io.WriteCloser
for _, filename := range filenames {
f, err := OpenFileForWriting(fs, filename)
if err != nil {
for _, wc := range writeClosers {
wc.Close()
}
return nil, err
}
writeClosers = append(writeClosers, f)
}
return hugio.NewMultiWriteCloser(writeClosers...), nil
}
// OpenFileForWriting opens or creates the given file. If the target directory
// does not exist, it gets created.
func OpenFileForWriting(fs afero.Fs, filename string) (afero.File, error) {
filename = filepath.Clean(filename)
// Create will truncate if file already exists.
// os.Create will create any new files with mode 0666 (before umask).
f, err := fs.Create(filename)
if err != nil {
if !herrors.IsNotExist(err) {
return nil, err
}
if err = fs.MkdirAll(filepath.Dir(filename), 0o777); err != nil { // before umask
return nil, err
}
f, err = fs.Create(filename)
}
return f, err
}
// GetCacheDir returns a cache dir from the given filesystem and config.
// The dir will be created if it does not exist.
func GetCacheDir(fs afero.Fs, cacheDir string) (string, error) {
cacheDir = cacheDirDefault(cacheDir)
if cacheDir != "" {
exists, err := DirExists(cacheDir, fs)
if err != nil {
return "", err
}
if !exists {
err := fs.MkdirAll(cacheDir, 0o777) // Before umask
if err != nil {
return "", fmt.Errorf("failed to create cache dir: %w", err)
}
}
return cacheDir, nil
}
const hugoCacheBase = "hugo_cache"
// Avoid filling up the home dir with Hugo cache dirs from development.
if !htesting.IsTest {
userCacheDir, err := os.UserCacheDir()
if err == nil {
cacheDir := filepath.Join(userCacheDir, hugoCacheBase)
if err := fs.Mkdir(cacheDir, 0o777); err == nil || os.IsExist(err) {
return cacheDir, nil
}
}
}
// Fall back to a cache in /tmp.
userName := os.Getenv("USER")
if userName != "" {
return GetTempDir(hugoCacheBase+"_"+userName, fs), nil
} else {
return GetTempDir(hugoCacheBase, fs), nil
}
}
func cacheDirDefault(cacheDir string) string {
// Always use the cacheDir config if set.
if len(cacheDir) > 1 {
return addTrailingFileSeparator(cacheDir)
}
// See Issue #8714.
// Turns out that Cloudflare also sets NETLIFY=true in its build environment,
// but all of these 3 should not give any false positives.
if os.Getenv("NETLIFY") == "true" && os.Getenv("PULL_REQUEST") != "" && os.Getenv("DEPLOY_PRIME_URL") != "" {
// Netlify's cache behavior is not documented, the currently best example
// is this project:
// https://github.com/philhawksworth/content-shards/blob/master/gulpfile.js
return "/opt/build/cache/hugo_cache/"
}
// This will fall back to an hugo_cache folder in either os.UserCacheDir or the tmp dir, which should work fine for most CI
// providers. See this for a working CircleCI setup:
// https://github.com/bep/hugo-sass-test/blob/6c3960a8f4b90e8938228688bc49bdcdd6b2d99e/.circleci/config.yml
// If not, they can set the HUGO_CACHEDIR environment variable or cacheDir config key.
return ""
}
func addTrailingFileSeparator(s string) string {
if !strings.HasSuffix(s, FilePathSeparator) {
s = s + FilePathSeparator
}
return s
}
// GetTempDir returns a temporary directory with the given sub path.
func GetTempDir(subPath string, fs afero.Fs) string {
return afero.GetTempDir(fs, subPath)
}
// DirExists checks if a path exists and is a directory.
func DirExists(path string, fs afero.Fs) (bool, error) {
return afero.DirExists(fs, path)
}
// IsDir checks if a given path is a directory.
func IsDir(path string, fs afero.Fs) (bool, error) {
return afero.IsDir(fs, path)
}
// IsEmpty checks if a given path is empty, meaning it doesn't contain any regular files.
func IsEmpty(path string, fs afero.Fs) (bool, error) {
var hasFile bool
err := afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
hasFile = true
return filepath.SkipDir
})
return !hasFile, err
}
// Exists checks if a file or directory exists.
func Exists(path string, fs afero.Fs) (bool, error) {
return afero.Exists(fs, path)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/content_test.go | helpers/content_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 helpers_test
import (
"bytes"
"html/template"
"strings"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/helpers"
)
func TestTrimShortHTML(t *testing.T) {
tests := []struct {
markup string
input []byte
output []byte
}{
{"markdown", []byte(""), []byte("")},
{"markdown", []byte("Plain text"), []byte("Plain text")},
{"markdown", []byte("<p>Simple paragraph</p>"), []byte("Simple paragraph")},
{"markdown", []byte("\n \n \t <p> \t Whitespace\nHTML \n\t </p>\n\t"), []byte("Whitespace\nHTML")},
{"markdown", []byte("<p>Multiple</p><p>paragraphs</p>"), []byte("<p>Multiple</p><p>paragraphs</p>")},
{"markdown", []byte("<p>Nested<p>paragraphs</p></p>"), []byte("<p>Nested<p>paragraphs</p></p>")},
{"markdown", []byte("<p>Hello</p>\n<ul>\n<li>list1</li>\n<li>list2</li>\n</ul>"), []byte("<p>Hello</p>\n<ul>\n<li>list1</li>\n<li>list2</li>\n</ul>")},
// Issue 11698
{"markdown", []byte("<h2 id=`a`>b</h2>\n\n<p>c</p>"), []byte("<h2 id=`a`>b</h2>\n\n<p>c</p>")},
// Issue 12369
{"markdown", []byte("<div class=\"paragraph\">\n<p>foo</p>\n</div>"), []byte("<div class=\"paragraph\">\n<p>foo</p>\n</div>")},
{"asciidoc", []byte("<div class=\"paragraph\">\n<p>foo</p>\n</div>"), []byte("foo")},
}
c := newTestContentSpec(nil)
for i, test := range tests {
output := c.TrimShortHTML(test.input, test.markup)
if !bytes.Equal(test.output, output) {
t.Errorf("Test %d failed. Expected %q got %q", i, test.output, output)
}
}
}
func BenchmarkTrimShortHTML(b *testing.B) {
c := newTestContentSpec(nil)
for b.Loop() {
c.TrimShortHTML([]byte("<p>Simple paragraph</p>"), "markdown")
}
}
func TestBytesToHTML(t *testing.T) {
c := qt.New(t)
c.Assert(helpers.BytesToHTML([]byte("dobedobedo")), qt.Equals, template.HTML("dobedobedo"))
}
func TestExtractTOCNormalContent(t *testing.T) {
content := []byte("<nav>\n<ul>\nTOC<li><a href=\"#")
actualTocLessContent, actualToc := helpers.ExtractTOC(content)
expectedTocLess := []byte("TOC<li><a href=\"#")
expectedToc := []byte("<nav id=\"TableOfContents\">\n<ul>\n")
if !bytes.Equal(actualTocLessContent, expectedTocLess) {
t.Errorf("Actual tocless (%s) did not equal expected (%s) tocless content", actualTocLessContent, expectedTocLess)
}
if !bytes.Equal(actualToc, expectedToc) {
t.Errorf("Actual toc (%s) did not equal expected (%s) toc content", actualToc, expectedToc)
}
}
func TestExtractTOCGreaterThanSeventy(t *testing.T) {
content := []byte("<nav>\n<ul>\nTOC This is a very long content which will definitely be greater than seventy, I promise you that.<li><a href=\"#")
actualTocLessContent, actualToc := helpers.ExtractTOC(content)
// Because the start of Toc is greater than 70+startpoint of <li> content and empty TOC will be returned
expectedToc := []byte("")
if !bytes.Equal(actualTocLessContent, content) {
t.Errorf("Actual tocless (%s) did not equal expected (%s) tocless content", actualTocLessContent, content)
}
if !bytes.Equal(actualToc, expectedToc) {
t.Errorf("Actual toc (%s) did not equal expected (%s) toc content", actualToc, expectedToc)
}
}
func TestExtractNoTOC(t *testing.T) {
content := []byte("TOC")
actualTocLessContent, actualToc := helpers.ExtractTOC(content)
expectedToc := []byte("")
if !bytes.Equal(actualTocLessContent, content) {
t.Errorf("Actual tocless (%s) did not equal expected (%s) tocless content", actualTocLessContent, content)
}
if !bytes.Equal(actualToc, expectedToc) {
t.Errorf("Actual toc (%s) did not equal expected (%s) toc content", actualToc, expectedToc)
}
}
var totalWordsBenchmarkString = strings.Repeat("Hugo Rocks ", 200)
func TestTotalWords(t *testing.T) {
for i, this := range []struct {
s string
words int
}{
{"Two, Words!", 2},
{"Word", 1},
{"", 0},
{"One, Two, Three", 3},
{totalWordsBenchmarkString, 400},
} {
actualWordCount := helpers.TotalWords(this.s)
if actualWordCount != this.words {
t.Errorf("[%d] Actual word count (%d) for test string (%s) did not match %d", i, actualWordCount, this.s, this.words)
}
}
}
func BenchmarkTotalWords(b *testing.B) {
for b.Loop() {
wordCount := helpers.TotalWords(totalWordsBenchmarkString)
if wordCount != 400 {
b.Fatal("Wordcount error")
}
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/emoji_test.go | helpers/emoji_test.go | // Copyright 2016 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"reflect"
"testing"
)
func TestEmojiCustom(t *testing.T) {
for i, this := range []struct {
input string
expect []byte
}{
{"A :smile: a day", []byte("A 😄 a day")},
{"A few :smile:s a day", []byte("A few 😄s a day")},
{"A :smile: and a :beer: makes the day for sure.", []byte("A 😄 and a 🍺 makes the day for sure.")},
{"A :smile: and: a :beer:", []byte("A 😄 and: a 🍺")},
{"A :diamond_shape_with_a_dot_inside: and then some.", []byte("A 💠 and then some.")},
{":smile:", []byte("😄")},
{":smi", []byte(":smi")},
{"A :smile:", []byte("A 😄")},
{":beer:!", []byte("🍺!")},
{"::smile:", []byte(":😄")},
{":beer::", []byte("🍺:")},
{" :beer: :", []byte(" 🍺 :")},
{":beer: and :smile: and another :beer:!", []byte("🍺 and 😄 and another 🍺!")},
{" :beer: : ", []byte(" 🍺 : ")},
{"No smiles for you!", []byte("No smiles for you!")},
{" The motto: no smiles! ", []byte(" The motto: no smiles! ")},
{":hugo_is_the_best_static_gen:", []byte(":hugo_is_the_best_static_gen:")},
{"은행 :smile: 은행", []byte("은행 😄 은행")},
// #2198
{"See: A :beer:!", []byte("See: A 🍺!")},
{`Aaaaaaaaaa: aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa.
:beer:`, []byte(`Aaaaaaaaaa: aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa.
🍺`)},
{"test :\n```bash\nthis is a test\n```\n\ntest\n\n:cool::blush:::pizza:\\:blush : : blush: :pizza:", []byte("test :\n```bash\nthis is a test\n```\n\ntest\n\n🆒😊:🍕\\:blush : : blush: 🍕")},
{
// 2391
"[a](http://gohugo.io) :smile: [r](http://gohugo.io/introduction/overview/) :beer:",
[]byte(`[a](http://gohugo.io) 😄 [r](http://gohugo.io/introduction/overview/) 🍺`),
},
} {
result := Emojify([]byte(this.input))
if !reflect.DeepEqual(result, this.expect) {
t.Errorf("[%d] got %q but expected %q", i, result, this.expect)
}
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/path_test.go | helpers/path_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 helpers_test
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
"time"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/helpers"
"github.com/spf13/afero"
)
func TestMakePath(t *testing.T) {
tests := []struct {
input string
expected string
removeAccents bool
}{
{"dot.slash/backslash\\underscore_pound#plus+hyphen-", "dot.slash/backslash\\underscore_pound#plus+hyphen-", true},
{"abcXYZ0123456789", "abcXYZ0123456789", true},
{"%20 %2", "%20-2", true},
{"foo- bar", "foo-bar", true},
{" Foo bar ", "Foo-bar", true},
{"Foo.Bar/foo_Bar-Foo", "Foo.Bar/foo_Bar-Foo", true},
{"fOO,bar:foobAR", "fOObarfoobAR", true},
{"FOo/BaR.html", "FOo/BaR.html", true},
{"трям/трям", "трям/трям", true},
{"은행", "은행", true},
{"Банковский кассир", "Банковскии-кассир", true},
// Issue #1488
{"संस्कृत", "संस्कृत", false},
{"a%C3%B1ame", "a%C3%B1ame", false}, // Issue #1292
{"this+is+a+test", "this+is+a+test", false}, // Issue #1290
{"~foo", "~foo", false}, // Issue #2177
{"foo--bar", "foo--bar", true}, // Issue #7288
{"foo@bar", "foo@bar", true}, // Issue #10548
}
for _, test := range tests {
p := newTestPathSpec("removePathAccents", test.removeAccents)
output := p.MakePath(test.input)
if output != test.expected {
t.Errorf("Expected %#v, got %#v\n", test.expected, output)
}
}
}
func TestMakePathSanitized(t *testing.T) {
p := newTestPathSpec()
tests := []struct {
input string
expected string
}{
{" FOO bar ", "foo-bar"},
{"Foo.Bar/fOO_bAr-Foo", "foo.bar/foo_bar-foo"},
{"FOO,bar:FooBar", "foobarfoobar"},
{"foo/BAR.HTML", "foo/bar.html"},
{"трям/трям", "трям/трям"},
{"은행", "은행"},
}
for _, test := range tests {
output := p.MakePathSanitized(test.input)
if output != test.expected {
t.Errorf("Expected %#v, got %#v\n", test.expected, output)
}
}
}
func TestMakePathSanitizedDisablePathToLower(t *testing.T) {
p := newTestPathSpec("disablePathToLower", true)
tests := []struct {
input string
expected string
}{
{" FOO bar ", "FOO-bar"},
{"Foo.Bar/fOO_bAr-Foo", "Foo.Bar/fOO_bAr-Foo"},
{"FOO,bar:FooBar", "FOObarFooBar"},
{"foo/BAR.HTML", "foo/BAR.HTML"},
{"трям/трям", "трям/трям"},
{"은행", "은행"},
}
for _, test := range tests {
output := p.MakePathSanitized(test.input)
if output != test.expected {
t.Errorf("Expected %#v, got %#v\n", test.expected, output)
}
}
}
func TestMakePathRelative(t *testing.T) {
type test struct {
inPath, path1, path2, output string
}
data := []test{
{"/abc/bcd/ab.css", "/abc/bcd", "/bbc/bcd", "/ab.css"},
{"/abc/bcd/ab.css", "/abcd/bcd", "/abc/bcd", "/ab.css"},
}
for i, d := range data {
output, _ := helpers.MakePathRelative(d.inPath, d.path1, d.path2)
if d.output != output {
t.Errorf("Test #%d failed. Expected %q got %q", i, d.output, output)
}
}
_, error := helpers.MakePathRelative("a/b/c.ss", "/a/c", "/d/c", "/e/f")
if error == nil {
t.Errorf("Test failed, expected error")
}
}
func TestGetDottedRelativePath(t *testing.T) {
for _, f := range []func(string) string{filepath.FromSlash, func(s string) string { return s }} {
doTestGetDottedRelativePath(f, t)
}
}
func doTestGetDottedRelativePath(urlFixer func(string) string, t *testing.T) {
type test struct {
input, expected string
}
data := []test{
{"", "./"},
{urlFixer("/"), "./"},
{urlFixer("post"), "../"},
{urlFixer("/post"), "../"},
{urlFixer("post/"), "../"},
{urlFixer("tags/foo.html"), "../"},
{urlFixer("/tags/foo.html"), "../"},
{urlFixer("/post/"), "../"},
{urlFixer("////post/////"), "../"},
{urlFixer("/foo/bar/index.html"), "../../"},
{urlFixer("/foo/bar/foo/"), "../../../"},
{urlFixer("/foo/bar/foo"), "../../../"},
{urlFixer("foo/bar/foo/"), "../../../"},
{urlFixer("foo/bar/foo/bar"), "../../../../"},
{"404.html", "./"},
{"404.xml", "./"},
{"/404.html", "./"},
}
for i, d := range data {
output := helpers.GetDottedRelativePath(d.input)
if d.expected != output {
t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, output)
}
}
}
func TestMakeTitle(t *testing.T) {
type test struct {
input, expected string
}
data := []test{
{"Make-Title", "Make Title"},
{"MakeTitle", "MakeTitle"},
{"make_title", "make_title"},
}
for i, d := range data {
output := helpers.MakeTitle(d.input)
if d.expected != output {
t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, output)
}
}
}
func TestDirExists(t *testing.T) {
type test struct {
input string
expected bool
}
data := []test{
{".", true},
{"./", true},
{"..", true},
{"../", true},
{"./..", true},
{"./../", true},
{os.TempDir(), true},
{os.TempDir() + helpers.FilePathSeparator, true},
{"/", true},
{"/some-really-random-directory-name", false},
{"/some/really/random/directory/name", false},
{"./some-really-random-local-directory-name", false},
{"./some/really/random/local/directory/name", false},
}
for i, d := range data {
exists, _ := helpers.DirExists(filepath.FromSlash(d.input), new(afero.OsFs))
if d.expected != exists {
t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists)
}
}
}
func TestIsDir(t *testing.T) {
type test struct {
input string
expected bool
}
data := []test{
{"./", true},
{"/", true},
{"./this-directory-does-not-existi", false},
{"/this-absolute-directory/does-not-exist", false},
}
for i, d := range data {
exists, _ := helpers.IsDir(d.input, new(afero.OsFs))
if d.expected != exists {
t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists)
}
}
}
func createZeroSizedFileInTempDir(t *testing.T) *os.File {
t.Helper()
filePrefix := "_path_test_"
f, err := os.CreateTemp(t.TempDir(), filePrefix)
if err != nil {
t.Error(err)
}
if err := f.Close(); err != nil {
t.Error(err)
}
return f
}
func createNonZeroSizedFileInTempDir(t *testing.T) *os.File {
t.Helper()
f := createZeroSizedFileInTempDir(t)
byteString := []byte("byteString")
err := os.WriteFile(f.Name(), byteString, 0o644)
if err != nil {
t.Error(err)
}
return f
}
func TestExists(t *testing.T) {
zeroSizedFile := createZeroSizedFileInTempDir(t)
nonZeroSizedFile := createNonZeroSizedFileInTempDir(t)
emptyDirectory := t.TempDir()
nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
nonExistentDir := os.TempDir() + "/this/directory/does/not/exist/"
type test struct {
input string
expectedResult bool
expectedErr error
}
data := []test{
{zeroSizedFile.Name(), true, nil},
{nonZeroSizedFile.Name(), true, nil},
{emptyDirectory, true, nil},
{nonExistentFile, false, nil},
{nonExistentDir, false, nil},
}
for i, d := range data {
exists, err := helpers.Exists(d.input, new(afero.OsFs))
if d.expectedResult != exists {
t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists)
}
if d.expectedErr != err {
t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err)
}
}
}
func TestAbsPathify(t *testing.T) {
type test struct {
inPath, workingDir, expected string
}
data := []test{
{os.TempDir(), filepath.FromSlash("/work"), filepath.Clean(os.TempDir())}, // TempDir has trailing slash
{"dir", filepath.FromSlash("/work"), filepath.FromSlash("/work/dir")},
}
windowsData := []test{
{"c:\\banana\\..\\dir", "c:\\foo", "c:\\dir"},
{"\\dir", "c:\\foo", "c:\\foo\\dir"},
{"c:\\", "c:\\foo", "c:\\"},
}
unixData := []test{
{"/banana/../dir/", "/work", "/dir"},
}
for i, d := range data {
// todo see comment in AbsPathify
ps := newTestPathSpec("workingDir", d.workingDir)
expected := ps.AbsPathify(d.inPath)
if d.expected != expected {
t.Errorf("Test %d failed. Expected %q but got %q", i, d.expected, expected)
}
}
t.Logf("Running platform specific path tests for %s", runtime.GOOS)
if runtime.GOOS == "windows" {
for i, d := range windowsData {
ps := newTestPathSpec("workingDir", d.workingDir)
expected := ps.AbsPathify(d.inPath)
if d.expected != expected {
t.Errorf("Test %d failed. Expected %q but got %q", i, d.expected, expected)
}
}
} else {
for i, d := range unixData {
ps := newTestPathSpec("workingDir", d.workingDir)
expected := ps.AbsPathify(d.inPath)
if d.expected != expected {
t.Errorf("Test %d failed. Expected %q but got %q", i, d.expected, expected)
}
}
}
}
func TestExtractAndGroupRootPaths(t *testing.T) {
c := qt.New(t)
t.Run("Basic grouping", func(t *testing.T) {
in := []string{
filepath.FromSlash("/a/b/c/d"),
filepath.FromSlash("/a/b/c/e"),
filepath.FromSlash("/a/b/e/f"),
filepath.FromSlash("/a/b"),
filepath.FromSlash("/a/b/c/b/g"),
filepath.FromSlash("/c/d/e"),
}
result := helpers.ExtractAndGroupRootPaths(in)
c.Assert(result, qt.DeepEquals, []string{"/a/b/{c,e}", "/c/d/e"})
})
t.Run("Limits number of root groups", func(t *testing.T) {
in := []string{}
// Create 15 different root paths to exceed maxRootGroups (10)
for i := 0; i < 15; i++ {
in = append(in, filepath.FromSlash(fmt.Sprintf("/path%d/subdir", i)))
}
result := helpers.ExtractAndGroupRootPaths(in)
// Should have 10 paths + 1 "... and X more" message
c.Assert(len(result), qt.Equals, 11)
c.Assert(result[10], qt.Matches, `\.\.\. and \d+ more`)
})
}
func BenchmarkExtractAndGroupRootPaths(b *testing.B) {
in := []string{}
for i := 0; i < 10; i++ {
for j := 0; j < 1000; j++ {
in = append(in, fmt.Sprintf("/a/b/c/s%d/p%d", i, j))
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
helpers.ExtractAndGroupRootPaths(in)
}
}
func TestFindCWD(t *testing.T) {
type test struct {
expectedDir string
expectedErr error
}
// cwd, _ := os.Getwd()
data := []test{
//{cwd, nil},
// Commenting this out. It doesn't work properly.
// There's a good reason why we don't use os.Getwd(), it doesn't actually work the way we want it to.
// I really don't know a better way to test this function. - SPF 2014.11.04
}
for i, d := range data {
dir, err := helpers.FindCWD()
if d.expectedDir != dir {
t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedDir, dir)
}
if d.expectedErr != err {
t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedErr, err)
}
}
}
func TestSafeWriteToDisk(t *testing.T) {
emptyFile := createZeroSizedFileInTempDir(t)
tmpDir := t.TempDir()
randomString := "This is a random string!"
reader := strings.NewReader(randomString)
fileExists := fmt.Errorf("%v already exists", emptyFile.Name())
type test struct {
filename string
expectedErr error
}
now := time.Now().Unix()
nowStr := strconv.FormatInt(now, 10)
data := []test{
{emptyFile.Name(), fileExists},
{tmpDir + "/" + nowStr, nil},
}
for i, d := range data {
e := helpers.SafeWriteToDisk(d.filename, reader, new(afero.OsFs))
if d.expectedErr != nil {
if d.expectedErr.Error() != e.Error() {
t.Errorf("Test %d failed. Expected error %q but got %q", i, d.expectedErr.Error(), e.Error())
}
} else {
if d.expectedErr != e {
t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedErr, e)
}
contents, _ := os.ReadFile(d.filename)
if randomString != string(contents) {
t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
}
}
reader.Seek(0, 0)
}
}
func TestWriteToDisk(t *testing.T) {
emptyFile := createZeroSizedFileInTempDir(t)
tmpDir := t.TempDir()
randomString := "This is a random string!"
reader := strings.NewReader(randomString)
type test struct {
filename string
expectedErr error
}
now := time.Now().Unix()
nowStr := strconv.FormatInt(now, 10)
data := []test{
{emptyFile.Name(), nil},
{tmpDir + "/" + nowStr, nil},
}
for i, d := range data {
e := helpers.WriteToDisk(d.filename, reader, new(afero.OsFs))
if d.expectedErr != e {
t.Errorf("Test %d failed. WriteToDisk Error Expected %q but got %q", i, d.expectedErr, e)
}
contents, e := os.ReadFile(d.filename)
if e != nil {
t.Errorf("Test %d failed. Could not read file %s. Reason: %s\n", i, d.filename, e)
}
if randomString != string(contents) {
t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
}
reader.Seek(0, 0)
}
}
func TestGetTempDir(t *testing.T) {
dir := os.TempDir()
if helpers.FilePathSeparator != dir[len(dir)-1:] {
dir = dir + helpers.FilePathSeparator
}
testDir := "hugoTestFolder" + helpers.FilePathSeparator
tests := []struct {
input string
expected string
}{
{"", dir},
{testDir + " Foo bar ", dir + testDir + " Foo bar " + helpers.FilePathSeparator},
{testDir + "Foo.Bar/foo_Bar-Foo", dir + testDir + "Foo.Bar/foo_Bar-Foo" + helpers.FilePathSeparator},
{testDir + "fOO,bar:foo%bAR", dir + testDir + "fOObarfoo%bAR" + helpers.FilePathSeparator},
{testDir + "fOO,bar:foobAR", dir + testDir + "fOObarfoobAR" + helpers.FilePathSeparator},
{testDir + "FOo/BaR.html", dir + testDir + "FOo/BaR.html" + helpers.FilePathSeparator},
{testDir + "трям/трям", dir + testDir + "трям/трям" + helpers.FilePathSeparator},
{testDir + "은행", dir + testDir + "은행" + helpers.FilePathSeparator},
{testDir + "Банковский кассир", dir + testDir + "Банковский кассир" + helpers.FilePathSeparator},
}
for _, test := range tests {
output := helpers.GetTempDir(test.input, new(afero.MemMapFs))
if output != test.expected {
t.Errorf("Expected %#v, got %#v\n", test.expected, output)
}
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/url.go | helpers/url.go | // Copyright 2015 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"net/url"
"path"
"path/filepath"
"strings"
"github.com/gohugoio/hugo/common/paths"
)
// URLize is similar to MakePath, but with Unicode handling
// Example:
//
// uri: Vim (text editor)
// urlize: vim-text-editor
func (p *PathSpec) URLize(uri string) string {
return p.URLEscape(p.MakePathSanitized(uri))
}
// URLizeFilename creates an URL from a filename by escaping unicode letters
// and turn any filepath separator into forward slashes.
func (p *PathSpec) URLizeFilename(filename string) string {
return p.URLEscape(filepath.ToSlash(filename))
}
// URLEscape escapes unicode letters.
func (p *PathSpec) URLEscape(uri string) string {
// escape unicode letters
parsedURI, err := url.Parse(uri)
if err != nil {
// if net/url can not parse URL it means Sanitize works incorrectly
panic(err)
}
x := parsedURI.String()
return x
}
// AbsURL creates an absolute URL from the relative path given and the BaseURL set in config.
func (p *PathSpec) AbsURL(in string, addLanguage bool) string {
isAbs, err := p.IsAbsURL(in)
if err != nil {
return in
}
if isAbs || strings.HasPrefix(in, "//") {
// It is already absolute, return it as is.
return in
}
baseURL := p.getBaseURLRoot(in)
if addLanguage {
prefix := p.GetLanguagePrefix()
if prefix != "" {
hasPrefix := false
// avoid adding language prefix if already present
in2 := in
if strings.HasPrefix(in, "/") {
in2 = in[1:]
}
if in2 == prefix {
hasPrefix = true
} else {
hasPrefix = strings.HasPrefix(in2, prefix+"/")
}
if !hasPrefix {
addSlash := in == "" || strings.HasSuffix(in, "/")
in = path.Join(prefix, in)
if addSlash {
in += "/"
}
}
}
}
return paths.MakePermalink(baseURL, in).String()
}
func (p *PathSpec) getBaseURLRoot(path string) string {
if strings.HasPrefix(path, "/") {
// Treat it as relative to the server root.
return p.Cfg.BaseURL().WithoutPath
} else {
// Treat it as relative to the baseURL.
return p.Cfg.BaseURL().WithPath
}
}
func (p *PathSpec) IsAbsURL(in string) (bool, error) {
// Fast path.
if strings.HasPrefix(in, "http://") || strings.HasPrefix(in, "https://") {
return true, nil
}
u, err := url.Parse(in)
if err != nil {
return false, err
}
return u.IsAbs(), nil
}
func (p *PathSpec) RelURL(in string, addLanguage bool) string {
isAbs, err := p.IsAbsURL(in)
if err != nil {
return in
}
baseURL := p.getBaseURLRoot(in)
canonifyURLs := p.Cfg.CanonifyURLs()
if (!strings.HasPrefix(in, baseURL) && isAbs) || strings.HasPrefix(in, "//") {
return in
}
u := in
if strings.HasPrefix(in, baseURL) {
u = strings.TrimPrefix(u, baseURL)
}
if addLanguage {
prefix := p.GetLanguagePrefix()
if prefix != "" {
hasPrefix := false
// avoid adding language prefix if already present
in2 := in
if strings.HasPrefix(in, "/") {
in2 = in[1:]
}
if in2 == prefix {
hasPrefix = true
} else {
hasPrefix = strings.HasPrefix(in2, prefix+"/")
}
if !hasPrefix {
hadSlash := strings.HasSuffix(u, "/")
u = path.Join(prefix, u)
if hadSlash {
u += "/"
}
}
}
}
if !canonifyURLs {
u = paths.AddContextRoot(baseURL, u)
}
if in == "" && !strings.HasSuffix(u, "/") && strings.HasSuffix(baseURL, "/") {
u += "/"
}
if !strings.HasPrefix(u, "/") {
u = "/" + u
}
return u
}
// PrependBasePath prepends any baseURL sub-folder to the given resource
func (p *PathSpec) PrependBasePath(rel string, isAbs bool) string {
basePath := p.GetBasePath(!isAbs)
if basePath != "" {
rel = filepath.ToSlash(rel)
// Need to prepend any path from the baseURL
hadSlash := strings.HasSuffix(rel, "/")
rel = path.Join(basePath, rel)
if hadSlash {
rel += "/"
}
}
return rel
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/processing_stats.go | helpers/processing_stats.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 helpers
import (
"io"
"strconv"
"sync/atomic"
"github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/renderer"
"github.com/olekukonko/tablewriter/tw"
)
// ProcessingStats represents statistics about a site build.
type ProcessingStats struct {
Name string
Pages uint64
PaginatorPages uint64
Static uint64
ProcessedImages uint64
Files uint64
Aliases uint64
Cleaned uint64
}
type processingStatsTitleVal struct {
name string
val uint64
}
func (s *ProcessingStats) toVals() []processingStatsTitleVal {
return []processingStatsTitleVal{
{"Pages", s.Pages},
{"Paginator pages", s.PaginatorPages},
{"Non-page files", s.Files},
{"Static files", s.Static},
{"Processed images", s.ProcessedImages},
{"Aliases", s.Aliases},
{"Cleaned", s.Cleaned},
}
}
// NewProcessingStats returns a new ProcessingStats instance.
func NewProcessingStats(name string) *ProcessingStats {
return &ProcessingStats{Name: name}
}
// Incr increments a given counter.
func (s *ProcessingStats) Incr(counter *uint64) {
atomic.AddUint64(counter, 1)
}
// Add adds an amount to a given counter.
func (s *ProcessingStats) Add(counter *uint64, amount int) {
atomic.AddUint64(counter, uint64(amount))
}
// ProcessingStatsTable writes a table-formatted representation of stats to w.
func ProcessingStatsTable(w io.Writer, stats ...*ProcessingStats) {
names := make([]string, len(stats)+1)
var data [][]string
for i := range stats {
stat := stats[i]
names[i+1] = stat.Name
titleVals := stat.toVals()
if i == 0 {
data = make([][]string, len(titleVals))
}
for j, tv := range titleVals {
if i == 0 {
data[j] = []string{tv.name, strconv.Itoa(int(tv.val))}
} else {
data[j] = append(data[j], strconv.Itoa(int(tv.val)))
}
}
}
table := tablewriter.NewTable(
w,
tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
Borders: tw.BorderNone,
Symbols: tw.NewSymbols(tw.StyleLight),
Settings: tw.Settings{
Separators: tw.Separators{BetweenRows: tw.Off},
Lines: tw.Lines{ShowFooterLine: tw.On},
},
})),
tablewriter.WithConfig(
tablewriter.Config{
MaxWidth: 70,
Row: tw.CellConfig{Alignment: tw.CellAlignment{Global: tw.AlignRight, PerColumn: []tw.Align{tw.AlignLeft}}},
}),
)
table.Bulk(data)
table.Header(names)
table.Render()
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/testhelpers_test.go | helpers/testhelpers_test.go | package helpers_test
import (
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/config/testconfig"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
"github.com/spf13/afero"
)
func newTestPathSpecFromCfgAndLang(cfg config.Provider, lang string) *helpers.PathSpec {
mfs := afero.NewMemMapFs()
configs := testconfig.GetTestConfigs(mfs, cfg)
var conf config.AllProvider
if lang == "" {
conf = configs.GetFirstLanguageConfig()
} else {
conf = configs.GetByLang(lang)
if conf == nil {
panic("no config for lang " + lang)
}
}
fs := hugofs.NewFrom(mfs, conf.BaseConfig())
ps, err := helpers.NewPathSpec(fs, conf, loggers.NewDefault(), nil)
if err != nil {
panic(err)
}
return ps
}
func newTestPathSpec(configKeyValues ...any) *helpers.PathSpec {
cfg := config.New()
for i := 0; i < len(configKeyValues); i += 2 {
cfg.Set(configKeyValues[i].(string), configKeyValues[i+1])
}
return newTestPathSpecFromCfgAndLang(cfg, "")
}
func newTestContentSpec(cfg config.Provider) *helpers.ContentSpec {
fs := afero.NewMemMapFs()
conf := testconfig.GetTestConfig(fs, cfg)
spec, err := helpers.NewContentSpec(conf, loggers.NewDefault(), fs, nil)
if err != nil {
panic(err)
}
return spec
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/url_test.go | helpers/url_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 helpers_test
import (
"fmt"
"strings"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config"
)
func TestURLize(t *testing.T) {
p := newTestPathSpec()
tests := []struct {
input string
expected string
}{
{" foo bar ", "foo-bar"},
{"foo.bar/foo_bar-foo", "foo.bar/foo_bar-foo"},
{"foo,bar:foobar", "foobarfoobar"},
{"foo/bar.html", "foo/bar.html"},
{"трям/трям", "%D1%82%D1%80%D1%8F%D0%BC/%D1%82%D1%80%D1%8F%D0%BC"},
{"100%-google", "100-google"},
}
for _, test := range tests {
output := p.URLize(test.input)
if output != test.expected {
t.Errorf("Expected %#v, got %#v\n", test.expected, output)
}
}
}
func TestAbsURL(t *testing.T) {
for _, defaultInSubDir := range []bool{true, false} {
for _, addLanguage := range []bool{true, false} {
for _, m := range []bool{true, false} {
for _, l := range []string{"en", "fr"} {
doTestAbsURL(t, defaultInSubDir, addLanguage, m, l)
}
}
}
}
}
func doTestAbsURL(t *testing.T, defaultInSubDir, addLanguage, multilingual bool, lang string) {
c := qt.New(t)
tests := []struct {
input string
baseURL string
expected string
}{
// Issue 9994
{"foo/bar", "https://example.org/foo/", "https://example.org/foo/MULTIfoo/bar"},
{"/foo/bar", "https://example.org/foo/", "https://example.org/MULTIfoo/bar"},
{"/test/foo", "http://base/", "http://base/MULTItest/foo"},
{"/" + lang + "/test/foo", "http://base/", "http://base/" + lang + "/test/foo"},
{"", "http://base/ace/", "http://base/ace/MULTI"},
{"/test/2/foo/", "http://base", "http://base/MULTItest/2/foo/"},
{"http://abs", "http://base/", "http://abs"},
{"schema://abs", "http://base/", "schema://abs"},
{"//schemaless", "http://base/", "//schemaless"},
{"test/2/foo/", "http://base/path", "http://base/path/MULTItest/2/foo/"},
{lang + "/test/2/foo/", "http://base/path", "http://base/path/" + lang + "/test/2/foo/"},
{"/test/2/foo/", "http://base/path", "http://base/MULTItest/2/foo/"},
{"http//foo", "http://base/path", "http://base/path/MULTIhttp/foo"},
}
if multilingual && addLanguage && defaultInSubDir {
newTests := []struct {
input string
baseURL string
expected string
}{
{lang + "test", "http://base/", "http://base/" + lang + "/" + lang + "test"},
{"/" + lang + "test", "http://base/", "http://base/" + lang + "/" + lang + "test"},
}
tests = append(tests, newTests...)
}
for _, test := range tests {
c.Run(fmt.Sprintf("%v/%t-%t-%t/%s", test, defaultInSubDir, addLanguage, multilingual, lang), func(c *qt.C) {
v := config.New()
if multilingual {
v.Set("languages", map[string]any{
"fr": map[string]any{
"weight": 20,
},
"en": map[string]any{
"weight": 10,
},
})
v.Set("defaultContentLanguage", "en")
} else {
v.Set("defaultContentLanguage", lang)
v.Set("languages", map[string]any{
lang: map[string]any{
"weight": 10,
},
})
}
v.Set("defaultContentLanguageInSubdir", defaultInSubDir)
v.Set("baseURL", test.baseURL)
var configLang string
if multilingual {
configLang = lang
}
defaultContentLanguage := lang
if multilingual {
defaultContentLanguage = "en"
}
p := newTestPathSpecFromCfgAndLang(v, configLang)
output := p.AbsURL(test.input, addLanguage)
expected := test.expected
if addLanguage {
addLanguage = defaultInSubDir && lang == defaultContentLanguage
addLanguage = addLanguage || (lang != defaultContentLanguage && multilingual)
}
if addLanguage {
expected = strings.Replace(expected, "MULTI", lang+"/", 1)
} else {
expected = strings.Replace(expected, "MULTI", "", 1)
}
c.Assert(output, qt.Equals, expected)
})
}
}
func TestRelURL(t *testing.T) {
for _, defaultInSubDir := range []bool{true, false} {
for _, addLanguage := range []bool{true, false} {
for _, m := range []bool{true, false} {
for _, l := range []string{"en", "fr"} {
doTestRelURL(t, defaultInSubDir, addLanguage, m, l)
}
}
}
}
}
func doTestRelURL(t testing.TB, defaultInSubDir, addLanguage, multilingual bool, lang string) {
t.Helper()
c := qt.New(t)
v := config.New()
if multilingual {
v.Set("languages", map[string]any{
"fr": map[string]any{
"weight": 20,
},
"en": map[string]any{
"weight": 10,
},
})
v.Set("defaultContentLanguage", "en")
} else {
v.Set("defaultContentLanguage", lang)
v.Set("languages", map[string]any{
lang: map[string]any{
"weight": 10,
},
})
}
v.Set("defaultContentLanguageInSubdir", defaultInSubDir)
tests := []struct {
input string
baseURL string
canonify bool
expected string
}{
// Issue 9994
{"/foo/bar", "https://example.org/foo/", false, "MULTI/foo/bar"},
{"foo/bar", "https://example.org/foo/", false, "/fooMULTI/foo/bar"},
// Issue 11080
{"mailto:a@b.com", "http://base/", false, "mailto:a@b.com"},
{"ftp://b.com/a.txt", "http://base/", false, "ftp://b.com/a.txt"},
{"/test/foo", "http://base/", false, "MULTI/test/foo"},
{"/" + lang + "/test/foo", "http://base/", false, "/" + lang + "/test/foo"},
{lang + "/test/foo", "http://base/", false, "/" + lang + "/test/foo"},
{"test.css", "http://base/sub", false, "/subMULTI/test.css"},
{"test.css", "http://base/sub", true, "MULTI/test.css"},
{"/test/", "http://base/", false, "MULTI/test/"},
{"test/", "http://base/sub/", false, "/subMULTI/test/"},
{"/test/", "http://base/sub/", true, "MULTI/test/"},
{"", "http://base/ace/", false, "/aceMULTI/"},
{"", "http://base/ace", false, "/aceMULTI/"},
{"http://abs", "http://base/", false, "http://abs"},
{"//schemaless", "http://base/", false, "//schemaless"},
}
if multilingual && addLanguage && defaultInSubDir {
newTests := []struct {
input string
baseURL string
canonify bool
expected string
}{
{lang + "test", "http://base/", false, "/" + lang + "/" + lang + "test"},
{"/" + lang + "test", "http://base/", false, "/" + lang + "/" + lang + "test"},
}
tests = append(tests, newTests...)
}
for i, test := range tests {
c.Run(fmt.Sprintf("%v/defaultInSubDir=%t;addLanguage=%t;multilingual=%t/%s", test, defaultInSubDir, addLanguage, multilingual, lang), func(c *qt.C) {
v.Set("baseURL", test.baseURL)
v.Set("canonifyURLs", test.canonify)
defaultContentLanguage := lang
if multilingual {
defaultContentLanguage = "en"
}
p := newTestPathSpecFromCfgAndLang(v, lang)
output := p.RelURL(test.input, addLanguage)
expected := test.expected
if addLanguage {
addLanguage = defaultInSubDir && lang == defaultContentLanguage
addLanguage = addLanguage || (lang != defaultContentLanguage && multilingual)
}
if addLanguage {
expected = strings.Replace(expected, "MULTI", "/"+lang, 1)
} else {
expected = strings.Replace(expected, "MULTI", "", 1)
}
c.Assert(output, qt.Equals, expected, qt.Commentf("[%d] %s", i, test.input))
})
}
}
func BenchmarkRelURL(b *testing.B) {
v := config.New()
v.Set("baseURL", "https://base/")
p := newTestPathSpecFromCfgAndLang(v, "")
for b.Loop() {
_ = p.RelURL("https://base/foo/bar", false)
}
}
func BenchmarkAbsURL(b *testing.B) {
v := config.New()
v.Set("baseURL", "https://base/")
p := newTestPathSpecFromCfgAndLang(v, "")
b.ResetTimer()
b.Run("relurl", func(b *testing.B) {
for b.Loop() {
_ = p.AbsURL("foo/bar", false)
}
})
b.Run("absurl", func(b *testing.B) {
for b.Loop() {
_ = p.AbsURL("https://base/foo/bar", false)
}
})
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/emoji.go | helpers/emoji.go | // Copyright 2016 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"bytes"
"sync"
"github.com/kyokomi/emoji/v2"
)
var (
emojiInit sync.Once
emojis = make(map[string][]byte)
emojiDelim = []byte(":")
emojiWordDelim = []byte(" ")
emojiMaxSize int
)
// Emojify "emojifies" the input source.
// Note that the input byte slice will be modified if needed.
// See http://www.emoji-cheat-sheet.com/
func Emojify(source []byte) []byte {
emojiInit.Do(initEmoji)
start := 0
k := bytes.Index(source[start:], emojiDelim)
for k != -1 {
j := start + k
upper := min(j+emojiMaxSize, len(source))
endEmoji := bytes.Index(source[j+1:upper], emojiDelim)
nextWordDelim := bytes.Index(source[j:upper], emojiWordDelim)
if endEmoji < 0 {
start++
} else if endEmoji == 0 || (nextWordDelim != -1 && nextWordDelim < endEmoji) {
start += endEmoji + 1
} else {
endKey := endEmoji + j + 2
emojiKey := source[j:endKey]
if emoji, ok := emojis[string(emojiKey)]; ok {
source = append(source[:j], append(emoji, source[endKey:]...)...)
}
start += endEmoji
}
if start >= len(source) {
break
}
k = bytes.Index(source[start:], emojiDelim)
}
return source
}
func initEmoji() {
emojiMap := emoji.CodeMap()
for k, v := range emojiMap {
emojis[k] = []byte(v)
if len(k) > emojiMaxSize {
emojiMaxSize = len(k)
}
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/docshelper.go | helpers/docshelper.go | package helpers
import (
"sort"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
"github.com/gohugoio/hugo/docshelper"
)
// This is is just some helpers used to create some JSON used in the Hugo docs.
func init() {
docsProvider := func() docshelper.DocProvider {
var chromaLexers []any
sort.Sort(lexers.GlobalLexerRegistry.Lexers)
for _, l := range lexers.GlobalLexerRegistry.Lexers {
config := l.Config()
lexerEntry := struct {
Name string
Aliases []string
}{
config.Name,
config.Aliases,
}
chromaLexers = append(chromaLexers, lexerEntry)
}
return docshelper.DocProvider{"chroma": map[string]any{
"lexers": chromaLexers,
"styles": styles.Names(),
}}
}
docshelper.AddDocProviderFunc(docsProvider)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/general_test.go | helpers/general_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 helpers_test
import (
"strings"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/helpers"
)
func TestResolveMarkup(t *testing.T) {
spec := newTestContentSpec(nil)
for i, this := range []struct {
in string
expect string
}{
{"md", "markdown"},
{"markdown", "markdown"},
{"mdown", "markdown"},
{"asciidocext", "asciidoc"},
{"adoc", "asciidoc"},
{"ad", "asciidoc"},
{"rst", "rst"},
{"pandoc", "pandoc"},
{"pdc", "pandoc"},
{"html", "html"},
{"htm", "html"},
{"org", "org"},
{"excel", ""},
} {
result := spec.ResolveMarkup(this.in)
if result != this.expect {
t.Errorf("[%d] got %s but expected %s", i, result, this.expect)
}
}
}
func TestFirstUpper(t *testing.T) {
for i, this := range []struct {
in string
expect string
}{
{"foo", "Foo"},
{"foo bar", "Foo bar"},
{"Foo Bar", "Foo Bar"},
{"", ""},
{"å", "Å"},
} {
result := helpers.FirstUpper(this.in)
if result != this.expect {
t.Errorf("[%d] got %s but expected %s", i, result, this.expect)
}
}
}
func TestHasStringsPrefix(t *testing.T) {
for i, this := range []struct {
s []string
prefix []string
expect bool
}{
{[]string{"a"}, []string{"a"}, true},
{[]string{}, []string{}, true},
{[]string{"a", "b", "c"}, []string{"a", "b"}, true},
{[]string{"d", "a", "b", "c"}, []string{"a", "b"}, false},
{[]string{"abra", "ca", "dabra"}, []string{"abra", "ca"}, true},
{[]string{"abra", "ca"}, []string{"abra", "ca", "dabra"}, false},
} {
result := helpers.HasStringsPrefix(this.s, this.prefix)
if result != this.expect {
t.Fatalf("[%d] got %t but expected %t", i, result, this.expect)
}
}
}
func TestHasStringsSuffix(t *testing.T) {
for i, this := range []struct {
s []string
suffix []string
expect bool
}{
{[]string{"a"}, []string{"a"}, true},
{[]string{}, []string{}, true},
{[]string{"a", "b", "c"}, []string{"b", "c"}, true},
{[]string{"abra", "ca", "dabra"}, []string{"abra", "ca"}, false},
{[]string{"abra", "ca", "dabra"}, []string{"ca", "dabra"}, true},
} {
result := helpers.HasStringsSuffix(this.s, this.suffix)
if result != this.expect {
t.Fatalf("[%d] got %t but expected %t", i, result, this.expect)
}
}
}
var containsTestText = (`На берегу пустынных волн
Стоял он, дум великих полн,
И вдаль глядел. Пред ним широко
Река неслася; бедный чёлн
По ней стремился одиноко.
По мшистым, топким берегам
Чернели избы здесь и там,
Приют убогого чухонца;
И лес, неведомый лучам
В тумане спрятанного солнца,
Кругом шумел.
Τη γλώσσα μου έδωσαν ελληνική
το σπίτι φτωχικό στις αμμουδιές του Ομήρου.
Μονάχη έγνοια η γλώσσα μου στις αμμουδιές του Ομήρου.
από το Άξιον Εστί
του Οδυσσέα Ελύτη
Sîne klâwen durh die wolken sint geslagen,
er stîget ûf mit grôzer kraft,
ich sih in grâwen tägelîch als er wil tagen,
den tac, der im geselleschaft
erwenden wil, dem werden man,
den ich mit sorgen în verliez.
ich bringe in hinnen, ob ich kan.
sîn vil manegiu tugent michz leisten hiez.
`)
var containsBenchTestData = []struct {
v1 string
v2 []byte
expect bool
}{
{"abc", []byte("a"), true},
{"abc", []byte("b"), true},
{"abcdefg", []byte("efg"), true},
{"abc", []byte("d"), false},
{containsTestText, []byte("стремился"), true},
{containsTestText, []byte(containsTestText[10:80]), true},
{containsTestText, []byte(containsTestText[100:111]), true},
{containsTestText, []byte(containsTestText[len(containsTestText)-100 : len(containsTestText)-10]), true},
{containsTestText, []byte(containsTestText[len(containsTestText)-20:]), true},
{containsTestText, []byte("notfound"), false},
}
// some corner cases
var containsAdditionalTestData = []struct {
v1 string
v2 []byte
expect bool
}{
{"", nil, false},
{"", []byte("a"), false},
{"a", []byte(""), false},
{"", []byte(""), false},
}
func TestSliceToLower(t *testing.T) {
t.Parallel()
tests := []struct {
value []string
expected []string
}{
{[]string{"a", "b", "c"}, []string{"a", "b", "c"}},
{[]string{"a", "B", "c"}, []string{"a", "b", "c"}},
{[]string{"A", "B", "C"}, []string{"a", "b", "c"}},
}
for _, test := range tests {
res := helpers.SliceToLower(test.value)
for i, val := range res {
if val != test.expected[i] {
t.Errorf("Case mismatch. Expected %s, got %s", test.expected[i], res[i])
}
}
}
}
func TestReaderContains(t *testing.T) {
c := qt.New(t)
for i, this := range append(containsBenchTestData, containsAdditionalTestData...) {
result := helpers.ReaderContains(strings.NewReader(this.v1), this.v2)
if result != this.expect {
t.Errorf("[%d] got %t but expected %t", i, result, this.expect)
}
}
c.Assert(helpers.ReaderContains(nil, []byte("a")), qt.Equals, false)
c.Assert(helpers.ReaderContains(nil, nil), qt.Equals, false)
}
func TestGetTitleFunc(t *testing.T) {
title := "somewhere over the Rainbow"
c := qt.New(t)
c.Assert(helpers.GetTitleFunc("go")(title), qt.Equals, "Somewhere Over The Rainbow")
c.Assert(helpers.GetTitleFunc("chicago")(title), qt.Equals, "Somewhere over the Rainbow")
c.Assert(helpers.GetTitleFunc("Chicago")(title), qt.Equals, "Somewhere over the Rainbow")
c.Assert(helpers.GetTitleFunc("ap")(title), qt.Equals, "Somewhere Over the Rainbow")
c.Assert(helpers.GetTitleFunc("ap")(title), qt.Equals, "Somewhere Over the Rainbow")
c.Assert(helpers.GetTitleFunc("")(title), qt.Equals, "Somewhere Over the Rainbow")
c.Assert(helpers.GetTitleFunc("unknown")(title), qt.Equals, "Somewhere Over the Rainbow")
c.Assert(helpers.GetTitleFunc("none")(title), qt.Equals, title)
c.Assert(helpers.GetTitleFunc("firstupper")(title), qt.Equals, "Somewhere over the Rainbow")
}
func BenchmarkReaderContains(b *testing.B) {
for b.Loop() {
for i, this := range containsBenchTestData {
result := helpers.ReaderContains(strings.NewReader(this.v1), this.v2)
if result != this.expect {
b.Errorf("[%d] got %t but expected %t", i, result, this.expect)
}
}
}
}
func TestStringSliceToList(t *testing.T) {
for _, tt := range []struct {
slice []string
conjunction string
want string
}{
{[]string{}, "", ""},
{[]string{"foo"}, "", "foo"},
{[]string{"foo"}, "and", "foo"},
{[]string{"foo", "bar"}, "", "foo and bar"},
{[]string{"foo", "bar"}, "and", "foo and bar"},
{[]string{"foo", "bar"}, "or", "foo or bar"},
{[]string{"foo", "bar", "baz"}, "", "foo, bar, and baz"},
{[]string{"foo", "bar", "baz"}, "and", "foo, bar, and baz"},
{[]string{"foo", "bar", "baz"}, "or", "foo, bar, or baz"},
} {
got := helpers.StringSliceToList(tt.slice, tt.conjunction)
if got != tt.want {
t.Errorf("StringSliceToList() got: %q, want: %q", got, tt.want)
}
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/helpers/content.go | helpers/content.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 helpers implements general utility functions that work with
// and on content. The helper functions defined here lay down the
// foundation of how Hugo works with files and filepaths, and perform
// string operations on content.
package helpers
import (
"bytes"
"html/template"
"strings"
"unicode"
"github.com/gohugoio/hugo/common/hexec"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/media"
"github.com/spf13/afero"
"github.com/gohugoio/hugo/markup/converter"
"github.com/gohugoio/hugo/markup"
"github.com/gohugoio/hugo/config"
)
// ContentSpec provides functionality to render markdown content.
type ContentSpec struct {
Converters markup.ConverterProvider
anchorNameSanitizer converter.AnchorNameSanitizer
Cfg config.AllProvider
}
// NewContentSpec returns a ContentSpec initialized
// with the appropriate fields from the given config.Provider.
func NewContentSpec(cfg config.AllProvider, logger loggers.Logger, contentFs afero.Fs, ex *hexec.Exec) (*ContentSpec, error) {
spec := &ContentSpec{
Cfg: cfg,
}
converterProvider, err := markup.NewConverterProvider(converter.ProviderConfig{
Conf: cfg,
ContentFs: contentFs,
Logger: logger,
Exec: ex,
})
if err != nil {
return nil, err
}
spec.Converters = converterProvider
p := converterProvider.Get("markdown")
conv, err := p.New(converter.DocumentContext{})
if err != nil {
return nil, err
}
if as, ok := conv.(converter.AnchorNameSanitizer); ok {
spec.anchorNameSanitizer = as
} else {
// Use Goldmark's sanitizer
p := converterProvider.Get("goldmark")
conv, err := p.New(converter.DocumentContext{})
if err != nil {
return nil, err
}
spec.anchorNameSanitizer = conv.(converter.AnchorNameSanitizer)
}
return spec, nil
}
// stripEmptyNav strips out empty <nav> tags from content.
func stripEmptyNav(in []byte) []byte {
return bytes.Replace(in, []byte("<nav>\n</nav>\n\n"), []byte(``), -1)
}
// BytesToHTML converts bytes to type template.HTML.
func BytesToHTML(b []byte) template.HTML {
return template.HTML(string(b))
}
// ExtractTOC extracts Table of Contents from content.
func ExtractTOC(content []byte) (newcontent []byte, toc []byte) {
if !bytes.Contains(content, []byte("<nav>")) {
return content, nil
}
origContent := make([]byte, len(content))
copy(origContent, content)
first := []byte(`<nav>
<ul>`)
last := []byte(`</ul>
</nav>`)
replacement := []byte(`<nav id="TableOfContents">
<ul>`)
startOfTOC := bytes.Index(content, first)
peekEnd := min(len(content), 70+startOfTOC)
if startOfTOC < 0 {
return stripEmptyNav(content), toc
}
// Need to peek ahead to see if this nav element is actually the right one.
correctNav := bytes.Index(content[startOfTOC:peekEnd], []byte(`<li><a href="#`))
if correctNav < 0 { // no match found
return content, toc
}
lengthOfTOC := bytes.Index(content[startOfTOC:], last) + len(last)
endOfTOC := startOfTOC + lengthOfTOC
newcontent = append(content[:startOfTOC], content[endOfTOC:]...)
toc = append(replacement, origContent[startOfTOC+len(first):endOfTOC]...)
return
}
func (c *ContentSpec) SanitizeAnchorName(s string) string {
return c.anchorNameSanitizer.SanitizeAnchorName(s)
}
func (c *ContentSpec) ResolveMarkup(in string) string {
in = strings.ToLower(in)
if mediaType, found := c.Cfg.ContentTypes().(media.ContentTypes).Types().GetBestMatch(markup.ResolveMarkup(in)); found {
return mediaType.SubType
}
if conv := c.Converters.Get(in); conv != nil {
return markup.ResolveMarkup(conv.Name())
}
return ""
}
// TotalWords counts instance of one or more consecutive white space
// characters, as defined by unicode.IsSpace, in s.
// This is a cheaper way of word counting than the obvious len(strings.Fields(s)).
func TotalWords(s string) int {
n := 0
inWord := false
for _, r := range s {
wasInWord := inWord
inWord = !unicode.IsSpace(r)
if inWord && !wasInWord {
n++
}
}
return n
}
// TrimShortHTML removes the outer tags from HTML input where (a) the opening
// tag is present only once with the input, and (b) the opening and closing
// tags wrap the input after white space removal.
func (c *ContentSpec) TrimShortHTML(input []byte, markup string) []byte {
openingTag := []byte("<p>")
closingTag := []byte("</p>")
if markup == media.DefaultContentTypes.AsciiDoc.SubType {
openingTag = []byte("<div class=\"paragraph\">\n<p>")
closingTag = []byte("</p>\n</div>")
}
if bytes.Count(input, openingTag) == 1 {
input = bytes.TrimSpace(input)
if bytes.HasPrefix(input, openingTag) && bytes.HasSuffix(input, closingTag) {
input = bytes.TrimPrefix(input, openingTag)
input = bytes.TrimSuffix(input, closingTag)
input = bytes.TrimSpace(input)
}
}
return input
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/deploy/deploy_test.go | deploy/deploy_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.
//go:build withdeploy
package deploy
import (
"bytes"
"compress/gzip"
"context"
"crypto/md5"
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"testing"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/deploy/deployconfig"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/media"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/spf13/afero"
"gocloud.dev/blob"
"gocloud.dev/blob/fileblob"
"gocloud.dev/blob/memblob"
)
func TestFindDiffs(t *testing.T) {
hash1 := []byte("hash 1")
hash2 := []byte("hash 2")
makeLocal := func(path string, size int64, hash []byte) *localFile {
return &localFile{NativePath: path, SlashPath: filepath.ToSlash(path), UploadSize: size, md5: hash}
}
makeRemote := func(path string, size int64, hash []byte) *blob.ListObject {
return &blob.ListObject{Key: path, Size: size, MD5: hash}
}
tests := []struct {
Description string
Local []*localFile
Remote []*blob.ListObject
Force bool
WantUpdates []*fileToUpload
WantDeletes []string
}{
{
Description: "empty -> no diffs",
},
{
Description: "local == remote -> no diffs",
Local: []*localFile{
makeLocal("aaa", 1, hash1),
makeLocal("bbb", 2, hash1),
makeLocal("ccc", 3, hash2),
},
Remote: []*blob.ListObject{
makeRemote("aaa", 1, hash1),
makeRemote("bbb", 2, hash1),
makeRemote("ccc", 3, hash2),
},
},
{
Description: "local w/ separators == remote -> no diffs",
Local: []*localFile{
makeLocal(filepath.Join("aaa", "aaa"), 1, hash1),
makeLocal(filepath.Join("bbb", "bbb"), 2, hash1),
makeLocal(filepath.Join("ccc", "ccc"), 3, hash2),
},
Remote: []*blob.ListObject{
makeRemote("aaa/aaa", 1, hash1),
makeRemote("bbb/bbb", 2, hash1),
makeRemote("ccc/ccc", 3, hash2),
},
},
{
Description: "local == remote with force flag true -> diffs",
Local: []*localFile{
makeLocal("aaa", 1, hash1),
makeLocal("bbb", 2, hash1),
makeLocal("ccc", 3, hash2),
},
Remote: []*blob.ListObject{
makeRemote("aaa", 1, hash1),
makeRemote("bbb", 2, hash1),
makeRemote("ccc", 3, hash2),
},
Force: true,
WantUpdates: []*fileToUpload{
{makeLocal("aaa", 1, nil), reasonForce},
{makeLocal("bbb", 2, nil), reasonForce},
{makeLocal("ccc", 3, nil), reasonForce},
},
},
{
Description: "local == remote with route.Force true -> diffs",
Local: []*localFile{
{NativePath: "aaa", SlashPath: "aaa", UploadSize: 1, matcher: &deployconfig.Matcher{Force: true}, md5: hash1},
makeLocal("bbb", 2, hash1),
},
Remote: []*blob.ListObject{
makeRemote("aaa", 1, hash1),
makeRemote("bbb", 2, hash1),
},
WantUpdates: []*fileToUpload{
{makeLocal("aaa", 1, nil), reasonForce},
},
},
{
Description: "extra local file -> upload",
Local: []*localFile{
makeLocal("aaa", 1, hash1),
makeLocal("bbb", 2, hash2),
},
Remote: []*blob.ListObject{
makeRemote("aaa", 1, hash1),
},
WantUpdates: []*fileToUpload{
{makeLocal("bbb", 2, nil), reasonNotFound},
},
},
{
Description: "extra remote file -> delete",
Local: []*localFile{
makeLocal("aaa", 1, hash1),
},
Remote: []*blob.ListObject{
makeRemote("aaa", 1, hash1),
makeRemote("bbb", 2, hash2),
},
WantDeletes: []string{"bbb"},
},
{
Description: "diffs in size or md5 -> upload",
Local: []*localFile{
makeLocal("aaa", 1, hash1),
makeLocal("bbb", 2, hash1),
makeLocal("ccc", 1, hash2),
},
Remote: []*blob.ListObject{
makeRemote("aaa", 1, nil),
makeRemote("bbb", 1, hash1),
makeRemote("ccc", 1, hash1),
},
WantUpdates: []*fileToUpload{
{makeLocal("aaa", 1, nil), reasonMD5Missing},
{makeLocal("bbb", 2, nil), reasonSize},
{makeLocal("ccc", 1, nil), reasonMD5Differs},
},
},
{
Description: "mix of updates and deletes",
Local: []*localFile{
makeLocal("same", 1, hash1),
makeLocal("updated", 2, hash1),
makeLocal("updated2", 1, hash2),
makeLocal("new", 1, hash1),
makeLocal("new2", 2, hash2),
},
Remote: []*blob.ListObject{
makeRemote("same", 1, hash1),
makeRemote("updated", 1, hash1),
makeRemote("updated2", 1, hash1),
makeRemote("stale", 1, hash1),
makeRemote("stale2", 1, hash1),
},
WantUpdates: []*fileToUpload{
{makeLocal("new", 1, nil), reasonNotFound},
{makeLocal("new2", 2, nil), reasonNotFound},
{makeLocal("updated", 2, nil), reasonSize},
{makeLocal("updated2", 1, nil), reasonMD5Differs},
},
WantDeletes: []string{"stale", "stale2"},
},
}
for _, tc := range tests {
t.Run(tc.Description, func(t *testing.T) {
local := map[string]*localFile{}
for _, l := range tc.Local {
local[l.SlashPath] = l
}
remote := map[string]*blob.ListObject{}
for _, r := range tc.Remote {
remote[r.Key] = r
}
d := newDeployer()
gotUpdates, gotDeletes := d.findDiffs(local, remote, tc.Force)
gotUpdates = applyOrdering(nil, gotUpdates)[0]
sort.Slice(gotDeletes, func(i, j int) bool { return gotDeletes[i] < gotDeletes[j] })
if diff := cmp.Diff(gotUpdates, tc.WantUpdates, cmpopts.IgnoreUnexported(localFile{})); diff != "" {
t.Errorf("updates differ:\n%s", diff)
}
if diff := cmp.Diff(gotDeletes, tc.WantDeletes); diff != "" {
t.Errorf("deletes differ:\n%s", diff)
}
})
}
}
func TestWalkLocal(t *testing.T) {
tests := map[string]struct {
Given []string
Expect []string
MapPath func(string) string
}{
"Empty": {
Given: []string{},
Expect: []string{},
},
"Normal": {
Given: []string{"file.txt", "normal_dir/file.txt"},
Expect: []string{"file.txt", "normal_dir/file.txt"},
},
"Hidden": {
Given: []string{"file.txt", ".hidden_dir/file.txt", "normal_dir/file.txt"},
Expect: []string{"file.txt", "normal_dir/file.txt"},
},
"Well Known": {
Given: []string{"file.txt", ".hidden_dir/file.txt", ".well-known/file.txt"},
Expect: []string{"file.txt", ".well-known/file.txt"},
},
"StripIndexHTML": {
Given: []string{"index.html", "file.txt", "dir/index.html", "dir/file.txt"},
Expect: []string{"index.html", "file.txt", "dir/", "dir/file.txt"},
MapPath: stripIndexHTML,
},
}
for desc, tc := range tests {
t.Run(desc, func(t *testing.T) {
fs := afero.NewMemMapFs()
for _, name := range tc.Given {
dir, _ := path.Split(name)
if dir != "" {
if err := fs.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
}
if fd, err := fs.Create(name); err != nil {
t.Fatal(err)
} else {
fd.Close()
}
}
d := newDeployer()
if got, err := d.walkLocal(fs, nil, nil, nil, media.DefaultTypes, tc.MapPath); err != nil {
t.Fatal(err)
} else {
expect := map[string]any{}
for _, path := range tc.Expect {
if _, ok := got[path]; !ok {
t.Errorf("expected %q in results, but was not found", path)
}
expect[path] = nil
}
for path := range got {
if _, ok := expect[path]; !ok {
t.Errorf("got %q in results unexpectedly", path)
}
}
}
})
}
}
func TestStripIndexHTML(t *testing.T) {
tests := map[string]struct {
Input string
Output string
}{
"Unmapped": {Input: "normal_file.txt", Output: "normal_file.txt"},
"Stripped": {Input: "directory/index.html", Output: "directory/"},
"NoSlash": {Input: "prefix_index.html", Output: "prefix_index.html"},
"Root": {Input: "index.html", Output: "index.html"},
}
for desc, tc := range tests {
t.Run(desc, func(t *testing.T) {
got := stripIndexHTML(tc.Input)
if got != tc.Output {
t.Errorf("got %q, expect %q", got, tc.Output)
}
})
}
}
func TestStripIndexHTMLMatcher(t *testing.T) {
// StripIndexHTML should not affect matchers.
fs := afero.NewMemMapFs()
if err := fs.Mkdir("dir", 0o755); err != nil {
t.Fatal(err)
}
for _, name := range []string{"index.html", "dir/index.html", "file.txt"} {
if fd, err := fs.Create(name); err != nil {
t.Fatal(err)
} else {
fd.Close()
}
}
d := newDeployer()
const pattern = `\.html$`
matcher := &deployconfig.Matcher{Pattern: pattern, Gzip: true, Re: regexp.MustCompile(pattern)}
if got, err := d.walkLocal(fs, []*deployconfig.Matcher{matcher}, nil, nil, media.DefaultTypes, stripIndexHTML); err != nil {
t.Fatal(err)
} else {
for _, name := range []string{"index.html", "dir/"} {
lf := got[name]
if lf == nil {
t.Errorf("missing file %q", name)
} else if lf.matcher == nil {
t.Errorf("file %q has nil matcher, expect %q", name, pattern)
}
}
const name = "file.txt"
lf := got[name]
if lf == nil {
t.Errorf("missing file %q", name)
} else if lf.matcher != nil {
t.Errorf("file %q has matcher %q, expect nil", name, lf.matcher.Pattern)
}
}
}
func TestLocalFile(t *testing.T) {
const (
content = "hello world!"
)
contentBytes := []byte(content)
contentLen := int64(len(contentBytes))
contentMD5 := md5.Sum(contentBytes)
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
if _, err := gz.Write(contentBytes); err != nil {
t.Fatal(err)
}
gz.Close()
gzBytes := buf.Bytes()
gzLen := int64(len(gzBytes))
gzMD5 := md5.Sum(gzBytes)
tests := []struct {
Description string
Path string
Matcher *deployconfig.Matcher
MediaTypesConfig map[string]any
WantContent []byte
WantSize int64
WantMD5 []byte
WantContentType string // empty string is always OK, since content type detection is OS-specific
WantCacheControl string
WantContentEncoding string
}{
{
Description: "file with no suffix",
Path: "foo",
WantContent: contentBytes,
WantSize: contentLen,
WantMD5: contentMD5[:],
},
{
Description: "file with .txt suffix",
Path: "foo.txt",
WantContent: contentBytes,
WantSize: contentLen,
WantMD5: contentMD5[:],
},
{
Description: "CacheControl from matcher",
Path: "foo.txt",
Matcher: &deployconfig.Matcher{CacheControl: "max-age=630720000"},
WantContent: contentBytes,
WantSize: contentLen,
WantMD5: contentMD5[:],
WantCacheControl: "max-age=630720000",
},
{
Description: "ContentEncoding from matcher",
Path: "foo.txt",
Matcher: &deployconfig.Matcher{ContentEncoding: "foobar"},
WantContent: contentBytes,
WantSize: contentLen,
WantMD5: contentMD5[:],
WantContentEncoding: "foobar",
},
{
Description: "ContentType from matcher",
Path: "foo.txt",
Matcher: &deployconfig.Matcher{ContentType: "foo/bar"},
WantContent: contentBytes,
WantSize: contentLen,
WantMD5: contentMD5[:],
WantContentType: "foo/bar",
},
{
Description: "gzipped content",
Path: "foo.txt",
Matcher: &deployconfig.Matcher{Gzip: true},
WantContent: gzBytes,
WantSize: gzLen,
WantMD5: gzMD5[:],
WantContentEncoding: "gzip",
},
{
Description: "Custom MediaType",
Path: "foo.hugo",
MediaTypesConfig: map[string]any{
"hugo/custom": map[string]any{
"suffixes": []string{"hugo"},
},
},
WantContent: contentBytes,
WantSize: contentLen,
WantMD5: contentMD5[:],
WantContentType: "hugo/custom",
},
}
for _, tc := range tests {
t.Run(tc.Description, func(t *testing.T) {
fs := new(afero.MemMapFs)
if err := afero.WriteFile(fs, tc.Path, []byte(content), os.ModePerm); err != nil {
t.Fatal(err)
}
mediaTypes := media.DefaultTypes
if len(tc.MediaTypesConfig) > 0 {
mt, err := media.DecodeTypes(tc.MediaTypesConfig)
if err != nil {
t.Fatal(err)
}
mediaTypes = mt.Config
}
lf, err := newLocalFile(fs, tc.Path, filepath.ToSlash(tc.Path), tc.Matcher, mediaTypes)
if err != nil {
t.Fatal(err)
}
if got := lf.UploadSize; got != tc.WantSize {
t.Errorf("got size %d want %d", got, tc.WantSize)
}
if got := lf.MD5(); !bytes.Equal(got, tc.WantMD5) {
t.Errorf("got MD5 %x want %x", got, tc.WantMD5)
}
if got := lf.CacheControl(); got != tc.WantCacheControl {
t.Errorf("got CacheControl %q want %q", got, tc.WantCacheControl)
}
if got := lf.ContentEncoding(); got != tc.WantContentEncoding {
t.Errorf("got ContentEncoding %q want %q", got, tc.WantContentEncoding)
}
if tc.WantContentType != "" {
if got := lf.ContentType(); got != tc.WantContentType {
t.Errorf("got ContentType %q want %q", got, tc.WantContentType)
}
}
// Verify the reader last to ensure the previous operations don't
// interfere with it.
r, err := lf.Reader()
if err != nil {
t.Fatal(err)
}
gotContent, err := io.ReadAll(r)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(gotContent, tc.WantContent) {
t.Errorf("got content %q want %q", string(gotContent), string(tc.WantContent))
}
r.Close()
// Verify we can read again.
r, err = lf.Reader()
if err != nil {
t.Fatal(err)
}
gotContent, err = io.ReadAll(r)
if err != nil {
t.Fatal(err)
}
r.Close()
if !bytes.Equal(gotContent, tc.WantContent) {
t.Errorf("got content %q want %q", string(gotContent), string(tc.WantContent))
}
})
}
}
func TestOrdering(t *testing.T) {
tests := []struct {
Description string
Uploads []string
Ordering []*regexp.Regexp
Want [][]string
}{
{
Description: "empty",
Want: [][]string{nil},
},
{
Description: "no ordering",
Uploads: []string{"c", "b", "a", "d"},
Want: [][]string{{"a", "b", "c", "d"}},
},
{
Description: "one ordering",
Uploads: []string{"db", "c", "b", "a", "da"},
Ordering: []*regexp.Regexp{regexp.MustCompile("^d")},
Want: [][]string{{"da", "db"}, {"a", "b", "c"}},
},
{
Description: "two orderings",
Uploads: []string{"db", "c", "b", "a", "da"},
Ordering: []*regexp.Regexp{
regexp.MustCompile("^d"),
regexp.MustCompile("^b"),
},
Want: [][]string{{"da", "db"}, {"b"}, {"a", "c"}},
},
}
for _, tc := range tests {
t.Run(tc.Description, func(t *testing.T) {
uploads := make([]*fileToUpload, len(tc.Uploads))
for i, u := range tc.Uploads {
uploads[i] = &fileToUpload{Local: &localFile{SlashPath: u}}
}
gotUploads := applyOrdering(tc.Ordering, uploads)
var got [][]string
for _, subslice := range gotUploads {
var gotsubslice []string
for _, u := range subslice {
gotsubslice = append(gotsubslice, u.Local.SlashPath)
}
got = append(got, gotsubslice)
}
if diff := cmp.Diff(got, tc.Want); diff != "" {
t.Error(diff)
}
})
}
}
type fileData struct {
Name string // name of the file
Contents string // contents of the file
}
// initLocalFs initializes fs with some test files.
func initLocalFs(ctx context.Context, fs afero.Fs) ([]*fileData, error) {
// The initial local filesystem.
local := []*fileData{
{"aaa", "aaa"},
{"bbb", "bbb"},
{"subdir/aaa", "subdir-aaa"},
{"subdir/nested/aaa", "subdir-nested-aaa"},
{"subdir2/bbb", "subdir2-bbb"},
}
if err := writeFiles(fs, local); err != nil {
return nil, err
}
return local, nil
}
// fsTest represents an (afero.FS, Go CDK blob.Bucket) against which end-to-end
// tests can be run.
type fsTest struct {
name string
fs afero.Fs
bucket *blob.Bucket
}
// initFsTests initializes a pair of tests for end-to-end test:
// 1. An in-memory afero.Fs paired with an in-memory Go CDK bucket.
// 2. A filesystem-based afero.Fs paired with an filesystem-based Go CDK bucket.
// It returns the pair of tests and a cleanup function.
func initFsTests(t *testing.T) []*fsTest {
t.Helper()
tmpfsdir := t.TempDir()
tmpbucketdir := t.TempDir()
memfs := afero.NewMemMapFs()
membucket := memblob.OpenBucket(nil)
t.Cleanup(func() { membucket.Close() })
filefs := hugofs.NewBasePathFs(afero.NewOsFs(), tmpfsdir)
filebucket, err := fileblob.OpenBucket(tmpbucketdir, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { filebucket.Close() })
tests := []*fsTest{
{"mem", memfs, membucket},
{"file", filefs, filebucket},
}
return tests
}
// TestEndToEndSync verifies that basic adds, updates, and deletes are working
// correctly.
func TestEndToEndSync(t *testing.T) {
ctx := context.Background()
tests := initFsTests(t)
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
local, err := initLocalFs(ctx, test.fs)
if err != nil {
t.Fatal(err)
}
deployer := &Deployer{
localFs: test.fs,
bucket: test.bucket,
mediaTypes: media.DefaultTypes,
cfg: deployconfig.DeployConfig{Workers: 2, MaxDeletes: -1},
}
// Initial deployment should sync remote with local.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("initial deploy: failed: %v", err)
}
wantSummary := deploySummary{NumLocal: 5, NumRemote: 0, NumUploads: 5, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("initial deploy: got %v, want %v", deployer.summary, wantSummary)
}
if diff, err := verifyRemote(ctx, deployer.bucket, local); err != nil {
t.Errorf("initial deploy: failed to verify remote: %v", err)
} else if diff != "" {
t.Errorf("initial deploy: remote snapshot doesn't match expected:\n%v", diff)
}
// A repeat deployment shouldn't change anything.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("no-op deploy: %v", err)
}
wantSummary = deploySummary{NumLocal: 5, NumRemote: 5, NumUploads: 0, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("no-op deploy: got %v, want %v", deployer.summary, wantSummary)
}
// Make some changes to the local filesystem:
// 1. Modify file [0].
// 2. Delete file [1].
// 3. Add a new file (sorted last).
updatefd := local[0]
updatefd.Contents = "new contents"
deletefd := local[1]
local = append(local[:1], local[2:]...) // removing deleted [1]
newfd := &fileData{"zzz", "zzz"}
local = append(local, newfd)
if err := writeFiles(test.fs, []*fileData{updatefd, newfd}); err != nil {
t.Fatal(err)
}
if err := test.fs.Remove(deletefd.Name); err != nil {
t.Fatal(err)
}
// A deployment should apply those 3 changes.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("deploy after changes: failed: %v", err)
}
wantSummary = deploySummary{NumLocal: 5, NumRemote: 5, NumUploads: 2, NumDeletes: 1}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("deploy after changes: got %v, want %v", deployer.summary, wantSummary)
}
if diff, err := verifyRemote(ctx, deployer.bucket, local); err != nil {
t.Errorf("deploy after changes: failed to verify remote: %v", err)
} else if diff != "" {
t.Errorf("deploy after changes: remote snapshot doesn't match expected:\n%v", diff)
}
// Again, a repeat deployment shouldn't change anything.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("no-op deploy: %v", err)
}
wantSummary = deploySummary{NumLocal: 5, NumRemote: 5, NumUploads: 0, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("no-op deploy: got %v, want %v", deployer.summary, wantSummary)
}
})
}
}
// TestMaxDeletes verifies that the "maxDeletes" flag is working correctly.
func TestMaxDeletes(t *testing.T) {
ctx := context.Background()
tests := initFsTests(t)
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
local, err := initLocalFs(ctx, test.fs)
if err != nil {
t.Fatal(err)
}
deployer := &Deployer{
localFs: test.fs,
bucket: test.bucket,
mediaTypes: media.DefaultTypes,
cfg: deployconfig.DeployConfig{Workers: 2, MaxDeletes: -1},
}
// Sync remote with local.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("initial deploy: failed: %v", err)
}
wantSummary := deploySummary{NumLocal: 5, NumRemote: 0, NumUploads: 5, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("initial deploy: got %v, want %v", deployer.summary, wantSummary)
}
// Delete two files, [1] and [2].
if err := test.fs.Remove(local[1].Name); err != nil {
t.Fatal(err)
}
if err := test.fs.Remove(local[2].Name); err != nil {
t.Fatal(err)
}
// A deployment with maxDeletes=0 shouldn't change anything.
deployer.cfg.MaxDeletes = 0
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("deploy failed: %v", err)
}
wantSummary = deploySummary{NumLocal: 3, NumRemote: 5, NumUploads: 0, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("deploy: got %v, want %v", deployer.summary, wantSummary)
}
// A deployment with maxDeletes=1 shouldn't change anything either.
deployer.cfg.MaxDeletes = 1
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("deploy failed: %v", err)
}
wantSummary = deploySummary{NumLocal: 3, NumRemote: 5, NumUploads: 0, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("deploy: got %v, want %v", deployer.summary, wantSummary)
}
// A deployment with maxDeletes=2 should make the changes.
deployer.cfg.MaxDeletes = 2
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("deploy failed: %v", err)
}
wantSummary = deploySummary{NumLocal: 3, NumRemote: 5, NumUploads: 0, NumDeletes: 2}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("deploy: got %v, want %v", deployer.summary, wantSummary)
}
// Delete two more files, [0] and [3].
if err := test.fs.Remove(local[0].Name); err != nil {
t.Fatal(err)
}
if err := test.fs.Remove(local[3].Name); err != nil {
t.Fatal(err)
}
// A deployment with maxDeletes=-1 should make the changes.
deployer.cfg.MaxDeletes = -1
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("deploy failed: %v", err)
}
wantSummary = deploySummary{NumLocal: 1, NumRemote: 3, NumUploads: 0, NumDeletes: 2}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("deploy: got %v, want %v", deployer.summary, wantSummary)
}
})
}
}
// TestIncludeExclude verifies that the include/exclude options for targets work.
func TestIncludeExclude(t *testing.T) {
ctx := context.Background()
tests := []struct {
Include string
Exclude string
Want deploySummary
}{
{
Want: deploySummary{NumLocal: 5, NumUploads: 5},
},
{
Include: "**aaa",
Want: deploySummary{NumLocal: 3, NumUploads: 3},
},
{
Include: "**bbb",
Want: deploySummary{NumLocal: 2, NumUploads: 2},
},
{
Include: "aaa",
Want: deploySummary{NumLocal: 1, NumUploads: 1},
},
{
Exclude: "**aaa",
Want: deploySummary{NumLocal: 2, NumUploads: 2},
},
{
Exclude: "**bbb",
Want: deploySummary{NumLocal: 3, NumUploads: 3},
},
{
Exclude: "aaa",
Want: deploySummary{NumLocal: 4, NumUploads: 4},
},
{
Include: "**aaa",
Exclude: "**nested**",
Want: deploySummary{NumLocal: 2, NumUploads: 2},
},
}
for _, test := range tests {
t.Run(fmt.Sprintf("include %q exclude %q", test.Include, test.Exclude), func(t *testing.T) {
fsTests := initFsTests(t)
fsTest := fsTests[1] // just do file-based test
_, err := initLocalFs(ctx, fsTest.fs)
if err != nil {
t.Fatal(err)
}
tgt := &deployconfig.Target{
Include: test.Include,
Exclude: test.Exclude,
}
if err := tgt.ParseIncludeExclude(); err != nil {
t.Error(err)
}
deployer := &Deployer{
localFs: fsTest.fs,
cfg: deployconfig.DeployConfig{Workers: 2, MaxDeletes: -1}, bucket: fsTest.bucket,
target: tgt,
mediaTypes: media.DefaultTypes,
}
// Sync remote with local.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("deploy: failed: %v", err)
}
if !cmp.Equal(deployer.summary, test.Want) {
t.Errorf("deploy: got %v, want %v", deployer.summary, test.Want)
}
})
}
}
// TestIncludeExcludeRemoteDelete verifies deleted local files that don't match include/exclude patterns
// are not deleted on the remote.
func TestIncludeExcludeRemoteDelete(t *testing.T) {
ctx := context.Background()
tests := []struct {
Include string
Exclude string
Want deploySummary
}{
{
Want: deploySummary{NumLocal: 3, NumRemote: 5, NumUploads: 0, NumDeletes: 2},
},
{
Include: "**aaa",
Want: deploySummary{NumLocal: 2, NumRemote: 3, NumUploads: 0, NumDeletes: 1},
},
{
Include: "subdir/**",
Want: deploySummary{NumLocal: 1, NumRemote: 2, NumUploads: 0, NumDeletes: 1},
},
{
Exclude: "**bbb",
Want: deploySummary{NumLocal: 2, NumRemote: 3, NumUploads: 0, NumDeletes: 1},
},
{
Exclude: "bbb",
Want: deploySummary{NumLocal: 3, NumRemote: 4, NumUploads: 0, NumDeletes: 1},
},
}
for _, test := range tests {
t.Run(fmt.Sprintf("include %q exclude %q", test.Include, test.Exclude), func(t *testing.T) {
fsTests := initFsTests(t)
fsTest := fsTests[1] // just do file-based test
local, err := initLocalFs(ctx, fsTest.fs)
if err != nil {
t.Fatal(err)
}
deployer := &Deployer{
localFs: fsTest.fs,
cfg: deployconfig.DeployConfig{Workers: 2, MaxDeletes: -1}, bucket: fsTest.bucket,
mediaTypes: media.DefaultTypes,
}
// Initial sync to get the files on the remote
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("deploy: failed: %v", err)
}
// Delete two files, [1] and [2].
if err := fsTest.fs.Remove(local[1].Name); err != nil {
t.Fatal(err)
}
if err := fsTest.fs.Remove(local[2].Name); err != nil {
t.Fatal(err)
}
// Second sync
tgt := &deployconfig.Target{
Include: test.Include,
Exclude: test.Exclude,
}
if err := tgt.ParseIncludeExclude(); err != nil {
t.Error(err)
}
deployer.target = tgt
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("deploy: failed: %v", err)
}
if !cmp.Equal(deployer.summary, test.Want) {
t.Errorf("deploy: got %v, want %v", deployer.summary, test.Want)
}
})
}
}
// TestCompression verifies that gzip compression works correctly.
// In particular, MD5 hashes must be of the compressed content.
func TestCompression(t *testing.T) {
ctx := context.Background()
tests := initFsTests(t)
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
local, err := initLocalFs(ctx, test.fs)
if err != nil {
t.Fatal(err)
}
deployer := &Deployer{
localFs: test.fs,
bucket: test.bucket,
cfg: deployconfig.DeployConfig{Workers: 2, MaxDeletes: -1, Matchers: []*deployconfig.Matcher{{Pattern: ".*", Gzip: true, Re: regexp.MustCompile(".*")}}},
mediaTypes: media.DefaultTypes,
}
// Initial deployment should sync remote with local.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("initial deploy: failed: %v", err)
}
wantSummary := deploySummary{NumLocal: 5, NumRemote: 0, NumUploads: 5, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("initial deploy: got %v, want %v", deployer.summary, wantSummary)
}
// A repeat deployment shouldn't change anything.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("no-op deploy: %v", err)
}
wantSummary = deploySummary{NumLocal: 5, NumRemote: 5, NumUploads: 0, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("no-op deploy: got %v, want %v", deployer.summary, wantSummary)
}
// Make an update to the local filesystem, on [1].
updatefd := local[1]
updatefd.Contents = "new contents"
if err := writeFiles(test.fs, []*fileData{updatefd}); err != nil {
t.Fatal(err)
}
// A deployment should apply the changes.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("deploy after changes: failed: %v", err)
}
wantSummary = deploySummary{NumLocal: 5, NumRemote: 5, NumUploads: 1, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("deploy after changes: got %v, want %v", deployer.summary, wantSummary)
}
})
}
}
// TestMatching verifies that matchers match correctly, and that the Force
// attribute for matcher works.
func TestMatching(t *testing.T) {
ctx := context.Background()
tests := initFsTests(t)
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := initLocalFs(ctx, test.fs)
if err != nil {
t.Fatal(err)
}
deployer := &Deployer{
localFs: test.fs,
bucket: test.bucket,
cfg: deployconfig.DeployConfig{Workers: 2, MaxDeletes: -1, Matchers: []*deployconfig.Matcher{{Pattern: "^subdir/aaa$", Force: true, Re: regexp.MustCompile("^subdir/aaa$")}}},
mediaTypes: media.DefaultTypes,
}
// Initial deployment to sync remote with local.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("initial deploy: failed: %v", err)
}
wantSummary := deploySummary{NumLocal: 5, NumRemote: 0, NumUploads: 5, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("initial deploy: got %v, want %v", deployer.summary, wantSummary)
}
// A repeat deployment should upload a single file, the one that matched the Force matcher.
// Note that matching happens based on the ToSlash form, so this matches
// even on Windows.
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("no-op deploy with single force matcher: %v", err)
}
wantSummary = deploySummary{NumLocal: 5, NumRemote: 5, NumUploads: 1, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("no-op deploy with single force matcher: got %v, want %v", deployer.summary, wantSummary)
}
// Repeat with a matcher that should now match 3 files.
deployer.cfg.Matchers = []*deployconfig.Matcher{{Pattern: "aaa", Force: true, Re: regexp.MustCompile("aaa")}}
if err := deployer.Deploy(ctx); err != nil {
t.Errorf("no-op deploy with triple force matcher: %v", err)
}
wantSummary = deploySummary{NumLocal: 5, NumRemote: 5, NumUploads: 3, NumDeletes: 0}
if !cmp.Equal(deployer.summary, wantSummary) {
t.Errorf("no-op deploy with triple force matcher: got %v, want %v", deployer.summary, wantSummary)
}
})
}
}
// writeFiles writes the files in fds to fd.
func writeFiles(fs afero.Fs, fds []*fileData) error {
for _, fd := range fds {
dir := path.Dir(fd.Name)
if dir != "." {
err := fs.MkdirAll(dir, os.ModePerm)
if err != nil {
return err
}
}
f, err := fs.Create(fd.Name)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(fd.Contents)
if err != nil {
return err
}
}
return nil
}
// verifyRemote that the current contents of bucket matches local.
// It returns an empty string if the contents matched, and a non-empty string
// capturing the diff if they didn't.
func verifyRemote(ctx context.Context, bucket *blob.Bucket, local []*fileData) (string, error) {
var cur []*fileData
iter := bucket.List(nil)
for {
obj, err := iter.Next(ctx)
if err == io.EOF {
break
}
if err != nil {
return "", err
}
contents, err := bucket.ReadAll(ctx, obj.Key)
if err != nil {
return "", err
}
cur = append(cur, &fileData{obj.Key, string(contents)})
}
if cmp.Equal(cur, local) {
return "", nil
}
diff := "got: \n"
for _, f := range cur {
diff += fmt.Sprintf(" %s: %s\n", f.Name, f.Contents)
}
diff += "want: \n"
for _, f := range local {
diff += fmt.Sprintf(" %s: %s\n", f.Name, f.Contents)
}
return diff, nil
}
func newDeployer() *Deployer {
return &Deployer{
logger: loggers.NewDefault(),
cfg: deployconfig.DeployConfig{Workers: 2},
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/deploy/deploy.go | deploy/deploy.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.
//go:build withdeploy
package deploy
import (
"bytes"
"compress/gzip"
"context"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"mime"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"github.com/dustin/go-humanize"
"github.com/gobwas/glob"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/common/para"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/deploy/deployconfig"
"github.com/gohugoio/hugo/media"
"github.com/spf13/afero"
"golang.org/x/text/unicode/norm"
"gocloud.dev/blob"
_ "gocloud.dev/blob/fileblob" // import
_ "gocloud.dev/blob/gcsblob" // import
_ "gocloud.dev/blob/s3blob" // import
"gocloud.dev/gcerrors"
)
// Deployer supports deploying the site to target cloud providers.
type Deployer struct {
localFs afero.Fs
bucket *blob.Bucket
mediaTypes media.Types // Hugo's MediaType to guess ContentType
quiet bool // true reduces STDOUT // TODO(bep) remove, this is a global feature.
cfg deployconfig.DeployConfig
logger loggers.Logger
target *deployconfig.Target // the target to deploy to
// For tests...
summary deploySummary // summary of latest Deploy results
}
type deploySummary struct {
NumLocal, NumRemote, NumUploads, NumDeletes int
}
const metaMD5Hash = "md5chksum" // the meta key to store md5hash in
// New constructs a new *Deployer.
func New(cfg config.AllProvider, logger loggers.Logger, localFs afero.Fs) (*Deployer, error) {
dcfg := cfg.GetConfigSection(deployconfig.DeploymentConfigKey).(deployconfig.DeployConfig)
targetName := dcfg.Target
if len(dcfg.Targets) == 0 {
return nil, errors.New("no deployment targets found")
}
mediaTypes := cfg.GetConfigSection("mediaTypes").(media.Types)
// Find the target to deploy to.
var tgt *deployconfig.Target
if targetName == "" {
// Default to the first target.
tgt = dcfg.Targets[0]
} else {
for _, t := range dcfg.Targets {
if t.Name == targetName {
tgt = t
}
}
if tgt == nil {
return nil, fmt.Errorf("deployment target %q not found", targetName)
}
}
return &Deployer{
localFs: localFs,
target: tgt,
quiet: cfg.BuildExpired(),
mediaTypes: mediaTypes,
cfg: dcfg,
}, nil
}
func (d *Deployer) openBucket(ctx context.Context) (*blob.Bucket, error) {
if d.bucket != nil {
return d.bucket, nil
}
d.logger.Printf("Deploying to target %q (%s)\n", d.target.Name, d.target.URL)
return blob.OpenBucket(ctx, d.target.URL)
}
// Deploy deploys the site to a target.
func (d *Deployer) Deploy(ctx context.Context) error {
if d.logger == nil {
d.logger = loggers.NewDefault()
}
bucket, err := d.openBucket(ctx)
if err != nil {
return err
}
if d.cfg.Workers <= 0 {
d.cfg.Workers = 10
}
// Load local files from the source directory.
var include, exclude glob.Glob
var mappath func(string) string
if d.target != nil {
include, exclude = d.target.IncludeGlob, d.target.ExcludeGlob
if d.target.StripIndexHTML {
mappath = stripIndexHTML
}
}
local, err := d.walkLocal(d.localFs, d.cfg.Matchers, include, exclude, d.mediaTypes, mappath)
if err != nil {
return err
}
d.logger.Infof("Found %d local files.\n", len(local))
d.summary.NumLocal = len(local)
// Load remote files from the target.
remote, err := d.walkRemote(ctx, bucket, include, exclude)
if err != nil {
return err
}
d.logger.Infof("Found %d remote files.\n", len(remote))
d.summary.NumRemote = len(remote)
// Diff local vs remote to see what changes need to be applied.
uploads, deletes := d.findDiffs(local, remote, d.cfg.Force)
d.summary.NumUploads = len(uploads)
d.summary.NumDeletes = len(deletes)
if len(uploads)+len(deletes) == 0 {
if !d.quiet {
d.logger.Println("No changes required.")
}
return nil
}
if !d.quiet {
d.logger.Println(summarizeChanges(uploads, deletes))
}
// Ask for confirmation before proceeding.
if d.cfg.Confirm && !d.cfg.DryRun {
fmt.Printf("Continue? (Y/n) ")
var confirm string
if _, err := fmt.Scanln(&confirm); err != nil {
return err
}
if confirm != "" && confirm[0] != 'y' && confirm[0] != 'Y' {
return errors.New("aborted")
}
}
// Order the uploads. They are organized in groups; all uploads in a group
// must be complete before moving on to the next group.
uploadGroups := applyOrdering(d.cfg.Ordering, uploads)
nParallel := d.cfg.Workers
var errs []error
var errMu sync.Mutex // protects errs
for _, uploads := range uploadGroups {
// Short-circuit for an empty group.
if len(uploads) == 0 {
continue
}
// Within the group, apply uploads in parallel.
sem := make(chan struct{}, nParallel)
for _, upload := range uploads {
if d.cfg.DryRun {
if !d.quiet {
d.logger.Printf("[DRY RUN] Would upload: %v\n", upload)
}
continue
}
sem <- struct{}{}
go func(upload *fileToUpload) {
if err := d.doSingleUpload(ctx, bucket, upload); err != nil {
errMu.Lock()
defer errMu.Unlock()
errs = append(errs, err)
}
<-sem
}(upload)
}
// Wait for all uploads in the group to finish.
for n := nParallel; n > 0; n-- {
sem <- struct{}{}
}
}
if d.cfg.MaxDeletes != -1 && len(deletes) > d.cfg.MaxDeletes {
d.logger.Warnf("Skipping %d deletes because it is more than --maxDeletes (%d). If this is expected, set --maxDeletes to a larger number, or -1 to disable this check.\n", len(deletes), d.cfg.MaxDeletes)
d.summary.NumDeletes = 0
} else {
// Apply deletes in parallel.
sort.Slice(deletes, func(i, j int) bool { return deletes[i] < deletes[j] })
sem := make(chan struct{}, nParallel)
for _, del := range deletes {
if d.cfg.DryRun {
if !d.quiet {
d.logger.Printf("[DRY RUN] Would delete %s\n", del)
}
continue
}
sem <- struct{}{}
go func(del string) {
d.logger.Infof("Deleting %s...\n", del)
if err := bucket.Delete(ctx, del); err != nil {
if gcerrors.Code(err) == gcerrors.NotFound {
d.logger.Warnf("Failed to delete %q because it wasn't found: %v", del, err)
} else {
errMu.Lock()
defer errMu.Unlock()
errs = append(errs, err)
}
}
<-sem
}(del)
}
// Wait for all deletes to finish.
for n := nParallel; n > 0; n-- {
sem <- struct{}{}
}
}
if len(errs) > 0 {
if !d.quiet {
d.logger.Printf("Encountered %d errors.\n", len(errs))
}
return errs[0]
}
if !d.quiet {
d.logger.Println("Success!")
}
if d.cfg.InvalidateCDN {
if d.target.CloudFrontDistributionID != "" {
if d.cfg.DryRun {
if !d.quiet {
d.logger.Printf("[DRY RUN] Would invalidate CloudFront CDN with ID %s\n", d.target.CloudFrontDistributionID)
}
} else {
d.logger.Println("Invalidating CloudFront CDN...")
if err := InvalidateCloudFront(ctx, d.target); err != nil {
d.logger.Printf("Failed to invalidate CloudFront CDN: %v\n", err)
return err
}
}
}
if d.target.GoogleCloudCDNOrigin != "" {
if d.cfg.DryRun {
if !d.quiet {
d.logger.Printf("[DRY RUN] Would invalidate Google Cloud CDN with origin %s\n", d.target.GoogleCloudCDNOrigin)
}
} else {
d.logger.Println("Invalidating Google Cloud CDN...")
if err := InvalidateGoogleCloudCDN(ctx, d.target.GoogleCloudCDNOrigin); err != nil {
d.logger.Printf("Failed to invalidate Google Cloud CDN: %v\n", err)
return err
}
}
}
d.logger.Println("Success!")
}
return nil
}
// summarizeChanges creates a text description of the proposed changes.
func summarizeChanges(uploads []*fileToUpload, deletes []string) string {
uploadSize := int64(0)
for _, u := range uploads {
uploadSize += u.Local.UploadSize
}
return fmt.Sprintf("Identified %d file(s) to upload, totaling %s, and %d file(s) to delete.", len(uploads), humanize.Bytes(uint64(uploadSize)), len(deletes))
}
// doSingleUpload executes a single file upload.
func (d *Deployer) doSingleUpload(ctx context.Context, bucket *blob.Bucket, upload *fileToUpload) error {
d.logger.Infof("Uploading %v...\n", upload)
opts := &blob.WriterOptions{
CacheControl: upload.Local.CacheControl(),
ContentEncoding: upload.Local.ContentEncoding(),
ContentType: upload.Local.ContentType(),
Metadata: map[string]string{metaMD5Hash: hex.EncodeToString(upload.Local.MD5())},
}
w, err := bucket.NewWriter(ctx, upload.Local.SlashPath, opts)
if err != nil {
return err
}
r, err := upload.Local.Reader()
if err != nil {
return err
}
defer r.Close()
_, err = io.Copy(w, r)
if err != nil {
return err
}
if err := w.Close(); err != nil {
return err
}
return nil
}
// localFile represents a local file from the source. Use newLocalFile to
// construct one.
type localFile struct {
// NativePath is the native path to the file (using file.Separator).
NativePath string
// SlashPath is NativePath converted to use /.
SlashPath string
// UploadSize is the size of the content to be uploaded. It may not
// be the same as the local file size if the content will be
// gzipped before upload.
UploadSize int64
fs afero.Fs
matcher *deployconfig.Matcher
md5 []byte // cache
gzipped bytes.Buffer // cached of gzipped contents if gzipping
mediaTypes media.Types
}
// newLocalFile initializes a *localFile.
func newLocalFile(fs afero.Fs, nativePath, slashpath string, m *deployconfig.Matcher, mt media.Types) (*localFile, error) {
f, err := fs.Open(nativePath)
if err != nil {
return nil, err
}
defer f.Close()
lf := &localFile{
NativePath: nativePath,
SlashPath: slashpath,
fs: fs,
matcher: m,
mediaTypes: mt,
}
if m != nil && m.Gzip {
// We're going to gzip the content. Do it once now, and cache the result
// in gzipped. The UploadSize is the size of the gzipped content.
gz := gzip.NewWriter(&lf.gzipped)
if _, err := io.Copy(gz, f); err != nil {
return nil, err
}
if err := gz.Close(); err != nil {
return nil, err
}
lf.UploadSize = int64(lf.gzipped.Len())
} else {
// Raw content. Just get the UploadSize.
info, err := f.Stat()
if err != nil {
return nil, err
}
lf.UploadSize = info.Size()
}
return lf, nil
}
// Reader returns an io.ReadCloser for reading the content to be uploaded.
// The caller must call Close on the returned ReaderCloser.
// The reader content may not be the same as the local file content due to
// gzipping.
func (lf *localFile) Reader() (io.ReadCloser, error) {
if lf.matcher != nil && lf.matcher.Gzip {
// We've got the gzipped contents cached in gzipped.
// Note: we can't use lf.gzipped directly as a Reader, since we it discards
// data after it is read, and we may read it more than once.
return io.NopCloser(bytes.NewReader(lf.gzipped.Bytes())), nil
}
// Not expected to fail since we did it successfully earlier in newLocalFile,
// but could happen due to changes in the underlying filesystem.
return lf.fs.Open(lf.NativePath)
}
// CacheControl returns the Cache-Control header to use for lf, based on the
// first matching matcher (if any).
func (lf *localFile) CacheControl() string {
if lf.matcher == nil {
return ""
}
return lf.matcher.CacheControl
}
// ContentEncoding returns the Content-Encoding header to use for lf, based
// on the matcher's Content-Encoding and Gzip fields.
func (lf *localFile) ContentEncoding() string {
if lf.matcher == nil {
return ""
}
if lf.matcher.Gzip {
return "gzip"
}
return lf.matcher.ContentEncoding
}
// ContentType returns the Content-Type header to use for lf.
// It first checks if there's a Content-Type header configured via a matching
// matcher; if not, it tries to generate one based on the filename extension.
// If this fails, the Content-Type will be the empty string. In this case, Go
// Cloud will automatically try to infer a Content-Type based on the file
// content.
func (lf *localFile) ContentType() string {
if lf.matcher != nil && lf.matcher.ContentType != "" {
return lf.matcher.ContentType
}
ext := filepath.Ext(lf.NativePath)
if mimeType, _, found := lf.mediaTypes.GetFirstBySuffix(strings.TrimPrefix(ext, ".")); found {
return mimeType.Type
}
return mime.TypeByExtension(ext)
}
// Force returns true if the file should be forced to re-upload based on the
// matching matcher.
func (lf *localFile) Force() bool {
return lf.matcher != nil && lf.matcher.Force
}
// MD5 returns an MD5 hash of the content to be uploaded.
func (lf *localFile) MD5() []byte {
if len(lf.md5) > 0 {
return lf.md5
}
h := md5.New()
r, err := lf.Reader()
if err != nil {
return nil
}
defer r.Close()
if _, err := io.Copy(h, r); err != nil {
return nil
}
lf.md5 = h.Sum(nil)
return lf.md5
}
// knownHiddenDirectory checks if the specified name is a well known
// hidden directory.
func knownHiddenDirectory(name string) bool {
knownDirectories := []string{
".well-known",
}
for _, dir := range knownDirectories {
if name == dir {
return true
}
}
return false
}
// walkLocal walks the source directory and returns a flat list of files,
// using localFile.SlashPath as the map keys.
func (d *Deployer) walkLocal(fs afero.Fs, matchers []*deployconfig.Matcher, include, exclude glob.Glob, mediaTypes media.Types, mappath func(string) string) (map[string]*localFile, error) {
retval := make(map[string]*localFile)
var mu sync.Mutex
workers := para.New(d.cfg.Workers)
g, _ := workers.Start(context.Background())
err := afero.Walk(fs, "", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
// Skip hidden directories.
if path != "" && strings.HasPrefix(info.Name(), ".") {
// Except for specific hidden directories
if !knownHiddenDirectory(info.Name()) {
return filepath.SkipDir
}
}
return nil
}
// .DS_Store is an internal MacOS attribute file; skip it.
if info.Name() == ".DS_Store" {
return nil
}
// Process each file in a worker
g.Run(func() error {
// When a file system is HFS+, its filepath is in NFD form.
if runtime.GOOS == "darwin" {
path = norm.NFC.String(path)
}
// Check include/exclude matchers.
slashpath := filepath.ToSlash(path)
if include != nil && !include.Match(slashpath) {
d.logger.Infof(" dropping %q due to include\n", slashpath)
return nil
}
if exclude != nil && exclude.Match(slashpath) {
d.logger.Infof(" dropping %q due to exclude\n", slashpath)
return nil
}
// Find the first matching matcher (if any).
var m *deployconfig.Matcher
for _, cur := range matchers {
if cur.Matches(slashpath) {
m = cur
break
}
}
// Apply any additional modifications to the local path, to map it to
// the remote path.
if mappath != nil {
slashpath = mappath(slashpath)
}
lf, err := newLocalFile(fs, path, slashpath, m, mediaTypes)
if err != nil {
return err
}
mu.Lock()
retval[lf.SlashPath] = lf
mu.Unlock()
return nil
})
return nil
})
if err != nil {
return nil, err
}
if err := g.Wait(); err != nil {
return nil, err
}
return retval, nil
}
// stripIndexHTML remaps keys matching "<dir>/index.html" to "<dir>/".
func stripIndexHTML(slashpath string) string {
const suffix = "/index.html"
if strings.HasSuffix(slashpath, suffix) {
return slashpath[:len(slashpath)-len(suffix)+1]
}
return slashpath
}
// walkRemote walks the target bucket and returns a flat list.
func (d *Deployer) walkRemote(ctx context.Context, bucket *blob.Bucket, include, exclude glob.Glob) (map[string]*blob.ListObject, error) {
retval := map[string]*blob.ListObject{}
iter := bucket.List(nil)
for {
obj, err := iter.Next(ctx)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
// Check include/exclude matchers.
if include != nil && !include.Match(obj.Key) {
d.logger.Infof(" remote dropping %q due to include\n", obj.Key)
continue
}
if exclude != nil && exclude.Match(obj.Key) {
d.logger.Infof(" remote dropping %q due to exclude\n", obj.Key)
continue
}
// If the remote didn't give us an MD5, use remote attributes MD5, if that doesn't exist compute one.
// This can happen for some providers (e.g., fileblob, which uses the
// local filesystem), but not for the most common Cloud providers
// (S3, GCS, Azure). Although, it can happen for S3 if the blob was uploaded
// via a multi-part upload.
// Although it's unfortunate to have to read the file, it's likely better
// than assuming a delta and re-uploading it.
if len(obj.MD5) == 0 {
var attrMD5 []byte
attrs, err := bucket.Attributes(ctx, obj.Key)
if err == nil {
md5String, exists := attrs.Metadata[metaMD5Hash]
if exists {
attrMD5, _ = hex.DecodeString(md5String)
}
}
if len(attrMD5) == 0 {
r, err := bucket.NewReader(ctx, obj.Key, nil)
if err == nil {
h := md5.New()
if _, err := io.Copy(h, r); err == nil {
obj.MD5 = h.Sum(nil)
}
r.Close()
}
} else {
obj.MD5 = attrMD5
}
}
retval[obj.Key] = obj
}
return retval, nil
}
// uploadReason is an enum of reasons why a file must be uploaded.
type uploadReason string
const (
reasonUnknown uploadReason = "unknown"
reasonNotFound uploadReason = "not found at target"
reasonForce uploadReason = "--force"
reasonSize uploadReason = "size differs"
reasonMD5Differs uploadReason = "md5 differs"
reasonMD5Missing uploadReason = "remote md5 missing"
)
// fileToUpload represents a single local file that should be uploaded to
// the target.
type fileToUpload struct {
Local *localFile
Reason uploadReason
}
func (u *fileToUpload) String() string {
details := []string{humanize.Bytes(uint64(u.Local.UploadSize))}
if s := u.Local.CacheControl(); s != "" {
details = append(details, fmt.Sprintf("Cache-Control: %q", s))
}
if s := u.Local.ContentEncoding(); s != "" {
details = append(details, fmt.Sprintf("Content-Encoding: %q", s))
}
if s := u.Local.ContentType(); s != "" {
details = append(details, fmt.Sprintf("Content-Type: %q", s))
}
return fmt.Sprintf("%s (%s): %v", u.Local.SlashPath, strings.Join(details, ", "), u.Reason)
}
// findDiffs diffs localFiles vs remoteFiles to see what changes should be
// applied to the remote target. It returns a slice of *fileToUpload and a
// slice of paths for files to delete.
func (d *Deployer) findDiffs(localFiles map[string]*localFile, remoteFiles map[string]*blob.ListObject, force bool) ([]*fileToUpload, []string) {
var uploads []*fileToUpload
var deletes []string
found := map[string]bool{}
for path, lf := range localFiles {
upload := false
reason := reasonUnknown
if remoteFile, ok := remoteFiles[path]; ok {
// The file exists in remote. Let's see if we need to upload it anyway.
// TODO: We don't register a diff if the metadata (e.g., Content-Type
// header) has changed. This would be difficult/expensive to detect; some
// providers return metadata along with their "List" result, but others
// (notably AWS S3) do not, so gocloud.dev's blob.Bucket doesn't expose
// it in the list result. It would require a separate request per blob
// to fetch. At least for now, we work around this by documenting it and
// providing a "force" flag (to re-upload everything) and a "force" bool
// per matcher (to re-upload all files in a matcher whose headers may have
// changed).
// Idea: extract a sample set of 1 file per extension + 1 file per matcher
// and check those files?
if force {
upload = true
reason = reasonForce
} else if lf.Force() {
upload = true
reason = reasonForce
} else if lf.UploadSize != remoteFile.Size {
upload = true
reason = reasonSize
} else if len(remoteFile.MD5) == 0 {
// This shouldn't happen unless the remote didn't give us an MD5 hash
// from List, AND we failed to compute one by reading the remote file.
// Default to considering the files different.
upload = true
reason = reasonMD5Missing
} else if !bytes.Equal(lf.MD5(), remoteFile.MD5) {
upload = true
reason = reasonMD5Differs
}
found[path] = true
} else {
// The file doesn't exist in remote.
upload = true
reason = reasonNotFound
}
if upload {
d.logger.Debugf("%s needs to be uploaded: %v\n", path, reason)
uploads = append(uploads, &fileToUpload{lf, reason})
} else {
d.logger.Debugf("%s exists at target and does not need to be uploaded", path)
}
}
// Remote files that weren't found locally should be deleted.
for path := range remoteFiles {
if !found[path] {
deletes = append(deletes, path)
}
}
return uploads, deletes
}
// applyOrdering returns an ordered slice of slices of uploads.
//
// The returned slice will have length len(ordering)+1.
//
// The subslice at index i, for i = 0 ... len(ordering)-1, will have all of the
// uploads whose Local.SlashPath matched the regex at ordering[i] (but not any
// previous ordering regex).
// The subslice at index len(ordering) will have the remaining uploads that
// didn't match any ordering regex.
//
// The subslices are sorted by Local.SlashPath.
func applyOrdering(ordering []*regexp.Regexp, uploads []*fileToUpload) [][]*fileToUpload {
// Sort the whole slice by Local.SlashPath first.
sort.Slice(uploads, func(i, j int) bool { return uploads[i].Local.SlashPath < uploads[j].Local.SlashPath })
retval := make([][]*fileToUpload, len(ordering)+1)
for _, u := range uploads {
matched := false
for i, re := range ordering {
if re.MatchString(u.Local.SlashPath) {
retval[i] = append(retval[i], u)
matched = true
break
}
}
if !matched {
retval[len(ordering)] = append(retval[len(ordering)], u)
}
}
return retval
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/deploy/cloudfront.go | deploy/cloudfront.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.
//go:build withdeploy
package deploy
import (
"context"
"net/url"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudfront"
"github.com/aws/aws-sdk-go-v2/service/cloudfront/types"
"github.com/gohugoio/hugo/deploy/deployconfig"
gcaws "gocloud.dev/aws"
)
// V2ConfigFromURLParams will fail for any unknown params, so we need to remove them.
// This is a mysterious API, but inspecting the code the known params are:
var v2ConfigValidParams = map[string]bool{
"endpoint": true,
"region": true,
"profile": true,
"awssdk": true,
}
// InvalidateCloudFront invalidates the CloudFront cache for distributionID.
// Uses AWS credentials config from the bucket URL.
func InvalidateCloudFront(ctx context.Context, target *deployconfig.Target) error {
u, err := url.Parse(target.URL)
if err != nil {
return err
}
vals := u.Query()
// Remove any unknown params.
for k := range vals {
if !v2ConfigValidParams[k] {
vals.Del(k)
}
}
cfg, err := gcaws.V2ConfigFromURLParams(ctx, vals)
if err != nil {
return err
}
cf := cloudfront.NewFromConfig(cfg)
req := &cloudfront.CreateInvalidationInput{
DistributionId: aws.String(target.CloudFrontDistributionID),
InvalidationBatch: &types.InvalidationBatch{
CallerReference: aws.String(time.Now().Format("20060102150405")),
Paths: &types.Paths{
Items: []string{"/*"},
Quantity: aws.Int32(1),
},
},
}
_, err = cf.CreateInvalidation(ctx, req)
return err
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/deploy/deploy_azure.go | deploy/deploy_azure.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.
//go:build !solaris && withdeploy
package deploy
import (
_ "gocloud.dev/blob"
_ "gocloud.dev/blob/azureblob" // import
)
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/deploy/google.go | deploy/google.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.
//go:build withdeploy
package deploy
import (
"context"
"fmt"
"strings"
"google.golang.org/api/compute/v1"
)
// Invalidate all of the content in a Google Cloud CDN distribution.
func InvalidateGoogleCloudCDN(ctx context.Context, origin string) error {
parts := strings.Split(origin, "/")
if len(parts) != 2 {
return fmt.Errorf("origin must be <project>/<origin>")
}
service, err := compute.NewService(ctx)
if err != nil {
return err
}
rule := &compute.CacheInvalidationRule{Path: "/*"}
_, err = service.UrlMaps.InvalidateCache(parts[0], parts[1], rule).Context(ctx).Do()
return err
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/deploy/deployconfig/deployConfig.go | deploy/deployconfig/deployConfig.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 deployconfig
import (
"errors"
"fmt"
"regexp"
"github.com/gobwas/glob"
"github.com/gohugoio/hugo/config"
hglob "github.com/gohugoio/hugo/hugofs/hglob"
"github.com/mitchellh/mapstructure"
)
const DeploymentConfigKey = "deployment"
// DeployConfig is the complete configuration for deployment.
type DeployConfig struct {
Targets []*Target
Matchers []*Matcher
Order []string
// Usually set via flags.
// Target deployment Name; defaults to the first one.
Target string
// Show a confirm prompt before deploying.
Confirm bool
// DryRun will try the deployment without any remote changes.
DryRun bool
// Force will re-upload all files.
Force bool
// Invalidate the CDN cache listed in the deployment target.
InvalidateCDN bool
// MaxDeletes is the maximum number of files to delete.
MaxDeletes int
// Number of concurrent workers to use when uploading files.
Workers int
Ordering []*regexp.Regexp `json:"-"` // compiled Order
}
type Target struct {
Name string
URL string
CloudFrontDistributionID string
// GoogleCloudCDNOrigin specifies the Google Cloud project and CDN origin to
// invalidate when deploying this target. It is specified as <project>/<origin>.
GoogleCloudCDNOrigin string
// Optional patterns of files to include/exclude for this target.
// Parsed using github.com/gobwas/glob.
Include string
Exclude string
// Parsed versions of Include/Exclude.
IncludeGlob glob.Glob `json:"-"`
ExcludeGlob glob.Glob `json:"-"`
// If true, any local path matching <dir>/index.html will be mapped to the
// remote path <dir>/. This does not affect the top-level index.html file,
// since that would result in an empty path.
StripIndexHTML bool
}
func (tgt *Target) ParseIncludeExclude() error {
var err error
if tgt.Include != "" {
tgt.IncludeGlob, err = hglob.GetGlob(tgt.Include)
if err != nil {
return fmt.Errorf("invalid deployment.target.include %q: %v", tgt.Include, err)
}
}
if tgt.Exclude != "" {
tgt.ExcludeGlob, err = hglob.GetGlob(tgt.Exclude)
if err != nil {
return fmt.Errorf("invalid deployment.target.exclude %q: %v", tgt.Exclude, err)
}
}
return nil
}
// Matcher represents configuration to be applied to files whose paths match
// a specified pattern.
type Matcher struct {
// Pattern is the string pattern to match against paths.
// Matching is done against paths converted to use / as the path separator.
Pattern string
// CacheControl specifies caching attributes to use when serving the blob.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
CacheControl string
// ContentEncoding specifies the encoding used for the blob's content, if any.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
ContentEncoding string
// ContentType specifies the MIME type of the blob being written.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
ContentType string
// Gzip determines whether the file should be gzipped before upload.
// If so, the ContentEncoding field will automatically be set to "gzip".
Gzip bool
// Force indicates that matching files should be re-uploaded. Useful when
// other route-determined metadata (e.g., ContentType) has changed.
Force bool
// Re is Pattern compiled.
Re *regexp.Regexp `json:"-"`
}
func (m *Matcher) Matches(path string) bool {
return m.Re.MatchString(path)
}
var DefaultConfig = DeployConfig{
Workers: 10,
InvalidateCDN: true,
MaxDeletes: 256,
}
// DecodeConfig creates a config from a given Hugo configuration.
func DecodeConfig(cfg config.Provider) (DeployConfig, error) {
dcfg := DefaultConfig
if !cfg.IsSet(DeploymentConfigKey) {
return dcfg, nil
}
if err := mapstructure.WeakDecode(cfg.GetStringMap(DeploymentConfigKey), &dcfg); err != nil {
return dcfg, err
}
if dcfg.Workers <= 0 {
dcfg.Workers = 10
}
for _, tgt := range dcfg.Targets {
if *tgt == (Target{}) {
return dcfg, errors.New("empty deployment target")
}
if err := tgt.ParseIncludeExclude(); err != nil {
return dcfg, err
}
}
var err error
for _, m := range dcfg.Matchers {
if *m == (Matcher{}) {
return dcfg, errors.New("empty deployment matcher")
}
m.Re, err = regexp.Compile(m.Pattern)
if err != nil {
return dcfg, fmt.Errorf("invalid deployment.matchers.pattern: %v", err)
}
}
for _, o := range dcfg.Order {
re, err := regexp.Compile(o)
if err != nil {
return dcfg, fmt.Errorf("invalid deployment.orderings.pattern: %v", err)
}
dcfg.Ordering = append(dcfg.Ordering, re)
}
return dcfg, nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/deploy/deployconfig/deployConfig_test.go | deploy/deployconfig/deployConfig_test.go | // Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build withdeploy
package deployconfig
import (
"fmt"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config"
)
func TestDecodeConfigFromTOML(t *testing.T) {
c := qt.New(t)
tomlConfig := `
someOtherValue = "foo"
[deployment]
order = ["o1", "o2"]
# All lowercase.
[[deployment.targets]]
name = "name0"
url = "url0"
cloudfrontdistributionid = "cdn0"
include = "*.html"
# All uppercase.
[[deployment.targets]]
NAME = "name1"
URL = "url1"
CLOUDFRONTDISTRIBUTIONID = "cdn1"
INCLUDE = "*.jpg"
# Camelcase.
[[deployment.targets]]
name = "name2"
url = "url2"
cloudFrontDistributionID = "cdn2"
exclude = "*.png"
# All lowercase.
[[deployment.matchers]]
pattern = "^pattern0$"
cachecontrol = "cachecontrol0"
contentencoding = "contentencoding0"
contenttype = "contenttype0"
# All uppercase.
[[deployment.matchers]]
PATTERN = "^pattern1$"
CACHECONTROL = "cachecontrol1"
CONTENTENCODING = "contentencoding1"
CONTENTTYPE = "contenttype1"
GZIP = true
FORCE = true
# Camelcase.
[[deployment.matchers]]
pattern = "^pattern2$"
cacheControl = "cachecontrol2"
contentEncoding = "contentencoding2"
contentType = "contenttype2"
gzip = true
force = true
`
cfg, err := config.FromConfigString(tomlConfig, "toml")
c.Assert(err, qt.IsNil)
dcfg, err := DecodeConfig(cfg)
c.Assert(err, qt.IsNil)
// Order.
c.Assert(len(dcfg.Order), qt.Equals, 2)
c.Assert(dcfg.Order[0], qt.Equals, "o1")
c.Assert(dcfg.Order[1], qt.Equals, "o2")
c.Assert(len(dcfg.Ordering), qt.Equals, 2)
// Targets.
c.Assert(len(dcfg.Targets), qt.Equals, 3)
wantInclude := []string{"*.html", "*.jpg", ""}
wantExclude := []string{"", "", "*.png"}
for i := 0; i < 3; i++ {
tgt := dcfg.Targets[i]
c.Assert(tgt.Name, qt.Equals, fmt.Sprintf("name%d", i))
c.Assert(tgt.URL, qt.Equals, fmt.Sprintf("url%d", i))
c.Assert(tgt.CloudFrontDistributionID, qt.Equals, fmt.Sprintf("cdn%d", i))
c.Assert(tgt.Include, qt.Equals, wantInclude[i])
if wantInclude[i] != "" {
c.Assert(tgt.IncludeGlob, qt.Not(qt.IsNil))
}
c.Assert(tgt.Exclude, qt.Equals, wantExclude[i])
if wantExclude[i] != "" {
c.Assert(tgt.ExcludeGlob, qt.Not(qt.IsNil))
}
}
// Matchers.
c.Assert(len(dcfg.Matchers), qt.Equals, 3)
for i := 0; i < 3; i++ {
m := dcfg.Matchers[i]
c.Assert(m.Pattern, qt.Equals, fmt.Sprintf("^pattern%d$", i))
c.Assert(m.Re, qt.Not(qt.IsNil))
c.Assert(m.CacheControl, qt.Equals, fmt.Sprintf("cachecontrol%d", i))
c.Assert(m.ContentEncoding, qt.Equals, fmt.Sprintf("contentencoding%d", i))
c.Assert(m.ContentType, qt.Equals, fmt.Sprintf("contenttype%d", i))
c.Assert(m.Gzip, qt.Equals, i != 0)
c.Assert(m.Force, qt.Equals, i != 0)
}
}
func TestInvalidOrderingPattern(t *testing.T) {
c := qt.New(t)
tomlConfig := `
someOtherValue = "foo"
[deployment]
order = ["["] # invalid regular expression
`
cfg, err := config.FromConfigString(tomlConfig, "toml")
c.Assert(err, qt.IsNil)
_, err = DecodeConfig(cfg)
c.Assert(err, qt.Not(qt.IsNil))
}
func TestInvalidMatcherPattern(t *testing.T) {
c := qt.New(t)
tomlConfig := `
someOtherValue = "foo"
[deployment]
[[deployment.matchers]]
Pattern = "[" # invalid regular expression
`
cfg, err := config.FromConfigString(tomlConfig, "toml")
c.Assert(err, qt.IsNil)
_, err = DecodeConfig(cfg)
c.Assert(err, qt.Not(qt.IsNil))
}
func TestDecodeConfigDefault(t *testing.T) {
c := qt.New(t)
dcfg, err := DecodeConfig(config.New())
c.Assert(err, qt.IsNil)
c.Assert(len(dcfg.Targets), qt.Equals, 0)
c.Assert(len(dcfg.Matchers), qt.Equals, 0)
}
func TestEmptyTarget(t *testing.T) {
c := qt.New(t)
tomlConfig := `
[deployment]
[[deployment.targets]]
`
cfg, err := config.FromConfigString(tomlConfig, "toml")
c.Assert(err, qt.IsNil)
_, err = DecodeConfig(cfg)
c.Assert(err, qt.Not(qt.IsNil))
}
func TestEmptyMatcher(t *testing.T) {
c := qt.New(t)
tomlConfig := `
[deployment]
[[deployment.matchers]]
`
cfg, err := config.FromConfigString(tomlConfig, "toml")
c.Assert(err, qt.IsNil)
_, err = DecodeConfig(cfg)
c.Assert(err, qt.Not(qt.IsNil))
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/commands.go | commands/commands.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 commands
import (
"context"
"github.com/bep/simplecobra"
)
// newExec wires up all of Hugo's CLI.
func newExec() (*simplecobra.Exec, error) {
rootCmd := &rootCommand{
commands: []simplecobra.Commander{
newHugoBuildCmd(),
newVersionCmd(),
newEnvCommand(),
newServerCommand(),
newDeployCommand(),
newConfigCommand(),
newNewCommand(),
newConvertCommand(),
newImportCommand(),
newListCommand(),
newModCommands(),
newGenCommand(),
newReleaseCommand(),
},
}
return simplecobra.New(rootCmd)
}
func newHugoBuildCmd() simplecobra.Commander {
return &hugoBuildCommand{}
}
// hugoBuildCommand just delegates to the rootCommand.
type hugoBuildCommand struct {
rootCmd *rootCommand
}
func (c *hugoBuildCommand) Commands() []simplecobra.Commander {
return nil
}
func (c *hugoBuildCommand) Name() string {
return "build"
}
func (c *hugoBuildCommand) Init(cd *simplecobra.Commandeer) error {
c.rootCmd = cd.Root.Command.(*rootCommand)
return c.rootCmd.initRootCommand("build", cd)
}
func (c *hugoBuildCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
return c.rootCmd.PreRun(cd, runner)
}
func (c *hugoBuildCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
return c.rootCmd.Run(ctx, cd, args)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/hugo_windows.go | commands/hugo_windows.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 commands
import (
// For time zone lookups on Windows without Go installed.
// See #8892
_ "time/tzdata"
"github.com/spf13/cobra"
)
func init() {
// This message to show to Windows users if Hugo is opened from explorer.exe
cobra.MousetrapHelpText = `
Hugo is a command-line tool for generating static websites.
You need to open PowerShell and run Hugo from there.
Visit https://gohugo.io/ for more information.`
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/deploy.go | commands/deploy.go | // Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build withdeploy
package commands
import (
"context"
"github.com/gohugoio/hugo/deploy"
"github.com/bep/simplecobra"
"github.com/spf13/cobra"
)
func newDeployCommand() simplecobra.Commander {
return &simpleCommand{
name: "deploy",
short: "Deploy your site to a cloud provider",
long: `Deploy your site to a cloud provider
See https://gohugo.io/hosting-and-deployment/hugo-deploy/ for detailed
documentation.
`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
h, err := r.Hugo(flagsToCfgWithAdditionalConfigBase(cd, nil, "deployment"))
if err != nil {
return err
}
deployer, err := deploy.New(h.Configs.GetFirstLanguageConfig(), h.Log, h.PathSpec.PublishFs)
if err != nil {
return err
}
return deployer.Deploy(ctx)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
applyDeployFlags(cmd, r)
},
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/commandeer.go | commands/commandeer.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 commands
import (
"context"
"errors"
"fmt"
"io"
"log"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"go.uber.org/automaxprocs/maxprocs"
"github.com/bep/clocks"
"github.com/bep/lazycache"
"github.com/bep/logg"
"github.com/bep/overlayfs"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/common/hstrings"
"github.com/gohugoio/hugo/common/htime"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/config/allconfig"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/resources/kinds"
"github.com/spf13/afero"
"github.com/spf13/cobra"
)
var errHelp = errors.New("help requested")
// Execute executes a command.
func Execute(args []string) error {
// Default GOMAXPROCS to be CPU limit aware, still respecting GOMAXPROCS env.
maxprocs.Set()
x, err := newExec()
if err != nil {
return err
}
args = mapLegacyArgs(args)
cd, err := x.Execute(context.Background(), args)
if cd != nil {
if closer, ok := cd.Root.Command.(types.Closer); ok {
closer.Close()
}
}
if err != nil {
if err == errHelp {
cd.CobraCommand.Help()
fmt.Println()
return nil
}
if simplecobra.IsCommandError(err) {
// Print the help, but also return the error to fail the command.
cd.CobraCommand.Help()
fmt.Println()
}
}
return err
}
type commonConfig struct {
mu *sync.Mutex
configs *allconfig.Configs
cfg config.Provider
fs *hugofs.Fs
}
type configKey struct {
counter int32
ignoreModulesDoesNotExists bool
}
// This is the root command.
type rootCommand struct {
Printf func(format string, v ...any)
Println func(a ...any)
StdOut io.Writer
StdErr io.Writer
logger loggers.Logger
// The main cache busting key for the caches below.
configVersionID atomic.Int32
// Some, but not all commands need access to these.
// Some needs more than one, so keep them in a small cache.
commonConfigs *lazycache.Cache[configKey, *commonConfig]
hugoSites *lazycache.Cache[configKey, *hugolib.HugoSites]
// changesFromBuild received from Hugo in watch mode.
changesFromBuild chan []identity.Identity
commands []simplecobra.Commander
// Flags
source string
buildWatch bool
environment string
// Common build flags.
baseURL string
gc bool
poll string
forceSyncStatic bool
// Profile flags (for debugging of performance problems)
cpuprofile string
memprofile string
mutexprofile string
traceprofile string
printm bool
logLevel string
quiet bool
devMode bool // Hidden flag.
renderToMemory bool
cfgFile string
cfgDir string
}
func (r *rootCommand) isVerbose() bool {
return r.logger.Level() <= logg.LevelInfo
}
func (r *rootCommand) Close() error {
if r.hugoSites != nil {
r.hugoSites.DeleteFunc(func(key configKey, value *hugolib.HugoSites) bool {
if value != nil {
value.Close()
}
return false
})
}
return nil
}
func (r *rootCommand) Build(cd *simplecobra.Commandeer, bcfg hugolib.BuildCfg, cfg config.Provider) (*hugolib.HugoSites, error) {
h, err := r.Hugo(cfg)
if err != nil {
return nil, err
}
if err := h.Build(bcfg); err != nil {
return nil, err
}
return h, nil
}
func (r *rootCommand) Commands() []simplecobra.Commander {
return r.commands
}
func (r *rootCommand) ConfigFromConfig(key configKey, oldConf *commonConfig) (*commonConfig, error) {
cc, _, err := r.commonConfigs.GetOrCreate(key, func(key configKey) (*commonConfig, error) {
fs := oldConf.fs
configs, err := allconfig.LoadConfig(
allconfig.ConfigSourceDescriptor{
Flags: oldConf.cfg,
Fs: fs.Source,
Filename: r.cfgFile,
ConfigDir: r.cfgDir,
Logger: r.logger,
Environment: r.environment,
IgnoreModuleDoesNotExist: key.ignoreModulesDoesNotExists,
},
)
if err != nil {
return nil, err
}
if !configs.Base.C.Clock.IsZero() {
// TODO(bep) find a better place for this.
htime.Clock = clocks.Start(configs.Base.C.Clock)
}
return &commonConfig{
mu: oldConf.mu,
configs: configs,
cfg: oldConf.cfg,
fs: fs,
}, nil
})
return cc, err
}
func (r *rootCommand) ConfigFromProvider(key configKey, cfg config.Provider) (*commonConfig, error) {
if cfg == nil {
panic("cfg must be set")
}
cc, _, err := r.commonConfigs.GetOrCreate(key, func(key configKey) (*commonConfig, error) {
var dir string
if r.source != "" {
dir, _ = filepath.Abs(r.source)
} else {
dir, _ = os.Getwd()
}
if cfg == nil {
cfg = config.New()
}
if !cfg.IsSet("workingDir") {
cfg.Set("workingDir", dir)
} else {
if err := os.MkdirAll(cfg.GetString("workingDir"), 0o777); err != nil {
return nil, fmt.Errorf("failed to create workingDir: %w", err)
}
}
// Load the config first to allow publishDir to be configured in config file.
configs, err := allconfig.LoadConfig(
allconfig.ConfigSourceDescriptor{
Flags: cfg,
Fs: hugofs.Os,
Filename: r.cfgFile,
ConfigDir: r.cfgDir,
Environment: r.environment,
Logger: r.logger,
IgnoreModuleDoesNotExist: key.ignoreModulesDoesNotExists,
},
)
if err != nil {
return nil, err
}
base := configs.Base
cfg.Set("publishDir", base.PublishDir)
cfg.Set("publishDirStatic", base.PublishDir)
cfg.Set("publishDirDynamic", base.PublishDir)
renderStaticToDisk := cfg.GetBool("renderStaticToDisk")
sourceFs := hugofs.Os
var destinationFs afero.Fs
if cfg.GetBool("renderToMemory") {
destinationFs = afero.NewMemMapFs()
if renderStaticToDisk {
// Hybrid, render dynamic content to Root.
cfg.Set("publishDirDynamic", "/")
} else {
// Rendering to memoryFS, publish to Root regardless of publishDir.
cfg.Set("publishDirDynamic", "/")
cfg.Set("publishDirStatic", "/")
}
} else {
destinationFs = hugofs.Os
}
fs := hugofs.NewFromSourceAndDestination(sourceFs, destinationFs, cfg)
if renderStaticToDisk {
dynamicFs := fs.PublishDir
publishDirStatic := cfg.GetString("publishDirStatic")
workingDir := cfg.GetString("workingDir")
absPublishDirStatic := paths.AbsPathify(workingDir, publishDirStatic)
staticFs := hugofs.NewBasePathFs(afero.NewOsFs(), absPublishDirStatic)
// Serve from both the static and dynamic fs,
// the first will take priority.
// THis is a read-only filesystem,
// we do all the writes to
// fs.Destination and fs.DestinationStatic.
fs.PublishDirServer = overlayfs.New(
overlayfs.Options{
Fss: []afero.Fs{
dynamicFs,
staticFs,
},
},
)
fs.PublishDirStatic = staticFs
}
if !base.C.Clock.IsZero() {
// TODO(bep) find a better place for this.
htime.Clock = clocks.Start(configs.Base.C.Clock)
}
if base.PrintPathWarnings {
// Note that we only care about the "dynamic creates" here,
// so skip the static fs.
fs.PublishDir = hugofs.NewCreateCountingFs(fs.PublishDir)
}
commonConfig := &commonConfig{
mu: &sync.Mutex{},
configs: configs,
cfg: cfg,
fs: fs,
}
return commonConfig, nil
})
return cc, err
}
func (r *rootCommand) HugFromConfig(conf *commonConfig) (*hugolib.HugoSites, error) {
k := configKey{counter: r.configVersionID.Load()}
h, _, err := r.hugoSites.GetOrCreate(k, func(key configKey) (*hugolib.HugoSites, error) {
depsCfg := r.newDepsConfig(conf)
return hugolib.NewHugoSites(depsCfg)
})
return h, err
}
func (r *rootCommand) Hugo(cfg config.Provider) (*hugolib.HugoSites, error) {
return r.getOrCreateHugo(cfg, false)
}
func (r *rootCommand) getOrCreateHugo(cfg config.Provider, ignoreModuleDoesNotExist bool) (*hugolib.HugoSites, error) {
k := configKey{counter: r.configVersionID.Load(), ignoreModulesDoesNotExists: ignoreModuleDoesNotExist}
h, _, err := r.hugoSites.GetOrCreate(k, func(key configKey) (*hugolib.HugoSites, error) {
conf, err := r.ConfigFromProvider(key, cfg)
if err != nil {
return nil, err
}
depsCfg := r.newDepsConfig(conf)
return hugolib.NewHugoSites(depsCfg)
})
return h, err
}
func (r *rootCommand) newDepsConfig(conf *commonConfig) deps.DepsCfg {
return deps.DepsCfg{Configs: conf.configs, Fs: conf.fs, StdOut: r.logger.StdOut(), StdErr: r.logger.StdErr(), LogLevel: r.logger.Level(), ChangesFromBuild: r.changesFromBuild}
}
func (r *rootCommand) Name() string {
return "hugo"
}
func (r *rootCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
b := newHugoBuilder(r, nil)
if !r.buildWatch {
defer b.postBuild("Total", time.Now())
}
if err := b.loadConfig(cd, false); err != nil {
return err
}
err := func() error {
if r.buildWatch {
defer r.timeTrack(time.Now(), "Built")
}
err := b.build()
if err != nil {
return err
}
return nil
}()
if err != nil {
return err
}
if !r.buildWatch {
// Done.
return nil
}
watchDirs, err := b.getDirList()
if err != nil {
return err
}
watchGroups := helpers.ExtractAndGroupRootPaths(watchDirs)
r.Printf("Watching for changes in %s\n", strings.Join(watchGroups, ", "))
watcher, err := b.newWatcher(r.poll, watchDirs...)
if err != nil {
return err
}
defer watcher.Close()
r.Println("Press Ctrl+C to stop")
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
<-sigs
return nil
}
func (r *rootCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
r.StdOut = os.Stdout
r.StdErr = os.Stderr
if r.quiet {
r.StdOut = io.Discard
r.StdErr = io.Discard
}
// Used by mkcert (server).
log.SetOutput(r.StdOut)
r.Printf = func(format string, v ...any) {
if !r.quiet {
fmt.Fprintf(r.StdOut, format, v...)
}
}
r.Println = func(a ...any) {
if !r.quiet {
fmt.Fprintln(r.StdOut, a...)
}
}
_, running := runner.Command.(*serverCommand)
var err error
r.logger, err = r.createLogger(running)
if err != nil {
return err
}
// Set up the global logger early to allow info deprecations during config load.
loggers.SetGlobalLogger(r.logger)
r.changesFromBuild = make(chan []identity.Identity, 10)
r.commonConfigs = lazycache.New(lazycache.Options[configKey, *commonConfig]{MaxEntries: 5})
// We don't want to keep stale HugoSites in memory longer than needed.
r.hugoSites = lazycache.New(lazycache.Options[configKey, *hugolib.HugoSites]{
MaxEntries: 1,
OnEvict: func(key configKey, value *hugolib.HugoSites) {
value.Close()
runtime.GC()
},
})
return nil
}
func (r *rootCommand) createLogger(running bool) (loggers.Logger, error) {
level := logg.LevelWarn
if r.devMode {
level = logg.LevelTrace
} else {
if r.logLevel != "" {
switch strings.ToLower(r.logLevel) {
case "debug":
level = logg.LevelDebug
case "info":
level = logg.LevelInfo
case "warn", "warning":
level = logg.LevelWarn
case "error":
level = logg.LevelError
default:
return nil, fmt.Errorf("invalid log level: %q, must be one of debug, warn, info or error", r.logLevel)
}
}
}
optsLogger := loggers.Options{
DistinctLevel: logg.LevelWarn,
Level: level,
StdOut: r.StdOut,
StdErr: r.StdErr,
StoreErrors: running,
}
return loggers.New(optsLogger), nil
}
func (r *rootCommand) resetLogs() {
r.logger.Reset()
loggers.Log().Reset()
}
// IsTestRun reports whether the command is running as a test.
func (r *rootCommand) IsTestRun() bool {
return os.Getenv("HUGO_TESTRUN") != ""
}
func (r *rootCommand) Init(cd *simplecobra.Commandeer) error {
return r.initRootCommand("", cd)
}
func (r *rootCommand) initRootCommand(subCommandName string, cd *simplecobra.Commandeer) error {
cmd := cd.CobraCommand
commandName := "hugo"
if subCommandName != "" {
commandName = subCommandName
}
cmd.Use = fmt.Sprintf("%s [flags]", commandName)
cmd.Short = "Build your site"
cmd.Long = `COMMAND_NAME is the main command, used to build your Hugo site.
Hugo is a Fast and Flexible Static Site Generator
built with love by spf13 and friends in Go.
Complete documentation is available at https://gohugo.io/.`
cmd.Long = strings.ReplaceAll(cmd.Long, "COMMAND_NAME", commandName)
// Configure persistent flags
cmd.PersistentFlags().StringVarP(&r.source, "source", "s", "", "filesystem path to read files relative from")
_ = cmd.MarkFlagDirname("source")
cmd.PersistentFlags().StringP("destination", "d", "", "filesystem path to write files to")
_ = cmd.MarkFlagDirname("destination")
cmd.PersistentFlags().StringVarP(&r.environment, "environment", "e", "", "build environment")
_ = cmd.RegisterFlagCompletionFunc("environment", cobra.NoFileCompletions)
cmd.PersistentFlags().StringP("themesDir", "", "", "filesystem path to themes directory")
_ = cmd.MarkFlagDirname("themesDir")
cmd.PersistentFlags().StringP("ignoreVendorPaths", "", "", "ignores any _vendor for module paths matching the given Glob pattern")
cmd.PersistentFlags().BoolP("noBuildLock", "", false, "don't create .hugo_build.lock file")
_ = cmd.RegisterFlagCompletionFunc("ignoreVendorPaths", cobra.NoFileCompletions)
cmd.PersistentFlags().String("clock", "", "set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00")
_ = cmd.RegisterFlagCompletionFunc("clock", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&r.cfgFile, "config", "", "config file (default is hugo.yaml|json|toml)")
_ = cmd.MarkFlagFilename("config", config.ValidConfigFileExtensions...)
cmd.PersistentFlags().StringVar(&r.cfgDir, "configDir", "config", "config dir")
_ = cmd.MarkFlagDirname("configDir")
cmd.PersistentFlags().BoolVar(&r.quiet, "quiet", false, "build in quiet mode")
cmd.PersistentFlags().BoolVarP(&r.renderToMemory, "renderToMemory", "M", false, "render to memory (mostly useful when running the server)")
cmd.PersistentFlags().BoolVarP(&r.devMode, "devMode", "", false, "only used for internal testing, flag hidden.")
cmd.PersistentFlags().StringVar(&r.logLevel, "logLevel", "", "log level (debug|info|warn|error)")
_ = cmd.RegisterFlagCompletionFunc("logLevel", cobra.FixedCompletions([]string{"debug", "info", "warn", "error"}, cobra.ShellCompDirectiveNoFileComp))
cmd.Flags().BoolVarP(&r.buildWatch, "watch", "w", false, "watch filesystem for changes and recreate as needed")
cmd.PersistentFlags().MarkHidden("devMode")
// Configure local flags
applyLocalFlagsBuild(cmd, r)
return nil
}
// A sub set of the complete build flags. These flags are used by new and mod.
func applyLocalFlagsBuildConfig(cmd *cobra.Command, r *rootCommand) {
cmd.Flags().StringSliceP("theme", "t", []string{}, "themes to use (located in /themes/THEMENAME/)")
_ = cmd.MarkFlagDirname("theme")
cmd.Flags().StringVarP(&r.baseURL, "baseURL", "b", "", "hostname (and path) to the root, e.g. https://spf13.com/")
cmd.Flags().StringP("cacheDir", "", "", "filesystem path to cache directory")
_ = cmd.MarkFlagDirname("cacheDir")
cmd.Flags().StringP("contentDir", "c", "", "filesystem path to content directory")
cmd.Flags().StringSliceP("renderSegments", "", []string{}, "named segments to render (configured in the segments config)")
}
// Flags needed to do a build (used by hugo and hugo server commands)
func applyLocalFlagsBuild(cmd *cobra.Command, r *rootCommand) {
applyLocalFlagsBuildConfig(cmd, r)
cmd.Flags().Bool("cleanDestinationDir", false, "remove files from destination not found in static directories")
cmd.Flags().BoolP("buildDrafts", "D", false, "include content marked as draft")
cmd.Flags().BoolP("buildFuture", "F", false, "include content with publishdate in the future")
cmd.Flags().BoolP("buildExpired", "E", false, "include expired content")
cmd.Flags().BoolP("ignoreCache", "", false, "ignores the cache directory")
cmd.Flags().Bool("enableGitInfo", false, "add Git revision, date, author, and CODEOWNERS info to the pages")
cmd.Flags().StringP("layoutDir", "l", "", "filesystem path to layout directory")
_ = cmd.MarkFlagDirname("layoutDir")
cmd.Flags().BoolVar(&r.gc, "gc", false, "enable to run some cleanup tasks (remove unused cache files) after the build")
cmd.Flags().StringVar(&r.poll, "poll", "", "set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes")
_ = cmd.RegisterFlagCompletionFunc("poll", cobra.NoFileCompletions)
cmd.Flags().Bool("panicOnWarning", false, "panic on first WARNING log")
cmd.Flags().Bool("templateMetrics", false, "display metrics about template executions")
cmd.Flags().Bool("templateMetricsHints", false, "calculate some improvement hints when combined with --templateMetrics")
cmd.Flags().BoolVar(&r.forceSyncStatic, "forceSyncStatic", false, "copy all files when static is changed.")
cmd.Flags().BoolP("noTimes", "", false, "don't sync modification time of files")
cmd.Flags().BoolP("noChmod", "", false, "don't sync permission mode of files")
cmd.Flags().BoolP("printI18nWarnings", "", false, "print missing translations")
cmd.Flags().BoolP("printPathWarnings", "", false, "print warnings on duplicate target paths etc.")
cmd.Flags().BoolP("printUnusedTemplates", "", false, "print warnings on unused templates.")
cmd.Flags().StringVarP(&r.cpuprofile, "profile-cpu", "", "", "write cpu profile to `file`")
cmd.Flags().StringVarP(&r.memprofile, "profile-mem", "", "", "write memory profile to `file`")
cmd.Flags().BoolVarP(&r.printm, "printMemoryUsage", "", false, "print memory usage to screen at intervals")
cmd.Flags().StringVarP(&r.mutexprofile, "profile-mutex", "", "", "write Mutex profile to `file`")
cmd.Flags().StringVarP(&r.traceprofile, "trace", "", "", "write trace to `file` (not useful in general)")
// Hide these for now.
cmd.Flags().MarkHidden("profile-cpu")
cmd.Flags().MarkHidden("profile-mem")
cmd.Flags().MarkHidden("profile-mutex")
cmd.Flags().StringSlice("disableKinds", []string{}, "disable different kind of pages (home, RSS etc.)")
_ = cmd.RegisterFlagCompletionFunc("disableKinds", cobra.FixedCompletions(kinds.AllKinds, cobra.ShellCompDirectiveNoFileComp))
cmd.Flags().Bool("minify", false, "minify any supported output format (HTML, XML etc.)")
}
func (r *rootCommand) timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
r.Printf("%s in %v ms\n", name, int(1000*elapsed.Seconds()))
}
type simpleCommand struct {
use string
name string
short string
long string
run func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *rootCommand, args []string) error
withc func(cmd *cobra.Command, r *rootCommand)
initc func(cd *simplecobra.Commandeer) error
commands []simplecobra.Commander
rootCmd *rootCommand
}
func (c *simpleCommand) Commands() []simplecobra.Commander {
return c.commands
}
func (c *simpleCommand) Name() string {
return c.name
}
func (c *simpleCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
if c.run == nil {
return nil
}
return c.run(ctx, cd, c.rootCmd, args)
}
func (c *simpleCommand) Init(cd *simplecobra.Commandeer) error {
c.rootCmd = cd.Root.Command.(*rootCommand)
cmd := cd.CobraCommand
cmd.Short = c.short
cmd.Long = c.long
if c.use != "" {
cmd.Use = c.use
}
if c.withc != nil {
c.withc(cmd, c.rootCmd)
}
return nil
}
func (c *simpleCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
if c.initc != nil {
return c.initc(cd)
}
return nil
}
func mapLegacyArgs(args []string) []string {
if len(args) > 1 && args[0] == "new" && !hstrings.EqualAny(args[1], "site", "theme", "content") {
// Insert "content" as the second argument
args = append(args[:1], append([]string{"content"}, args[1:]...)...)
}
return args
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/convert.go | commands/convert.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 commands
import (
"bytes"
"context"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/parser"
"github.com/gohugoio/hugo/parser/metadecoders"
"github.com/gohugoio/hugo/parser/pageparser"
"github.com/gohugoio/hugo/resources/page"
"github.com/spf13/cobra"
)
func newConvertCommand() *convertCommand {
var c *convertCommand
c = &convertCommand{
commands: []simplecobra.Commander{
&simpleCommand{
name: "toJSON",
short: "Convert front matter to JSON",
long: `toJSON converts all front matter in the content directory
to use JSON for the front matter.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
return c.convertContents(metadecoders.JSON)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
},
&simpleCommand{
name: "toTOML",
short: "Convert front matter to TOML",
long: `toTOML converts all front matter in the content directory
to use TOML for the front matter.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
return c.convertContents(metadecoders.TOML)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
},
&simpleCommand{
name: "toYAML",
short: "Convert front matter to YAML",
long: `toYAML converts all front matter in the content directory
to use YAML for the front matter.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
return c.convertContents(metadecoders.YAML)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
},
},
}
return c
}
type convertCommand struct {
// Flags.
outputDir string
unsafe bool
// Deps.
r *rootCommand
h *hugolib.HugoSites
// Commands.
commands []simplecobra.Commander
}
func (c *convertCommand) Commands() []simplecobra.Commander {
return c.commands
}
func (c *convertCommand) Name() string {
return "convert"
}
func (c *convertCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
return nil
}
func (c *convertCommand) Init(cd *simplecobra.Commandeer) error {
cmd := cd.CobraCommand
cmd.Short = "Convert front matter to another format"
cmd.Long = `Convert front matter to another format.
See convert's subcommands toJSON, toTOML and toYAML for more information.`
cmd.PersistentFlags().StringVarP(&c.outputDir, "output", "o", "", "filesystem path to write files to")
_ = cmd.MarkFlagDirname("output")
cmd.PersistentFlags().BoolVar(&c.unsafe, "unsafe", false, "enable less safe operations, please backup first")
cmd.RunE = nil
return nil
}
func (c *convertCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
c.r = cd.Root.Command.(*rootCommand)
cfg := config.New()
cfg.Set("buildDrafts", true)
h, err := c.r.Hugo(flagsToCfg(cd, cfg))
if err != nil {
return err
}
c.h = h
return nil
}
func (c *convertCommand) convertAndSavePage(p page.Page, site *hugolib.Site, targetFormat metadecoders.Format) error {
// The resources are not in .Site.AllPages.
for _, r := range p.Resources().ByType("page") {
if err := c.convertAndSavePage(r.(page.Page), site, targetFormat); err != nil {
return err
}
}
if p.File() == nil {
// No content file.
return nil
}
errMsg := fmt.Errorf("error processing file %q", p.File().Path())
site.Log.Infoln("attempting to convert", p.File().Filename())
f := p.File()
file, err := f.FileInfo().Meta().Open()
if err != nil {
site.Log.Errorln(errMsg)
file.Close()
return nil
}
pf, err := pageparser.ParseFrontMatterAndContent(file)
if err != nil {
site.Log.Errorln(errMsg)
file.Close()
return err
}
file.Close()
// better handling of dates in formats that don't have support for them
if pf.FrontMatterFormat == metadecoders.JSON || pf.FrontMatterFormat == metadecoders.YAML || pf.FrontMatterFormat == metadecoders.TOML {
for k, v := range pf.FrontMatter {
switch vv := v.(type) {
case time.Time:
pf.FrontMatter[k] = vv.Format(time.RFC3339)
}
}
}
var newContent bytes.Buffer
err = parser.InterfaceToFrontMatter(pf.FrontMatter, targetFormat, &newContent)
if err != nil {
site.Log.Errorln(errMsg)
return err
}
newContent.Write(pf.Content)
newFilename := p.File().Filename()
if c.outputDir != "" {
contentDir := strings.TrimSuffix(newFilename, p.File().Path())
contentDir = filepath.Base(contentDir)
newFilename = filepath.Join(c.outputDir, contentDir, p.File().Path())
}
fs := hugofs.Os
if err := helpers.WriteToDisk(newFilename, &newContent, fs); err != nil {
return fmt.Errorf("failed to save file %q:: %w", newFilename, err)
}
return nil
}
func (c *convertCommand) convertContents(format metadecoders.Format) error {
if c.outputDir == "" && !c.unsafe {
return newUserError("Unsafe operation not allowed, use --unsafe or set a different output path")
}
if err := c.h.Build(hugolib.BuildCfg{SkipRender: true}); err != nil {
return err
}
site := c.h.Sites[0]
var pagesBackedByFile page.Pages
for _, p := range site.AllPages() {
if p.File() == nil {
continue
}
pagesBackedByFile = append(pagesBackedByFile, p)
}
site.Log.Println("processing", len(pagesBackedByFile), "content files")
for _, p := range site.AllPages() {
if err := c.convertAndSavePage(p, site, format); err != nil {
return err
}
}
return nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/config.go | commands/config.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 commands
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"strings"
"time"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/config/allconfig"
"github.com/gohugoio/hugo/hugolib/sitesmatrix"
"github.com/gohugoio/hugo/modules"
"github.com/gohugoio/hugo/parser"
"github.com/gohugoio/hugo/parser/metadecoders"
"github.com/spf13/cobra"
)
// newConfigCommand creates a new config command and its subcommands.
func newConfigCommand() *configCommand {
return &configCommand{
commands: []simplecobra.Commander{
&configMountsCommand{},
},
}
}
type configCommand struct {
r *rootCommand
format string
lang string
printZero bool
commands []simplecobra.Commander
}
func (c *configCommand) Commands() []simplecobra.Commander {
return c.commands
}
func (c *configCommand) Name() string {
return "config"
}
func (c *configCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
conf, err := c.r.ConfigFromProvider(configKey{counter: c.r.configVersionID.Load()}, flagsToCfg(cd, nil))
if err != nil {
return err
}
var config *allconfig.Config
if c.lang != "" {
var found bool
config, found = conf.configs.LanguageConfigMap[c.lang]
if !found {
return fmt.Errorf("language %q not found", c.lang)
}
} else {
config = conf.configs.LanguageConfigMap[conf.configs.Base.DefaultContentLanguage]
}
var buf bytes.Buffer
dec := json.NewEncoder(&buf)
dec.SetIndent("", " ")
dec.SetEscapeHTML(false)
if err := dec.Encode(parser.ReplacingJSONMarshaller{Value: config, KeysToLower: true, OmitEmpty: !c.printZero}); err != nil {
return err
}
format := strings.ToLower(c.format)
switch format {
case "json":
os.Stdout.Write(buf.Bytes())
default:
// Decode the JSON to a map[string]interface{} and then unmarshal it again to the correct format.
var m map[string]any
if err := json.Unmarshal(buf.Bytes(), &m); err != nil {
return err
}
maps.ConvertFloat64WithNoDecimalsToInt(m)
switch format {
case "yaml":
return parser.InterfaceToConfig(m, metadecoders.YAML, os.Stdout)
case "toml":
return parser.InterfaceToConfig(m, metadecoders.TOML, os.Stdout)
default:
return fmt.Errorf("unsupported format: %q", format)
}
}
return nil
}
func (c *configCommand) Init(cd *simplecobra.Commandeer) error {
c.r = cd.Root.Command.(*rootCommand)
cmd := cd.CobraCommand
cmd.Short = "Display site configuration"
cmd.Long = `Display site configuration, both default and custom settings.`
cmd.Flags().StringVar(&c.format, "format", "toml", "preferred file format (toml, yaml or json)")
_ = cmd.RegisterFlagCompletionFunc("format", cobra.FixedCompletions([]string{"toml", "yaml", "json"}, cobra.ShellCompDirectiveNoFileComp))
cmd.Flags().StringVar(&c.lang, "lang", "", "the language to display config for. Defaults to the first language defined.")
cmd.Flags().BoolVar(&c.printZero, "printZero", false, `include config options with zero values (e.g. false, 0, "") in the output`)
_ = cmd.RegisterFlagCompletionFunc("lang", cobra.NoFileCompletions)
applyLocalFlagsBuildConfig(cmd, c.r)
return nil
}
func (c *configCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
return nil
}
type configModMount struct {
Source string `json:"source"`
Target string `json:"target"`
Sites sitesmatrix.Sites `json:"sites,omitzero"`
}
type configModMounts struct {
verbose bool
m modules.Module
}
// MarshalJSON is for internal use only.
func (m *configModMounts) MarshalJSON() ([]byte, error) {
var mounts []configModMount
for _, mount := range m.m.Mounts() {
mounts = append(mounts, configModMount{
Source: mount.Source,
Target: mount.Target,
Sites: mount.Sites,
})
}
var ownerPath string
if m.m.Owner() != nil {
ownerPath = m.m.Owner().Path()
}
if m.verbose {
config := m.m.Config()
return json.Marshal(&struct {
Path string `json:"path"`
Version string `json:"version"`
Time time.Time `json:"time"`
Owner string `json:"owner"`
Dir string `json:"dir"`
Meta map[string]any `json:"meta"`
HugoVersion modules.HugoVersion `json:"hugoVersion"`
Mounts []configModMount `json:"mounts"`
}{
Path: m.m.Path(),
Version: m.m.Version(),
Time: m.m.Time(),
Owner: ownerPath,
Dir: m.m.Dir(),
Meta: config.Params,
HugoVersion: config.HugoVersion,
Mounts: mounts,
})
}
return json.Marshal(&struct {
Path string `json:"path"`
Version string `json:"version"`
Time time.Time `json:"time"`
Owner string `json:"owner"`
Dir string `json:"dir"`
Mounts []configModMount `json:"mounts"`
}{
Path: m.m.Path(),
Version: m.m.Version(),
Time: m.m.Time(),
Owner: ownerPath,
Dir: m.m.Dir(),
Mounts: mounts,
})
}
type configMountsCommand struct {
r *rootCommand
configCmd *configCommand
}
func (c *configMountsCommand) Commands() []simplecobra.Commander {
return nil
}
func (c *configMountsCommand) Name() string {
return "mounts"
}
func (c *configMountsCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
r := c.configCmd.r
conf, err := r.ConfigFromProvider(configKey{counter: c.r.configVersionID.Load()}, flagsToCfg(cd, nil))
if err != nil {
return err
}
for _, m := range conf.configs.Modules {
if err := parser.InterfaceToConfig(&configModMounts{m: m, verbose: r.isVerbose()}, metadecoders.JSON, os.Stdout); err != nil {
return err
}
}
return nil
}
func (c *configMountsCommand) Init(cd *simplecobra.Commandeer) error {
c.r = cd.Root.Command.(*rootCommand)
cmd := cd.CobraCommand
cmd.Short = "Print the configured file mounts"
cmd.ValidArgsFunction = cobra.NoFileCompletions
applyLocalFlagsBuildConfig(cmd, c.r)
return nil
}
func (c *configMountsCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
c.configCmd = cd.Parent.Command.(*configCommand)
return nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/deploy_off.go | commands/deploy_off.go | // Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !withdeploy
// 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 commands
import (
"context"
"errors"
"github.com/bep/simplecobra"
"github.com/spf13/cobra"
)
func newDeployCommand() simplecobra.Commander {
return &simpleCommand{
name: "deploy",
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
return errors.New("deploy not supported in this version of Hugo; install a release with 'withdeploy' in the archive filename or build yourself with the 'withdeploy' build tag. Also see https://github.com/gohugoio/hugo/pull/12995")
},
withc: func(cmd *cobra.Command, r *rootCommand) {
applyDeployFlags(cmd, r)
cmd.Hidden = true
},
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/gen.go | commands/gen.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 commands
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"slices"
"strings"
"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/styles"
"github.com/bep/simplecobra"
"github.com/goccy/go-yaml"
"github.com/gohugoio/hugo/common/hugo"
"github.com/gohugoio/hugo/docshelper"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/parser"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
)
func newGenCommand() *genCommand {
var (
// Flags.
gendocdir string
genmandir string
// Chroma flags.
style string
highlightStyle string
lineNumbersInlineStyle string
lineNumbersTableStyle string
omitEmpty bool
omitClassComments bool
)
newChromaStyles := func() simplecobra.Commander {
return &simpleCommand{
name: "chromastyles",
short: "Generate CSS stylesheet for the Chroma code highlighter",
long: `Generate CSS stylesheet for the Chroma code highlighter for a given style. This stylesheet is needed if markup.highlight.noClasses is disabled in config.
See https://xyproto.github.io/splash/docs/all.html for a preview of the available styles`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
style = strings.ToLower(style)
if !slices.Contains(styles.Names(), style) {
return fmt.Errorf("invalid style: %s", style)
}
builder := styles.Get(style).Builder()
if highlightStyle != "" {
builder.Add(chroma.LineHighlight, highlightStyle)
}
if lineNumbersInlineStyle != "" {
builder.Add(chroma.LineNumbers, lineNumbersInlineStyle)
}
if lineNumbersTableStyle != "" {
builder.Add(chroma.LineNumbersTable, lineNumbersTableStyle)
}
style, err := builder.Build()
if err != nil {
return err
}
if omitEmpty {
// See https://github.com/alecthomas/chroma/commit/5b2a4c5a26c503c79bc86ba3c4ae5b330028bd3d
hugo.Deprecate("--omitEmpty", "Flag is no longer needed, empty classes are now always omitted.", "v0.149.0")
}
options := []html.Option{
html.WithCSSComments(!omitClassComments),
}
formatter := html.New(options...)
w := os.Stdout
fmt.Fprintf(w, "/* Generated using: hugo %s */\n\n", strings.Join(os.Args[1:], " "))
formatter.WriteCSS(w, style)
return nil
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.PersistentFlags().StringVar(&style, "style", "friendly", "highlighter style (see https://xyproto.github.io/splash/docs/)")
_ = cmd.RegisterFlagCompletionFunc("style", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&highlightStyle, "highlightStyle", "", `foreground and background colors for highlighted lines, e.g. --highlightStyle "#fff000 bg:#000fff"`)
_ = cmd.RegisterFlagCompletionFunc("highlightStyle", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&lineNumbersInlineStyle, "lineNumbersInlineStyle", "", `foreground and background colors for inline line numbers, e.g. --lineNumbersInlineStyle "#fff000 bg:#000fff"`)
_ = cmd.RegisterFlagCompletionFunc("lineNumbersInlineStyle", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&lineNumbersTableStyle, "lineNumbersTableStyle", "", `foreground and background colors for table line numbers, e.g. --lineNumbersTableStyle "#fff000 bg:#000fff"`)
_ = cmd.RegisterFlagCompletionFunc("lineNumbersTableStyle", cobra.NoFileCompletions)
cmd.PersistentFlags().BoolVar(&omitEmpty, "omitEmpty", false, `omit empty CSS rules (deprecated, no longer needed)`)
_ = cmd.RegisterFlagCompletionFunc("omitEmpty", cobra.NoFileCompletions)
cmd.PersistentFlags().BoolVar(&omitClassComments, "omitClassComments", false, `omit CSS class comment prefixes in the generated CSS`)
_ = cmd.RegisterFlagCompletionFunc("omitClassComments", cobra.NoFileCompletions)
},
}
}
newMan := func() simplecobra.Commander {
return &simpleCommand{
name: "man",
short: "Generate man pages for the Hugo CLI",
long: `This command automatically generates up-to-date man pages of Hugo's
command-line interface. By default, it creates the man page files
in the "man" directory under the current directory.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
header := &doc.GenManHeader{
Section: "1",
Manual: "Hugo Manual",
Source: fmt.Sprintf("Hugo %s", hugo.CurrentVersion),
}
if !strings.HasSuffix(genmandir, helpers.FilePathSeparator) {
genmandir += helpers.FilePathSeparator
}
if found, _ := helpers.Exists(genmandir, hugofs.Os); !found {
r.Println("Directory", genmandir, "does not exist, creating...")
if err := hugofs.Os.MkdirAll(genmandir, 0o777); err != nil {
return err
}
}
cd.CobraCommand.Root().DisableAutoGenTag = true
r.Println("Generating Hugo man pages in", genmandir, "...")
doc.GenManTree(cd.CobraCommand.Root(), header, genmandir)
r.Println("Done.")
return nil
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.PersistentFlags().StringVar(&genmandir, "dir", "man/", "the directory to write the man pages.")
_ = cmd.MarkFlagDirname("dir")
},
}
}
newGen := func() simplecobra.Commander {
const gendocFrontmatterTemplate = `---
title: "%s"
slug: %s
url: %s
---
`
return &simpleCommand{
name: "doc",
short: "Generate Markdown documentation for the Hugo CLI",
long: `Generate Markdown documentation for the Hugo CLI.
This command is, mostly, used to create up-to-date documentation
of Hugo's command-line interface for https://gohugo.io/.
It creates one Markdown file per command with front matter suitable
for rendering in Hugo.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
cd.CobraCommand.VisitParents(func(c *cobra.Command) {
// Disable the "Auto generated by spf13/cobra on DATE"
// as it creates a lot of diffs.
c.DisableAutoGenTag = true
})
if !strings.HasSuffix(gendocdir, helpers.FilePathSeparator) {
gendocdir += helpers.FilePathSeparator
}
if found, _ := helpers.Exists(gendocdir, hugofs.Os); !found {
r.Println("Directory", gendocdir, "does not exist, creating...")
if err := hugofs.Os.MkdirAll(gendocdir, 0o777); err != nil {
return err
}
}
prepender := func(filename string) string {
name := filepath.Base(filename)
base := strings.TrimSuffix(name, path.Ext(name))
url := "/docs/reference/commands/" + strings.ToLower(base) + "/"
return fmt.Sprintf(gendocFrontmatterTemplate, strings.Replace(base, "_", " ", -1), base, url)
}
linkHandler := func(name string) string {
base := strings.TrimSuffix(name, path.Ext(name))
return "/docs/reference/commands/" + strings.ToLower(base) + "/"
}
r.Println("Generating Hugo command-line documentation in", gendocdir, "...")
doc.GenMarkdownTreeCustom(cd.CobraCommand.Root(), gendocdir, prepender, linkHandler)
r.Println("Done.")
return nil
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.PersistentFlags().StringVar(&gendocdir, "dir", "/tmp/hugodoc/", "the directory to write the doc.")
_ = cmd.MarkFlagDirname("dir")
},
}
}
var docsHelperTarget string
newDocsHelper := func() simplecobra.Commander {
return &simpleCommand{
name: "docshelper",
short: "Generate some data files for the Hugo docs",
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
r.Println("Generate docs data to", docsHelperTarget)
var buf bytes.Buffer
jsonEnc := json.NewEncoder(&buf)
configProvider := func() docshelper.DocProvider {
conf := hugolib.DefaultConfig()
conf.CacheDir = "" // The default value does not make sense in the docs.
defaultConfig := parser.NullBoolJSONMarshaller{Wrapped: parser.LowerCaseCamelJSONMarshaller{Value: conf}}
return docshelper.DocProvider{"config": defaultConfig}
}
docshelper.AddDocProviderFunc(configProvider)
if err := jsonEnc.Encode(docshelper.GetDocProvider()); err != nil {
return err
}
// Decode the JSON to a map[string]interface{} and then unmarshal it again to the correct format.
var m map[string]any
if err := json.Unmarshal(buf.Bytes(), &m); err != nil {
return err
}
targetFile := filepath.Join(docsHelperTarget, "docs.yaml")
f, err := os.Create(targetFile)
if err != nil {
return err
}
defer f.Close()
yamlEnc := yaml.NewEncoder(f, yaml.UseSingleQuote(true), yaml.AutoInt())
if err := yamlEnc.Encode(m); err != nil {
return err
}
r.Println("Done!")
return nil
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.Hidden = true
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.PersistentFlags().StringVarP(&docsHelperTarget, "dir", "", "docs/data", "data dir")
},
}
}
return &genCommand{
commands: []simplecobra.Commander{
newChromaStyles(),
newGen(),
newMan(),
newDocsHelper(),
},
}
}
type genCommand struct {
rootCmd *rootCommand
commands []simplecobra.Commander
}
func (c *genCommand) Commands() []simplecobra.Commander {
return c.commands
}
func (c *genCommand) Name() string {
return "gen"
}
func (c *genCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
return nil
}
func (c *genCommand) Init(cd *simplecobra.Commandeer) error {
cmd := cd.CobraCommand
cmd.Short = "Generate documentation and syntax highlighting styles"
cmd.Long = "Generate documentation for your project using Hugo's documentation engine, including syntax highlighting for various programming languages."
cmd.RunE = nil
return nil
}
func (c *genCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
c.rootCmd = cd.Root.Command.(*rootCommand)
return nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/mod.go | commands/mod.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 commands
import (
"context"
"errors"
"os"
"path/filepath"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/modules/npm"
"github.com/spf13/cobra"
)
const commonUsageMod = `
Note that Hugo will always start out by resolving the components defined in the site
configuration, provided by a _vendor directory (if no --ignoreVendorPaths flag provided),
Go Modules, or a folder inside the themes directory, in that order.
See https://gohugo.io/hugo-modules/ for more information.
`
// buildConfigCommands creates a new config command and its subcommands.
func newModCommands() *modCommands {
var (
clean bool
pattern string
all bool
)
npmCommand := &simpleCommand{
name: "npm",
short: "Various npm helpers",
long: `Various npm (Node package manager) helpers.`,
commands: []simplecobra.Commander{
&simpleCommand{
name: "pack",
short: "Experimental: Prepares and writes a composite package.json file for your project",
long: `Prepares and writes a composite package.json file for your project.
On first run it creates a "package.hugo.json" in the project root if not already there. This file will be used as a template file
with the base dependency set.
This set will be merged with all "package.hugo.json" files found in the dependency tree, picking the version closest to the project.
This command is marked as 'Experimental'. We think it's a great idea, so it's not likely to be
removed from Hugo, but we need to test this out in "real life" to get a feel of it,
so this may/will change in future versions of Hugo.
`,
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
applyLocalFlagsBuildConfig(cmd, r)
},
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
h, err := r.Hugo(flagsToCfg(cd, nil))
if err != nil {
return err
}
return npm.Pack(h.BaseFs.ProjectSourceFs, h.BaseFs.AssetsWithDuplicatesPreserved.Fs)
},
},
},
}
return &modCommands{
commands: []simplecobra.Commander{
&simpleCommand{
name: "init",
short: "Initialize this project as a Hugo Module",
long: `Initialize this project as a Hugo Module.
It will try to guess the module path, but you may help by passing it as an argument, e.g:
hugo mod init github.com/gohugoio/testshortcodes
Note that Hugo Modules supports multi-module projects, so you can initialize a Hugo Module
inside a subfolder on GitHub, as one example.
`,
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
applyLocalFlagsBuildConfig(cmd, r)
},
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
h, err := r.getOrCreateHugo(flagsToCfg(cd, nil), true)
if err != nil {
return err
}
var initPath string
if len(args) >= 1 {
initPath = args[0]
}
c := h.Configs.ModulesClient
if err := c.Init(initPath); err != nil {
return err
}
return nil
},
},
&simpleCommand{
name: "verify",
short: "Verify dependencies",
long: `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.`,
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
applyLocalFlagsBuildConfig(cmd, r)
cmd.Flags().BoolVarP(&clean, "clean", "", false, "delete module cache for dependencies that fail verification")
},
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, nil))
if err != nil {
return err
}
client := conf.configs.ModulesClient
return client.Verify(clean)
},
},
&simpleCommand{
name: "graph",
short: "Print a module dependency graph",
long: `Print a module dependency graph with information about module status (disabled, vendored).
Note that for vendored modules, that is the version listed and not the one from go.mod.
`,
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
applyLocalFlagsBuildConfig(cmd, r)
cmd.Flags().BoolVarP(&clean, "clean", "", false, "delete module cache for dependencies that fail verification")
},
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, nil))
if err != nil {
return err
}
client := conf.configs.ModulesClient
return client.Graph(os.Stdout)
},
},
&simpleCommand{
name: "clean",
short: "Delete the Hugo Module cache for the current project",
long: `Delete the Hugo Module cache for the current project.`,
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
applyLocalFlagsBuildConfig(cmd, r)
cmd.Flags().StringVarP(&pattern, "pattern", "", "", `pattern matching module paths to clean (all if not set), e.g. "**hugo*"`)
_ = cmd.RegisterFlagCompletionFunc("pattern", cobra.NoFileCompletions)
cmd.Flags().BoolVarP(&all, "all", "", false, "clean entire module cache")
},
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
h, err := r.Hugo(flagsToCfg(cd, nil))
if err != nil {
return err
}
if all {
modCache := h.ResourceSpec.FileCaches.ModulesCache()
count, err := modCache.Prune(true)
r.Printf("Deleted %d files from module cache.", count)
return err
}
return h.Configs.ModulesClient.Clean(pattern)
},
},
&simpleCommand{
name: "tidy",
short: "Remove unused entries in go.mod and go.sum",
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
applyLocalFlagsBuildConfig(cmd, r)
},
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
h, err := r.Hugo(flagsToCfg(cd, nil))
if err != nil {
return err
}
return h.Configs.ModulesClient.Tidy()
},
},
&simpleCommand{
name: "vendor",
short: "Vendor all module dependencies into the _vendor directory",
long: `Vendor all module dependencies into the _vendor directory.
If a module is vendored, that is where Hugo will look for it's dependencies.
`,
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
applyLocalFlagsBuildConfig(cmd, r)
},
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
h, err := r.Hugo(flagsToCfg(cd, nil))
if err != nil {
return err
}
return h.Configs.ModulesClient.Vendor()
},
},
&simpleCommand{
name: "get",
short: "Resolves dependencies in your current Hugo project",
long: `
Resolves dependencies in your current Hugo project.
Some examples:
Install the latest version possible for a given module:
hugo mod get github.com/gohugoio/testshortcodes
Install a specific version:
hugo mod get github.com/gohugoio/testshortcodes@v0.3.0
Install the latest versions of all direct module dependencies:
hugo mod get
hugo mod get ./... (recursive)
Install the latest versions of all module dependencies (direct and indirect):
hugo mod get -u
hugo mod get -u ./... (recursive)
Run "go help get" for more information. All flags available for "go get" is also relevant here.
` + commonUsageMod,
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.DisableFlagParsing = true
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
// We currently just pass on the flags we get to Go and
// need to do the flag handling manually.
if len(args) == 1 && (args[0] == "-h" || args[0] == "--help") {
return errHelp
}
var lastArg string
if len(args) != 0 {
lastArg = args[len(args)-1]
}
if lastArg == "./..." {
args = args[:len(args)-1]
// Do a recursive update.
dirname, err := os.Getwd()
if err != nil {
return err
}
// Sanity chesimplecobra. We do recursive walking and want to avoid
// accidents.
if len(dirname) < 5 {
return errors.New("must not be run from the file system root")
}
filepath.Walk(dirname, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if info.Name() == "go.mod" {
// Found a module.
dir := filepath.Dir(path)
cfg := config.New()
cfg.Set("workingDir", dir)
conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Add(1)}, flagsToCfg(cd, cfg))
if err != nil {
return err
}
r.Println("Update module in", conf.configs.Base.WorkingDir)
client := conf.configs.ModulesClient
return client.Get(args...)
}
return nil
})
return nil
} else {
conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, nil))
if err != nil {
return err
}
client := conf.configs.ModulesClient
return client.Get(args...)
}
},
},
npmCommand,
},
}
}
type modCommands struct {
r *rootCommand
commands []simplecobra.Commander
}
func (c *modCommands) Commands() []simplecobra.Commander {
return c.commands
}
func (c *modCommands) Name() string {
return "mod"
}
func (c *modCommands) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
_, err := c.r.ConfigFromProvider(configKey{counter: c.r.configVersionID.Load()}, nil)
if err != nil {
return err
}
// config := conf.configs.Base
return nil
}
func (c *modCommands) Init(cd *simplecobra.Commandeer) error {
cmd := cd.CobraCommand
cmd.Short = "Manage modules"
cmd.Long = `Various helpers to help manage the modules in your project's dependency graph.
Most operations here requires a Go version installed on your system (>= Go 1.12) and the relevant VCS client (typically Git).
This is not needed if you only operate on modules inside /themes or if you have vendored them via "hugo mod vendor".
` + commonUsageMod
cmd.RunE = nil
return nil
}
func (c *modCommands) PreRun(cd, runner *simplecobra.Commandeer) error {
c.r = cd.Root.Command.(*rootCommand)
return nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/release.go | commands/release.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 commands
import (
"context"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/releaser"
"github.com/spf13/cobra"
)
// Note: This is a command only meant for internal use and must be run
// via "go run -tags release main.go release" on the actual code base that is in the release.
func newReleaseCommand() simplecobra.Commander {
var (
step int
skipPush bool
try bool
version string
)
return &simpleCommand{
name: "release",
short: "Release a new version of Hugo",
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
rel, err := releaser.New(skipPush, try, step, version)
if err != nil {
return err
}
return rel.Run()
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.Hidden = true
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.PersistentFlags().BoolVarP(&skipPush, "skip-push", "", false, "skip pushing to remote")
cmd.PersistentFlags().BoolVarP(&try, "try", "", false, "no changes")
cmd.PersistentFlags().IntVarP(&step, "step", "", 0, "step to run (1: set new version 2: prepare next dev version)")
cmd.PersistentFlags().StringVarP(&version, "version", "", "", "version to release (derived from branch name if not set)")
_ = cmd.RegisterFlagCompletionFunc("step", cobra.FixedCompletions([]string{"1", "2"}, cobra.ShellCompDirectiveNoFileComp))
},
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/hugobuilder.go | commands/hugobuilder.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 commands
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"runtime/trace"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/bep/debounce"
"github.com/bep/simplecobra"
"github.com/fsnotify/fsnotify"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/common/hstrings"
"github.com/gohugoio/hugo/common/htime"
"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/common/terminal"
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/hugolib/filesystems"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/livereload"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/watcher"
"github.com/spf13/fsync"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
type hugoBuilder struct {
r *rootCommand
confmu sync.Mutex
conf *commonConfig
// May be nil.
s *serverCommand
// Currently only set when in "fast render mode".
changeDetector *fileChangeDetector
visitedURLs *types.EvictingQueue[string]
fullRebuildSem *semaphore.Weighted
debounce func(f func())
onConfigLoaded func(reloaded bool) error
fastRenderMode bool
showErrorInBrowser bool
errState hugoBuilderErrState
}
var errConfigNotSet = errors.New("config not set")
func (c *hugoBuilder) withConfE(fn func(conf *commonConfig) error) error {
c.confmu.Lock()
defer c.confmu.Unlock()
if c.conf == nil {
return errConfigNotSet
}
return fn(c.conf)
}
func (c *hugoBuilder) withConf(fn func(conf *commonConfig)) {
c.confmu.Lock()
defer c.confmu.Unlock()
fn(c.conf)
}
type hugoBuilderErrState struct {
mu sync.Mutex
paused bool
builderr error
waserr bool
}
func (e *hugoBuilderErrState) setPaused(p bool) {
e.mu.Lock()
defer e.mu.Unlock()
e.paused = p
}
func (e *hugoBuilderErrState) isPaused() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.paused
}
func (e *hugoBuilderErrState) setBuildErr(err error) {
e.mu.Lock()
defer e.mu.Unlock()
e.builderr = err
}
func (e *hugoBuilderErrState) buildErr() error {
e.mu.Lock()
defer e.mu.Unlock()
return e.builderr
}
func (e *hugoBuilderErrState) setWasErr(w bool) {
e.mu.Lock()
defer e.mu.Unlock()
e.waserr = w
}
func (e *hugoBuilderErrState) wasErr() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.waserr
}
// getDirList provides NewWatcher() with a list of directories to watch for changes.
func (c *hugoBuilder) getDirList() ([]string, error) {
h, err := c.hugo()
if err != nil {
return nil, err
}
return hstrings.UniqueStringsSorted(h.PathSpec.BaseFs.WatchFilenames()), nil
}
func (c *hugoBuilder) initCPUProfile() (func(), error) {
if c.r.cpuprofile == "" {
return nil, nil
}
f, err := os.Create(c.r.cpuprofile)
if err != nil {
return nil, fmt.Errorf("failed to create CPU profile: %w", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
return nil, fmt.Errorf("failed to start CPU profile: %w", err)
}
return func() {
pprof.StopCPUProfile()
f.Close()
}, nil
}
func (c *hugoBuilder) initMemProfile() {
if c.r.memprofile == "" {
return
}
f, err := os.Create(c.r.memprofile)
if err != nil {
c.r.logger.Errorf("could not create memory profile: ", err)
}
defer f.Close()
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
c.r.logger.Errorf("could not write memory profile: ", err)
}
}
func (c *hugoBuilder) initMemTicker() func() {
memticker := time.NewTicker(5 * time.Second)
quit := make(chan struct{})
printMem := func() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("\n\nAlloc = %v\nTotalAlloc = %v\nSys = %v\nNumGC = %v\n\n", formatByteCount(m.Alloc), formatByteCount(m.TotalAlloc), formatByteCount(m.Sys), m.NumGC)
}
go func() {
for {
select {
case <-memticker.C:
printMem()
case <-quit:
memticker.Stop()
printMem()
return
}
}
}()
return func() {
close(quit)
}
}
func (c *hugoBuilder) initMutexProfile() (func(), error) {
if c.r.mutexprofile == "" {
return nil, nil
}
f, err := os.Create(c.r.mutexprofile)
if err != nil {
return nil, err
}
runtime.SetMutexProfileFraction(1)
return func() {
pprof.Lookup("mutex").WriteTo(f, 0)
f.Close()
}, nil
}
func (c *hugoBuilder) initProfiling() (func(), error) {
stopCPUProf, err := c.initCPUProfile()
if err != nil {
return nil, err
}
stopMutexProf, err := c.initMutexProfile()
if err != nil {
return nil, err
}
stopTraceProf, err := c.initTraceProfile()
if err != nil {
return nil, err
}
var stopMemTicker func()
if c.r.printm {
stopMemTicker = c.initMemTicker()
}
return func() {
c.initMemProfile()
if stopCPUProf != nil {
stopCPUProf()
}
if stopMutexProf != nil {
stopMutexProf()
}
if stopTraceProf != nil {
stopTraceProf()
}
if stopMemTicker != nil {
stopMemTicker()
}
}, nil
}
func (c *hugoBuilder) initTraceProfile() (func(), error) {
if c.r.traceprofile == "" {
return nil, nil
}
f, err := os.Create(c.r.traceprofile)
if err != nil {
return nil, fmt.Errorf("failed to create trace file: %w", err)
}
if err := trace.Start(f); err != nil {
return nil, fmt.Errorf("failed to start trace: %w", err)
}
return func() {
trace.Stop()
f.Close()
}, nil
}
// newWatcher creates a new watcher to watch filesystem events.
func (c *hugoBuilder) newWatcher(pollIntervalStr string, dirList ...string) (*watcher.Batcher, error) {
staticSyncer := &staticSyncer{c: c}
var pollInterval time.Duration
poll := pollIntervalStr != ""
if poll {
pollInterval, err := types.ToDurationE(pollIntervalStr)
if err != nil {
return nil, fmt.Errorf("invalid value for flag poll: %s", err)
}
c.r.logger.Printf("Use watcher with poll interval %v", pollInterval)
}
if pollInterval == 0 {
pollInterval = 500 * time.Millisecond
}
watcher, err := watcher.New(500*time.Millisecond, pollInterval, poll)
if err != nil {
return nil, err
}
h, err := c.hugo()
if err != nil {
return nil, err
}
spec := h.Deps.SourceSpec
for _, d := range dirList {
if d != "" {
if spec.IgnoreFile(d) {
continue
}
_ = watcher.Add(d)
}
}
// Identifies changes to config (config.toml) files.
configSet := make(map[string]bool)
var configFiles []string
c.withConf(func(conf *commonConfig) {
configFiles = conf.configs.LoadingInfo.ConfigFiles
})
c.r.Println("Watching for config changes in", strings.Join(configFiles, ", "))
for _, configFile := range configFiles {
watcher.Add(configFile)
configSet[configFile] = true
}
go func() {
for {
select {
case changes := <-c.r.changesFromBuild:
unlock, err := h.LockBuild()
if err != nil {
c.r.logger.Errorln("Failed to acquire a build lock: %s", err)
return
}
c.changeDetector.PrepareNew()
err = c.rebuildSitesForChanges(changes)
if err != nil {
c.r.logger.Errorln("Error while watching:", err)
}
if c.s != nil && c.s.doLiveReload {
doReload := c.changeDetector == nil || len(c.changeDetector.changed()) > 0
doReload = doReload || c.showErrorInBrowser && c.errState.buildErr() != nil
if doReload {
livereload.ForceRefresh()
}
}
unlock()
case evs := <-watcher.Events:
unlock, err := h.LockBuild()
if err != nil {
c.r.logger.Errorln("Failed to acquire a build lock: %s", err)
return
}
c.handleEvents(watcher, staticSyncer, evs, configSet)
if c.showErrorInBrowser && c.errState.buildErr() != nil {
// Need to reload browser to show the error
livereload.ForceRefresh()
}
unlock()
case err := <-watcher.Errors():
if err != nil && !herrors.IsNotExist(err) {
c.r.logger.Errorln("Error while watching:", err)
}
}
}
}()
return watcher, nil
}
func (c *hugoBuilder) build() error {
stopProfiling, err := c.initProfiling()
if err != nil {
return err
}
defer func() {
if stopProfiling != nil {
stopProfiling()
}
}()
if err := c.fullBuild(false); err != nil {
return err
}
if !c.r.quiet {
c.r.Println()
h, err := c.hugo()
if err != nil {
return err
}
h.PrintProcessingStats(os.Stdout)
c.r.Println()
}
return nil
}
func (c *hugoBuilder) buildSites(noBuildLock bool) (err error) {
defer func() {
c.errState.setBuildErr(err)
}()
var h *hugolib.HugoSites
h, err = c.hugo()
if err != nil {
return
}
err = h.Build(hugolib.BuildCfg{NoBuildLock: noBuildLock})
return
}
func (c *hugoBuilder) copyStatic() (map[string]uint64, error) {
m, err := c.doWithPublishDirs(c.copyStaticTo)
if err == nil || herrors.IsNotExist(err) {
return m, nil
}
return m, err
}
func (c *hugoBuilder) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint64, error) {
infol := c.r.logger.InfoCommand("static")
publishDir := helpers.FilePathSeparator
if sourceFs.PublishFolder != "" {
publishDir = filepath.Join(publishDir, sourceFs.PublishFolder)
}
fs := &countingStatFs{Fs: sourceFs.Fs}
syncer := fsync.NewSyncer()
c.withConf(func(conf *commonConfig) {
syncer.NoTimes = conf.configs.Base.NoTimes
syncer.NoChmod = conf.configs.Base.NoChmod
syncer.ChmodFilter = chmodFilter
syncer.DestFs = conf.fs.PublishDirStatic
// Now that we are using a unionFs for the static directories
// We can effectively clean the publishDir on initial sync
syncer.Delete = conf.configs.Base.CleanDestinationDir
})
syncer.SrcFs = fs
if syncer.Delete {
infol.Logf("removing all files from destination that don't exist in static dirs")
syncer.DeleteFilter = func(f fsync.FileInfo) bool {
name := f.Name()
// Keep .gitignore and .gitattributes anywhere
if name == ".gitignore" || name == ".gitattributes" {
return true
}
// Keep Hugo's original dot-directory behavior
return f.IsDir() && strings.HasPrefix(name, ".")
}
}
start := time.Now()
// because we are using a baseFs (to get the union right).
// set sync src to root
err := syncer.Sync(publishDir, helpers.FilePathSeparator)
if err != nil {
return 0, err
}
loggers.TimeTrackf(infol, start, nil, "syncing static files to %s", publishDir)
// Sync runs Stat 2 times for every source file.
numFiles := fs.statCounter / 2
return numFiles, err
}
func (c *hugoBuilder) doWithPublishDirs(f func(sourceFs *filesystems.SourceFilesystem) (uint64, error)) (map[string]uint64, error) {
langCount := make(map[string]uint64)
h, err := c.hugo()
if err != nil {
return nil, err
}
staticFilesystems := h.BaseFs.SourceFilesystems.Static
if len(staticFilesystems) == 0 {
c.r.logger.Infoln("No static directories found to sync")
return langCount, nil
}
for lang, fs := range staticFilesystems {
cnt, err := f(fs)
if err != nil {
return langCount, err
}
if lang == "" {
// Not multihost
c.withConf(func(conf *commonConfig) {
for _, l := range conf.configs.Languages {
langCount[l.Lang] = cnt
}
})
} else {
langCount[lang] = cnt
}
}
return langCount, nil
}
func (c *hugoBuilder) progressIntermediate() {
terminal.ReportProgress(c.r.StdOut, terminal.ProgressIntermediate, 0)
}
func (c *hugoBuilder) progressHidden() {
terminal.ReportProgress(c.r.StdOut, terminal.ProgressHidden, 0)
}
func (c *hugoBuilder) fullBuild(noBuildLock bool) error {
var (
g errgroup.Group
langCount map[string]uint64
)
c.r.logger.Println("Start building sites … ")
c.r.logger.Println(hugo.BuildVersionString())
c.r.logger.Println()
if terminal.IsTerminal(os.Stdout) {
defer func() {
fmt.Print(showCursor + clearLine)
}()
}
copyStaticFunc := func() error {
cnt, err := c.copyStatic()
if err != nil {
return fmt.Errorf("error copying static files: %w", err)
}
langCount = cnt
return nil
}
buildSitesFunc := func() error {
if err := c.buildSites(noBuildLock); err != nil {
return fmt.Errorf("error building site: %w", err)
}
return nil
}
// Do not copy static files and build sites in parallel if cleanDestinationDir is enabled.
// This flag deletes all static resources in /public folder that are missing in /static,
// and it does so at the end of copyStatic() call.
var cleanDestinationDir bool
c.withConf(func(conf *commonConfig) {
cleanDestinationDir = conf.configs.Base.CleanDestinationDir
})
if cleanDestinationDir {
if err := copyStaticFunc(); err != nil {
return err
}
if err := buildSitesFunc(); err != nil {
return err
}
} else {
g.Go(copyStaticFunc)
g.Go(buildSitesFunc)
if err := g.Wait(); err != nil {
return err
}
}
h, err := c.hugo()
if err != nil {
return err
}
for _, s := range h.Sites {
s.ProcessingStats.Static = langCount[s.Language().Lang]
}
if c.r.gc {
count, err := h.GC()
if err != nil {
return err
}
for _, s := range h.Sites {
// We have no way of knowing what site the garbage belonged to.
s.ProcessingStats.Cleaned = uint64(count)
}
}
return nil
}
func (c *hugoBuilder) fullRebuild(changeType string) {
if changeType == configChangeGoMod {
// go.mod may be changed during the build itself, and
// we really want to prevent superfluous builds.
if !c.fullRebuildSem.TryAcquire(1) {
return
}
c.fullRebuildSem.Release(1)
}
c.fullRebuildSem.Acquire(context.Background(), 1)
go func() {
defer c.fullRebuildSem.Release(1)
c.printChangeDetected(changeType)
defer func() {
// Allow any file system events to arrive basimplecobra.
// This will block any rebuild on config changes for the
// duration of the sleep.
time.Sleep(2 * time.Second)
}()
defer c.postBuild("Rebuilt", time.Now())
err := c.reloadConfig()
if err != nil {
// Set the processing on pause until the state is recovered.
c.errState.setPaused(true)
c.handleBuildErr(err, "Failed to reload config")
if c.s.doLiveReload {
livereload.ForceRefresh()
}
} else {
c.errState.setPaused(false)
}
if !c.errState.isPaused() {
_, err := c.copyStatic()
if err != nil {
c.r.logger.Errorln(err)
return
}
err = c.buildSites(false)
if err != nil {
c.r.logger.Errorln(err)
} else if c.s != nil && c.s.doLiveReload {
livereload.ForceRefresh()
}
}
}()
}
func (c *hugoBuilder) handleBuildErr(err error, msg string) {
c.errState.setBuildErr(err)
c.r.logger.Errorln(msg + ": " + cleanErrorLog(err.Error()))
}
func (c *hugoBuilder) handleEvents(watcher *watcher.Batcher,
staticSyncer *staticSyncer,
evs []fsnotify.Event,
configSet map[string]bool,
) {
defer func() {
c.errState.setWasErr(false)
}()
var isHandled bool
// Filter out ghost events (from deleted, renamed directories).
// This seems to be a bug in fsnotify, or possibly MacOS.
var n int
for _, ev := range evs {
keep := true
// Write and rename operations are often followed by CHMOD.
// There may be valid use cases for rebuilding the site on CHMOD,
// but that will require more complex logic than this simple conditional.
// On OS X this seems to be related to Spotlight, see:
// https://github.com/go-fsnotify/fsnotify/issues/15
// A workaround is to put your site(s) on the Spotlight exception list,
// but that may be a little mysterious for most end users.
// So, for now, we skip reload on CHMOD.
// We do have to check for WRITE though. On slower laptops a Chmod
// could be aggregated with other important events, and we still want
// to rebuild on those
if ev.Op == fsnotify.Chmod {
keep = false
} else if ev.Has(fsnotify.Create) || ev.Has(fsnotify.Write) {
if _, err := os.Stat(ev.Name); err != nil {
keep = false
}
}
if keep {
evs[n] = ev
n++
}
}
evs = evs[:n]
for _, ev := range evs {
isConfig := configSet[ev.Name]
configChangeType := configChangeConfig
if isConfig {
if strings.Contains(ev.Name, "go.mod") {
configChangeType = configChangeGoMod
}
if strings.Contains(ev.Name, ".work") {
configChangeType = configChangeGoWork
}
}
if !isConfig {
// It may be one of the /config folders
dirname := filepath.Dir(ev.Name)
if dirname != "." && configSet[dirname] {
isConfig = true
}
}
if isConfig {
isHandled = true
if ev.Op&fsnotify.Chmod == fsnotify.Chmod {
continue
}
if ev.Op&fsnotify.Remove == fsnotify.Remove || ev.Op&fsnotify.Rename == fsnotify.Rename {
c.withConf(func(conf *commonConfig) {
for _, configFile := range conf.configs.LoadingInfo.ConfigFiles {
counter := 0
for watcher.Add(configFile) != nil {
counter++
if counter >= 100 {
break
}
time.Sleep(100 * time.Millisecond)
}
}
})
}
// Config file(s) changed. Need full rebuild.
c.fullRebuild(configChangeType)
return
}
}
if isHandled {
return
}
if c.errState.isPaused() {
// Wait for the server to get into a consistent state before
// we continue with processing.
return
}
if len(evs) > 50 {
// This is probably a mass edit of the content dir.
// Schedule a full rebuild for when it slows down.
c.debounce(func() {
c.fullRebuild("")
})
return
}
c.r.logger.Debugln("Received System Events:", evs)
staticEvents := []fsnotify.Event{}
dynamicEvents := []fsnotify.Event{}
filterDuplicateEvents := func(evs []fsnotify.Event) []fsnotify.Event {
seen := make(map[string]bool)
var n int
for _, ev := range evs {
if seen[ev.Name] {
continue
}
seen[ev.Name] = true
evs[n] = ev
n++
}
return evs[:n]
}
h, err := c.hugo()
if err != nil {
c.r.logger.Errorln("Error getting the Hugo object:", err)
return
}
n = 0
for _, ev := range evs {
if h.ShouldSkipFileChangeEvent(ev) {
continue
}
evs[n] = ev
n++
}
evs = evs[:n]
for _, ev := range evs {
ext := filepath.Ext(ev.Name)
baseName := filepath.Base(ev.Name)
istemp := strings.HasSuffix(ext, "~") ||
(ext == ".swp") || // vim
(ext == ".swx") || // vim
(ext == ".bck") || // helix
(ext == ".tmp") || // generic temp file
(ext == ".DS_Store") || // OSX Thumbnail
baseName == "4913" || // vim
strings.HasPrefix(ext, ".goutputstream") || // gnome
strings.HasSuffix(ext, "jb_old___") || // intelliJ
strings.HasSuffix(ext, "jb_tmp___") || // intelliJ
strings.HasSuffix(ext, "jb_bak___") || // intelliJ
strings.HasPrefix(ext, ".sb-") || // byword
strings.HasPrefix(baseName, ".#") || // emacs
strings.HasPrefix(baseName, "#") // emacs
if istemp {
continue
}
if h.Deps.SourceSpec.IgnoreFile(ev.Name) {
continue
}
// Sometimes during rm -rf operations a '"": REMOVE' is triggered. Just ignore these
if ev.Name == "" {
continue
}
walkAdder := func(ctx context.Context, path string, f hugofs.FileMetaInfo) error {
if f.IsDir() {
c.r.logger.Println("adding created directory to watchlist", path)
if err := watcher.Add(path); err != nil {
return err
}
} else if !staticSyncer.isStatic(h, path) {
// Hugo's rebuilding logic is entirely file based. When you drop a new folder into
// /content on OSX, the above logic will handle future watching of those files,
// but the initial CREATE is lost.
dynamicEvents = append(dynamicEvents, fsnotify.Event{Name: path, Op: fsnotify.Create})
}
return nil
}
// recursively add new directories to watch list
if ev.Has(fsnotify.Create) || ev.Has(fsnotify.Rename) {
c.withConf(func(conf *commonConfig) {
if s, err := conf.fs.Source.Stat(ev.Name); err == nil && s.Mode().IsDir() {
_ = helpers.Walk(conf.fs.Source, ev.Name, walkAdder)
}
})
}
if staticSyncer.isStatic(h, ev.Name) {
staticEvents = append(staticEvents, ev)
} else {
dynamicEvents = append(dynamicEvents, ev)
}
}
lrl := c.r.logger.InfoCommand("livereload")
staticEvents = filterDuplicateEvents(staticEvents)
dynamicEvents = filterDuplicateEvents(dynamicEvents)
if len(staticEvents) > 0 {
c.printChangeDetected("Static files")
if c.r.forceSyncStatic {
c.r.logger.Printf("Syncing all static files\n")
_, err := c.copyStatic()
if err != nil {
c.r.logger.Errorln("Error copying static files to publish dir:", err)
return
}
} else {
if err := staticSyncer.syncsStaticEvents(staticEvents); err != nil {
c.r.logger.Errorln("Error syncing static files to publish dir:", err)
return
}
}
if c.s != nil && c.s.doLiveReload {
// Will block forever trying to write to a channel that nobody is reading if livereload isn't initialized
if !c.errState.wasErr() && len(staticEvents) == 1 {
h, err := c.hugo()
if err != nil {
c.r.logger.Errorln("Error getting the Hugo object:", err)
return
}
path := h.BaseFs.SourceFilesystems.MakeStaticPathRelative(staticEvents[0].Name)
path = h.RelURL(paths.ToSlashTrimLeading(path), false)
lrl.Logf("refreshing static file %q", path)
livereload.RefreshPath(path)
} else {
lrl.Logf("got %d static file change events, force refresh", len(staticEvents))
livereload.ForceRefresh()
}
}
}
if len(dynamicEvents) > 0 {
partitionedEvents := partitionDynamicEvents(
h.BaseFs.SourceFilesystems,
dynamicEvents)
onePageName := pickOneWriteOrCreatePath(h.Conf.ContentTypes(), partitionedEvents.ContentEvents)
c.printChangeDetected("")
c.changeDetector.PrepareNew()
func() {
defer c.postBuild("Total", time.Now())
if err := c.rebuildSites(dynamicEvents); err != nil {
c.handleBuildErr(err, "Rebuild failed")
}
}()
if c.s != nil && c.s.doLiveReload {
if c.errState.wasErr() {
livereload.ForceRefresh()
return
}
changed := c.changeDetector.changed()
if c.changeDetector != nil {
if len(changed) >= 10 {
lrl.Logf("build changed %d files", len(changed))
} else {
lrl.Logf("build changed %d files: %q", len(changed), changed)
}
if len(changed) == 0 {
// Nothing has changed.
return
}
}
// If this change set also contains one or more CSS files, we need to
// refresh these as well.
var cssChanges []string
var otherChanges []string
for _, ev := range changed {
if strings.HasSuffix(ev, ".css") {
cssChanges = append(cssChanges, ev)
} else {
otherChanges = append(otherChanges, ev)
}
}
if len(partitionedEvents.ContentEvents) > 0 {
navigate := c.s != nil && c.s.navigateToChanged
// We have fetched the same page above, but it may have
// changed.
var p page.Page
if navigate {
if onePageName != "" {
p = h.GetContentPage(onePageName)
}
}
if p != nil && p.RelPermalink() != "" {
link, port := p.RelPermalink(), p.Site().ServerPort()
lrl.Logf("navigating to %q using port %d", link, port)
livereload.NavigateToPathForPort(link, port)
} else {
lrl.Logf("no page to navigate to, force refresh")
livereload.ForceRefresh()
}
} else if len(otherChanges) > 0 || len(cssChanges) > 0 {
if len(otherChanges) == 1 {
// Allow single changes to be refreshed without a full page reload.
pathToRefresh := h.PathSpec.RelURL(paths.ToSlashTrimLeading(otherChanges[0]), false)
lrl.Logf("refreshing %q", pathToRefresh)
livereload.RefreshPath(pathToRefresh)
} else if len(cssChanges) == 0 || len(otherChanges) > 1 {
lrl.Logf("force refresh")
livereload.ForceRefresh()
}
} else {
lrl.Logf("force refresh")
livereload.ForceRefresh()
}
if len(cssChanges) > 0 {
// Allow some time for the live reload script to get reconnected.
if len(otherChanges) > 0 {
time.Sleep(200 * time.Millisecond)
}
for _, ev := range cssChanges {
pathToRefresh := h.PathSpec.RelURL(paths.ToSlashTrimLeading(ev), false)
lrl.Logf("refreshing CSS %q", pathToRefresh)
livereload.RefreshPath(pathToRefresh)
}
}
}
}
}
func (c *hugoBuilder) postBuild(what string, start time.Time) {
if h, err := c.hugo(); err == nil && h.Conf.Running() {
h.LogServerAddresses()
}
c.r.timeTrack(start, what)
}
func (c *hugoBuilder) hugo() (*hugolib.HugoSites, error) {
var h *hugolib.HugoSites
if err := c.withConfE(func(conf *commonConfig) error {
var err error
h, err = c.r.HugFromConfig(conf)
return err
}); err != nil {
return nil, err
}
if c.s != nil {
// A running server, register the media types.
for _, s := range h.Sites {
s.RegisterMediaTypes()
}
}
return h, nil
}
func (c *hugoBuilder) hugoTry() *hugolib.HugoSites {
var h *hugolib.HugoSites
c.withConf(func(conf *commonConfig) {
h, _ = c.r.HugFromConfig(conf)
})
return h
}
func (c *hugoBuilder) loadConfig(cd *simplecobra.Commandeer, running bool) error {
if terminal.PrintANSIColors(os.Stdout) {
defer c.progressHidden()
// If the configuration takes a while to load, we want to show some progress.
// This is typically loading of external modules.
d := debounce.New(500 * time.Millisecond)
d(func() {
c.progressIntermediate()
})
defer d(func() {})
}
cfg := config.New()
cfg.Set("renderToMemory", c.r.renderToMemory)
watch := c.r.buildWatch || (c.s != nil && c.s.serverWatch)
if c.r.environment == "" {
// We need to set the environment as early as possible because we need it to load the correct config.
// Check if the user has set it in env.
if env := os.Getenv("HUGO_ENVIRONMENT"); env != "" {
c.r.environment = env
} else if env := os.Getenv("HUGO_ENV"); env != "" {
c.r.environment = env
} else {
if c.s != nil {
// The server defaults to development.
c.r.environment = hugo.EnvironmentDevelopment
} else {
c.r.environment = hugo.EnvironmentProduction
}
}
}
cfg.Set("environment", c.r.environment)
cfg.Set("internal", maps.Params{
"running": running,
"watch": watch,
"verbose": c.r.isVerbose(),
"fastRenderMode": c.fastRenderMode,
})
conf, err := c.r.ConfigFromProvider(configKey{counter: c.r.configVersionID.Load()}, flagsToCfg(cd, cfg))
if err != nil {
return err
}
if len(conf.configs.LoadingInfo.ConfigFiles) == 0 {
//lint:ignore ST1005 end user message.
return errors.New("Unable to locate config file or config directory. Perhaps you need to create a new site.\nRun `hugo help new` for details.")
}
c.conf = conf
if c.onConfigLoaded != nil {
if err := c.onConfigLoaded(false); err != nil {
return err
}
}
return nil
}
var rebuildCounter atomic.Uint64
func (c *hugoBuilder) printChangeDetected(typ string) {
msg := "\nChange"
if typ != "" {
msg += " of " + typ
}
msg += fmt.Sprintf(" detected, rebuilding site (#%d).", rebuildCounter.Add(1))
c.r.logger.Println(msg)
const layout = "2006-01-02 15:04:05.000 -0700"
c.r.logger.Println(htime.Now().Format(layout))
}
func (c *hugoBuilder) rebuildSites(events []fsnotify.Event) (err error) {
defer func() {
c.errState.setBuildErr(err)
}()
if err := c.errState.buildErr(); err != nil {
ferrs := herrors.UnwrapFileErrorsWithErrorContext(err)
for _, err := range ferrs {
events = append(events, fsnotify.Event{Name: err.Position().Filename, Op: fsnotify.Write})
}
}
var h *hugolib.HugoSites
h, err = c.hugo()
if err != nil {
return
}
err = h.Build(hugolib.BuildCfg{NoBuildLock: true, RecentlyTouched: c.visitedURLs, ErrRecovery: c.errState.wasErr()}, events...)
return
}
func (c *hugoBuilder) rebuildSitesForChanges(ids []identity.Identity) (err error) {
defer func() {
c.errState.setBuildErr(err)
}()
var h *hugolib.HugoSites
h, err = c.hugo()
if err != nil {
return
}
whatChanged := &hugolib.WhatChanged{}
whatChanged.Add(ids...)
err = h.Build(hugolib.BuildCfg{NoBuildLock: true, WhatChanged: whatChanged, RecentlyTouched: c.visitedURLs, ErrRecovery: c.errState.wasErr()})
return
}
func (c *hugoBuilder) reloadConfig() error {
c.r.resetLogs()
c.r.configVersionID.Add(1)
if err := c.withConfE(func(conf *commonConfig) error {
oldConf := conf
newConf, err := c.r.ConfigFromConfig(configKey{counter: c.r.configVersionID.Load()}, conf)
if err != nil {
return err
}
sameLen := len(oldConf.configs.Languages) == len(newConf.configs.Languages)
if !sameLen {
if oldConf.configs.IsMultihost || newConf.configs.IsMultihost {
return errors.New("multihost change detected, please restart server")
}
}
c.conf = newConf
return nil
}); err != nil {
return err
}
if c.onConfigLoaded != nil {
if err := c.onConfigLoaded(true); err != nil {
return err
}
}
return nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/list.go | commands/list.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 commands
import (
"context"
"encoding/csv"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/resource"
"github.com/spf13/cobra"
)
// newListCommand creates a new list command and its subcommands.
func newListCommand() *listCommand {
createRecord := func(workingDir string, p page.Page) []string {
return []string{
filepath.ToSlash(strings.TrimPrefix(p.File().Filename(), workingDir+string(os.PathSeparator))),
p.Slug(),
p.Title(),
p.Date().Format(time.RFC3339),
p.ExpiryDate().Format(time.RFC3339),
p.PublishDate().Format(time.RFC3339),
strconv.FormatBool(p.Draft()),
p.Permalink(),
p.Kind(),
p.Section(),
}
}
list := func(cd *simplecobra.Commandeer, r *rootCommand, shouldInclude func(page.Page) bool, opts ...any) error {
bcfg := hugolib.BuildCfg{SkipRender: true}
cfg := flagsToCfg(cd, nil)
for i := 0; i < len(opts); i += 2 {
cfg.Set(opts[i].(string), opts[i+1])
}
h, err := r.Build(cd, bcfg, cfg)
if err != nil {
return err
}
writer := csv.NewWriter(r.StdOut)
defer writer.Flush()
writer.Write([]string{
"path",
"slug",
"title",
"date",
"expiryDate",
"publishDate",
"draft",
"permalink",
"kind",
"section",
})
for _, p := range h.Pages() {
if shouldInclude(p) {
record := createRecord(h.Conf.BaseConfig().WorkingDir, p)
if err := writer.Write(record); err != nil {
return err
}
}
}
return nil
}
return &listCommand{
commands: []simplecobra.Commander{
&simpleCommand{
name: "drafts",
short: "List draft content",
long: `List draft content.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
shouldInclude := func(p page.Page) bool {
if !p.Draft() || p.File() == nil {
return false
}
return true
}
return list(cd, r, shouldInclude,
"buildDrafts", true,
"buildFuture", true,
"buildExpired", true,
)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
},
&simpleCommand{
name: "future",
short: "List future content",
long: `List content with a future publication date.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
shouldInclude := func(p page.Page) bool {
if !resource.IsFuture(p) || p.File() == nil {
return false
}
return true
}
return list(cd, r, shouldInclude,
"buildFuture", true,
"buildDrafts", true,
)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
},
&simpleCommand{
name: "expired",
short: "List expired content",
long: `List content with a past expiration date.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
shouldInclude := func(p page.Page) bool {
if !resource.IsExpired(p) || p.File() == nil {
return false
}
return true
}
return list(cd, r, shouldInclude,
"buildExpired", true,
"buildDrafts", true,
)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
},
&simpleCommand{
name: "all",
short: "List all content",
long: `List all content including draft, future, and expired.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
shouldInclude := func(p page.Page) bool {
return p.File() != nil
}
return list(cd, r, shouldInclude, "buildDrafts", true, "buildFuture", true, "buildExpired", true)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
},
&simpleCommand{
name: "published",
short: "List published content",
long: `List content that is not draft, future, or expired.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
shouldInclude := func(p page.Page) bool {
return !p.Draft() && !resource.IsFuture(p) && !resource.IsExpired(p) && p.File() != nil
}
return list(cd, r, shouldInclude)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
},
},
}
}
type listCommand struct {
commands []simplecobra.Commander
}
func (c *listCommand) Commands() []simplecobra.Commander {
return c.commands
}
func (c *listCommand) Name() string {
return "list"
}
func (c *listCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
// Do nothing.
return nil
}
func (c *listCommand) Init(cd *simplecobra.Commandeer) error {
cmd := cd.CobraCommand
cmd.Short = "List content"
cmd.Long = `List content.
List requires a subcommand, e.g. hugo list drafts`
cmd.RunE = nil
return nil
}
func (c *listCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
return nil
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/server.go | commands/server.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 commands
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"maps"
"net"
"net/http"
_ "net/http/pprof"
"net/url"
"os"
"os/signal"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/bep/mclib"
"github.com/pkg/browser"
"github.com/bep/debounce"
"github.com/bep/simplecobra"
"github.com/fsnotify/fsnotify"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/common/hugo"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/langs"
"github.com/gohugoio/hugo/tpl/tplimpl"
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/common/urls"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/hugolib/filesystems"
"github.com/gohugoio/hugo/livereload"
"github.com/gohugoio/hugo/transform"
"github.com/gohugoio/hugo/transform/livereloadinject"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/fsync"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
var (
logDuplicateTemplateExecuteRe = regexp.MustCompile(`: template: .*?:\d+:\d+: executing ".*?"`)
logDuplicateTemplateParseRe = regexp.MustCompile(`: template: .*?:\d+:\d*`)
)
var logReplacer = strings.NewReplacer(
"can't", "can’t", // Chroma lexer doesn't do well with "can't"
"*hugolib.pageState", "page.Page", // Page is the public interface.
"Rebuild failed:", "",
)
const (
configChangeConfig = "config file"
configChangeGoMod = "go.mod file"
configChangeGoWork = "go work file"
)
const (
hugoHeaderRedirect = "X-Hugo-Redirect"
)
func newHugoBuilder(r *rootCommand, s *serverCommand, onConfigLoaded ...func(reloaded bool) error) *hugoBuilder {
var visitedURLs *types.EvictingQueue[string]
if s != nil && !s.disableFastRender {
visitedURLs = types.NewEvictingQueue[string](20)
}
return &hugoBuilder{
r: r,
s: s,
visitedURLs: visitedURLs,
fullRebuildSem: semaphore.NewWeighted(1),
debounce: debounce.New(4 * time.Second),
onConfigLoaded: func(reloaded bool) error {
for _, wc := range onConfigLoaded {
if err := wc(reloaded); err != nil {
return err
}
}
return nil
},
}
}
func newServerCommand() *serverCommand {
// Flags.
var uninstall bool
c := &serverCommand{
quit: make(chan bool),
commands: []simplecobra.Commander{
&simpleCommand{
name: "trust",
short: "Install the local CA in the system trust store",
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
action := "-install"
if uninstall {
action = "-uninstall"
}
os.Args = []string{action}
return mclib.RunMain()
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.Flags().BoolVar(&uninstall, "uninstall", false, "Uninstall the local CA (but do not delete it).")
},
},
},
}
return c
}
func (c *serverCommand) Commands() []simplecobra.Commander {
return c.commands
}
type countingStatFs struct {
afero.Fs
statCounter uint64
}
func (fs *countingStatFs) Stat(name string) (os.FileInfo, error) {
f, err := fs.Fs.Stat(name)
if err == nil {
if !f.IsDir() {
atomic.AddUint64(&fs.statCounter, 1)
}
}
return f, err
}
// dynamicEvents contains events that is considered dynamic, as in "not static".
// Both of these categories will trigger a new build, but the asset events
// does not fit into the "navigate to changed" logic.
type dynamicEvents struct {
ContentEvents []fsnotify.Event
AssetEvents []fsnotify.Event
}
type fileChangeDetector struct {
sync.Mutex
current map[string]uint64
prev map[string]uint64
irrelevantRe *regexp.Regexp
}
func (f *fileChangeDetector) OnFileClose(name string, checksum uint64) {
f.Lock()
defer f.Unlock()
f.current[name] = checksum
}
func (f *fileChangeDetector) PrepareNew() {
if f == nil {
return
}
f.Lock()
defer f.Unlock()
if f.current == nil {
f.current = make(map[string]uint64)
f.prev = make(map[string]uint64)
return
}
f.prev = make(map[string]uint64)
maps.Copy(f.prev, f.current)
f.current = make(map[string]uint64)
}
func (f *fileChangeDetector) changed() []string {
if f == nil {
return nil
}
f.Lock()
defer f.Unlock()
var c []string
for k, v := range f.current {
vv, found := f.prev[k]
if !found || v != vv {
c = append(c, k)
}
}
return f.filterIrrelevantAndSort(c)
}
func (f *fileChangeDetector) filterIrrelevantAndSort(in []string) []string {
var filtered []string
for _, v := range in {
if !f.irrelevantRe.MatchString(v) {
filtered = append(filtered, v)
}
}
sort.Strings(filtered)
return filtered
}
type fileServer struct {
baseURLs []urls.BaseURL
roots []string
errorTemplate func(err any) (io.Reader, error)
c *serverCommand
}
func (f *fileServer) createEndpoint(i int) (*http.ServeMux, net.Listener, string, string, error) {
r := f.c.r
baseURL := f.baseURLs[i]
root := f.roots[i]
port := f.c.serverPorts[i].p
listener := f.c.serverPorts[i].ln
logger := f.c.r.logger
if i == 0 {
r.Printf("Environment: %q\n", f.c.hugoTry().Deps.Site.Hugo().Environment)
mainTarget := "disk"
if f.c.r.renderToMemory {
mainTarget = "memory"
}
if f.c.renderStaticToDisk {
r.Printf("Serving pages from %s and static files from disk\n", mainTarget)
} else {
r.Printf("Serving pages from %s\n", mainTarget)
}
}
var httpFs *afero.HttpFs
f.c.withConf(func(conf *commonConfig) {
httpFs = afero.NewHttpFs(conf.fs.PublishDirServer)
})
fs := filesOnlyFs{httpFs.Dir(path.Join("/", root))}
if i == 0 && f.c.fastRenderMode {
r.Println("Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender")
}
decorate := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if f.c.showErrorInBrowser {
// First check the error state
err := f.c.getErrorWithContext()
if err != nil {
f.c.errState.setWasErr(true)
w.WriteHeader(500)
r, err := f.errorTemplate(err)
if err != nil {
logger.Errorln(err)
}
port = 1313
f.c.withConf(func(conf *commonConfig) {
if lrport := conf.configs.GetFirstLanguageConfig().BaseURLLiveReload().Port(); lrport != 0 {
port = lrport
}
})
lr := baseURL.URL()
lr.Host = fmt.Sprintf("%s:%d", lr.Hostname(), port)
fmt.Fprint(w, injectLiveReloadScript(r, lr))
return
}
}
if f.c.noHTTPCache {
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
w.Header().Set("Pragma", "no-cache")
}
var serverConfig config.Server
f.c.withConf(func(conf *commonConfig) {
serverConfig = conf.configs.Base.Server
})
// Ignore any query params for the operations below.
requestURI, _ := url.PathUnescape(strings.TrimSuffix(r.RequestURI, "?"+r.URL.RawQuery))
for _, header := range serverConfig.MatchHeaders(requestURI) {
w.Header().Set(header.Key, header.Value)
}
if canRedirect(requestURI, r) {
if redirect := serverConfig.MatchRedirect(requestURI, r.Header); !redirect.IsZero() {
doRedirect := true
// This matches Netlify's behavior and is needed for SPA behavior.
// See https://docs.netlify.com/routing/redirects/rewrites-proxies/
if !redirect.Force {
path := filepath.Clean(strings.TrimPrefix(requestURI, baseURL.Path()))
if root != "" {
path = filepath.Join(root, path)
}
var fs afero.Fs
f.c.withConf(func(conf *commonConfig) {
fs = conf.fs.PublishDirServer
})
fi, err := fs.Stat(path)
if err == nil {
if fi.IsDir() {
// There will be overlapping directories, so we
// need to check for a file.
_, err = fs.Stat(filepath.Join(path, "index.html"))
doRedirect = err != nil
} else {
doRedirect = false
}
}
}
if doRedirect {
w.Header().Set(hugoHeaderRedirect, "true")
switch redirect.Status {
case 404:
w.WriteHeader(404)
file, err := fs.Open(strings.TrimPrefix(redirect.To, baseURL.Path()))
if err == nil {
defer file.Close()
io.Copy(w, file)
} else {
fmt.Fprintln(w, "<h1>Page Not Found</h1>")
}
return
case 200:
if r2 := f.rewriteRequest(r, strings.TrimPrefix(redirect.To, baseURL.Path())); r2 != nil {
requestURI = redirect.To
r = r2
}
default:
w.Header().Set("Content-Type", "")
http.Redirect(w, r, redirect.To, redirect.Status)
return
}
}
}
}
if f.c.fastRenderMode && f.c.errState.buildErr() == nil {
if isNavigation(requestURI, r) {
// See issue 14240.
// Hugo escapes the URL paths when generating them,
// that may not be the case when we receive it back from the browser.
// PathEscape will escape if it is not already escaped.
requestURI = paths.PathEscape(requestURI)
if !f.c.visitedURLs.Contains(requestURI) {
// If not already on stack, re-render that single page.
if err := f.c.partialReRender(requestURI); err != nil {
f.c.handleBuildErr(err, fmt.Sprintf("Failed to render %q", requestURI))
if f.c.showErrorInBrowser {
http.Redirect(w, r, requestURI, http.StatusMovedPermanently)
return
}
}
}
f.c.visitedURLs.Add(requestURI)
}
}
h.ServeHTTP(w, r)
})
}
fileserver := decorate(http.FileServer(fs))
mu := http.NewServeMux()
if baseURL.Path() == "" || baseURL.Path() == "/" {
mu.Handle("/", fileserver)
} else {
mu.Handle(baseURL.Path(), http.StripPrefix(baseURL.Path(), fileserver))
}
if r.IsTestRun() {
var shutDownOnce sync.Once
mu.HandleFunc("/__stop", func(w http.ResponseWriter, r *http.Request) {
shutDownOnce.Do(func() {
close(f.c.quit)
})
})
}
endpoint := net.JoinHostPort(f.c.serverInterface, strconv.Itoa(port))
return mu, listener, baseURL.String(), endpoint, nil
}
func (f *fileServer) rewriteRequest(r *http.Request, toPath string) *http.Request {
r2 := new(http.Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = toPath
r2.Header.Set("X-Rewrite-Original-URI", r.URL.RequestURI())
return r2
}
type filesOnlyFs struct {
fs http.FileSystem
}
func (fs filesOnlyFs) Open(name string) (http.File, error) {
f, err := fs.fs.Open(name)
if err != nil {
return nil, err
}
return noDirFile{f}, nil
}
type noDirFile struct {
http.File
}
func (f noDirFile) Readdir(count int) ([]os.FileInfo, error) {
return nil, nil
}
type serverCommand struct {
r *rootCommand
commands []simplecobra.Commander
*hugoBuilder
quit chan bool // Closed when the server should shut down. Used in tests only.
serverPorts []serverPortListener
doLiveReload bool
// Flags.
renderStaticToDisk bool
navigateToChanged bool
openBrowser bool
serverAppend bool
serverInterface string
tlsCertFile string
tlsKeyFile string
tlsAuto bool
pprof bool
serverPort int
liveReloadPort int
serverWatch bool
noHTTPCache bool
disableLiveReload bool
disableFastRender bool
disableBrowserError bool
}
func (c *serverCommand) Name() string {
return "server"
}
func (c *serverCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
if c.pprof {
go func() {
http.ListenAndServe("localhost:8080", nil)
}()
}
// Watch runs its own server as part of the routine
if c.serverWatch {
watchDirs, err := c.getDirList()
if err != nil {
return err
}
watchGroups := helpers.ExtractAndGroupRootPaths(watchDirs)
c.r.Printf("Watching for changes in %s\n", strings.Join(watchGroups, ", "))
watcher, err := c.newWatcher(c.r.poll, watchDirs...)
if err != nil {
return err
}
defer watcher.Close()
}
err := func() error {
defer c.r.timeTrack(time.Now(), "Built")
return c.build()
}()
if err != nil {
return err
}
return c.serve()
}
func (c *serverCommand) Init(cd *simplecobra.Commandeer) error {
cmd := cd.CobraCommand
cmd.Short = "Start the embedded web server"
cmd.Long = `Hugo provides its own webserver which builds and serves the site.
While hugo server is high performance, it is a webserver with limited options.
The ` + "`" + `hugo server` + "`" + ` command will by default write and serve files from disk, but
you can render to memory by using the ` + "`" + `--renderToMemory` + "`" + ` flag. This can be
faster in some cases, but it will consume more memory.
By default hugo will also watch your files for any changes you make and
automatically rebuild the site. It will then live reload any open browser pages
and push the latest content to them. As most Hugo sites are built in a fraction
of a second, you will be able to save and see your changes nearly instantly.`
cmd.Aliases = []string{"serve"}
cmd.Flags().IntVarP(&c.serverPort, "port", "p", 1313, "port on which the server will listen")
_ = cmd.RegisterFlagCompletionFunc("port", cobra.NoFileCompletions)
cmd.Flags().IntVar(&c.liveReloadPort, "liveReloadPort", -1, "port for live reloading (i.e. 443 in HTTPS proxy situations)")
_ = cmd.RegisterFlagCompletionFunc("liveReloadPort", cobra.NoFileCompletions)
cmd.Flags().StringVarP(&c.serverInterface, "bind", "", "127.0.0.1", "interface to which the server will bind")
_ = cmd.RegisterFlagCompletionFunc("bind", cobra.NoFileCompletions)
cmd.Flags().StringVarP(&c.tlsCertFile, "tlsCertFile", "", "", "path to TLS certificate file")
_ = cmd.MarkFlagFilename("tlsCertFile", "pem")
cmd.Flags().StringVarP(&c.tlsKeyFile, "tlsKeyFile", "", "", "path to TLS key file")
_ = cmd.MarkFlagFilename("tlsKeyFile", "pem")
cmd.Flags().BoolVar(&c.tlsAuto, "tlsAuto", false, "generate and use locally-trusted certificates.")
cmd.Flags().BoolVar(&c.pprof, "pprof", false, "enable the pprof server (port 8080)")
cmd.Flags().BoolVarP(&c.serverWatch, "watch", "w", true, "watch filesystem for changes and recreate as needed")
cmd.Flags().BoolVar(&c.noHTTPCache, "noHTTPCache", false, "prevent HTTP caching")
cmd.Flags().BoolVarP(&c.serverAppend, "appendPort", "", true, "append port to baseURL")
cmd.Flags().BoolVar(&c.disableLiveReload, "disableLiveReload", false, "watch without enabling live browser reload on rebuild")
cmd.Flags().BoolVarP(&c.navigateToChanged, "navigateToChanged", "N", false, "navigate to changed content file on live browser reload")
cmd.Flags().BoolVarP(&c.openBrowser, "openBrowser", "O", false, "open the site in a browser after server startup")
cmd.Flags().BoolVar(&c.renderStaticToDisk, "renderStaticToDisk", false, "serve static files from disk and dynamic files from memory")
cmd.Flags().BoolVar(&c.disableFastRender, "disableFastRender", false, "enables full re-renders on changes")
cmd.Flags().BoolVar(&c.disableBrowserError, "disableBrowserError", false, "do not show build errors in the browser")
r := cd.Root.Command.(*rootCommand)
applyLocalFlagsBuild(cmd, r)
return nil
}
func (c *serverCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
c.r = cd.Root.Command.(*rootCommand)
c.hugoBuilder = newHugoBuilder(
c.r,
c,
func(reloaded bool) error {
if !reloaded {
if err := c.createServerPorts(cd); err != nil {
return err
}
if (c.tlsCertFile == "" || c.tlsKeyFile == "") && c.tlsAuto {
c.withConfE(func(conf *commonConfig) error {
return c.createCertificates(conf)
})
}
}
if err := c.setServerInfoInConfig(); err != nil {
return err
}
if !reloaded && c.fastRenderMode {
c.withConf(func(conf *commonConfig) {
conf.fs.PublishDir = hugofs.NewHashingFs(conf.fs.PublishDir, c.changeDetector)
conf.fs.PublishDirStatic = hugofs.NewHashingFs(conf.fs.PublishDirStatic, c.changeDetector)
})
}
return nil
},
)
destinationFlag := cd.CobraCommand.Flags().Lookup("destination")
if c.r.renderToMemory && (destinationFlag != nil && destinationFlag.Changed) {
return fmt.Errorf("cannot use --renderToMemory with --destination")
}
c.doLiveReload = !c.disableLiveReload
c.fastRenderMode = !c.disableFastRender
c.showErrorInBrowser = c.doLiveReload && !c.disableBrowserError
if c.fastRenderMode {
// For now, fast render mode only. It should, however, be fast enough
// for the full variant, too.
c.changeDetector = &fileChangeDetector{
// We use this detector to decide to do a Hot reload of a single path or not.
// We need to filter out source maps and possibly some other to be able
// to make that decision.
irrelevantRe: regexp.MustCompile(`\.map$`),
}
c.changeDetector.PrepareNew()
}
err := c.loadConfig(cd, true)
if err != nil {
return err
}
return nil
}
func (c *serverCommand) setServerInfoInConfig() error {
if len(c.serverPorts) == 0 {
panic("no server ports set")
}
return c.withConfE(func(conf *commonConfig) error {
for i, language := range conf.configs.Languages {
isMultihost := conf.configs.IsMultihost
var serverPort int
if isMultihost {
serverPort = c.serverPorts[i].p
} else {
serverPort = c.serverPorts[0].p
}
langConfig := conf.configs.LanguageConfigMap[language.Lang]
baseURLStr, err := c.fixURL(langConfig.BaseURL, c.r.baseURL, serverPort)
if err != nil {
return err
}
baseURL, err := urls.NewBaseURLFromString(baseURLStr)
if err != nil {
return fmt.Errorf("failed to create baseURL from %q: %s", baseURLStr, err)
}
baseURLLiveReload := baseURL
if c.liveReloadPort != -1 {
baseURLLiveReload, _ = baseURLLiveReload.WithPort(c.liveReloadPort)
}
langConfig.C.SetServerInfo(baseURL, baseURLLiveReload, c.serverInterface)
}
return nil
})
}
func (c *serverCommand) getErrorWithContext() any {
buildErr := c.errState.buildErr()
if buildErr == nil {
return nil
}
m := make(map[string]any)
m["Error"] = cleanErrorLog(c.r.logger.Errors())
m["Version"] = hugo.BuildVersionString()
ferrors := herrors.UnwrapFileErrorsWithErrorContext(buildErr)
m["Files"] = ferrors
return m
}
func (c *serverCommand) createCertificates(conf *commonConfig) error {
hostname := "localhost"
if c.r.baseURL != "" {
u, err := url.Parse(c.r.baseURL)
if err != nil {
return err
}
hostname = u.Hostname()
}
// For now, store these in the Hugo cache dir.
// Hugo should probably introduce some concept of a less temporary application directory.
keyDir := filepath.Join(conf.configs.LoadingInfo.BaseConfig.CacheDir, "_mkcerts")
// Create the directory if it doesn't exist.
if _, err := os.Stat(keyDir); os.IsNotExist(err) {
if err := os.MkdirAll(keyDir, 0o777); err != nil {
return err
}
}
c.tlsCertFile = filepath.Join(keyDir, fmt.Sprintf("%s.pem", hostname))
c.tlsKeyFile = filepath.Join(keyDir, fmt.Sprintf("%s-key.pem", hostname))
// Check if the certificate already exists and is valid.
certPEM, err := os.ReadFile(c.tlsCertFile)
if err == nil {
rootPem, err := os.ReadFile(filepath.Join(mclib.GetCAROOT(), "rootCA.pem"))
if err == nil {
if err := c.verifyCert(rootPem, certPEM, hostname); err == nil {
c.r.Println("Using existing", c.tlsCertFile, "and", c.tlsKeyFile)
return nil
}
}
}
c.r.Println("Creating TLS certificates in", keyDir)
// Yes, this is unfortunate, but it's currently the only way to use Mkcert as a library.
os.Args = []string{"-cert-file", c.tlsCertFile, "-key-file", c.tlsKeyFile, hostname}
return mclib.RunMain()
}
func (c *serverCommand) verifyCert(rootPEM, certPEM []byte, name string) error {
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM(rootPEM)
if !ok {
return fmt.Errorf("failed to parse root certificate")
}
block, _ := pem.Decode(certPEM)
if block == nil {
return fmt.Errorf("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse certificate: %v", err.Error())
}
opts := x509.VerifyOptions{
DNSName: name,
Roots: roots,
}
if _, err := cert.Verify(opts); err != nil {
return fmt.Errorf("failed to verify certificate: %v", err.Error())
}
return nil
}
func (c *serverCommand) createServerPorts(cd *simplecobra.Commandeer) error {
flags := cd.CobraCommand.Flags()
var cerr error
c.withConf(func(conf *commonConfig) {
isMultihost := conf.configs.IsMultihost
c.serverPorts = make([]serverPortListener, 1)
if isMultihost {
if !c.serverAppend {
cerr = errors.New("--appendPort=false not supported when in multihost mode")
return
}
c.serverPorts = make([]serverPortListener, len(conf.configs.Languages))
}
currentServerPort := c.serverPort
for i := range c.serverPorts {
l, err := net.Listen("tcp", net.JoinHostPort(c.serverInterface, strconv.Itoa(currentServerPort)))
if err == nil {
c.serverPorts[i] = serverPortListener{ln: l, p: currentServerPort}
} else {
if i == 0 && flags.Changed("port") {
// port set explicitly by user -- he/she probably meant it!
cerr = fmt.Errorf("server startup failed: %s", err)
return
}
c.r.Println("port", currentServerPort, "already in use, attempting to use an available port")
l, sp, err := helpers.TCPListen()
if err != nil {
cerr = fmt.Errorf("unable to find alternative port to use: %s", err)
return
}
c.serverPorts[i] = serverPortListener{ln: l, p: sp.Port}
}
currentServerPort = c.serverPorts[i].p + 1
}
})
return cerr
}
// fixURL massages the baseURL into a form needed for serving
// all pages correctly.
func (c *serverCommand) fixURL(baseURLFromConfig, baseURLFromFlag string, port int) (string, error) {
certsSet := (c.tlsCertFile != "" && c.tlsKeyFile != "") || c.tlsAuto
useLocalhost := false
baseURL := baseURLFromFlag
if baseURL == "" {
baseURL = baseURLFromConfig
useLocalhost = true
}
if !strings.HasSuffix(baseURL, "/") {
baseURL = baseURL + "/"
}
// do an initial parse of the input string
u, err := url.Parse(baseURL)
if err != nil {
return "", err
}
// if no Host is defined, then assume that no schema or double-slash were
// present in the url. Add a double-slash and make a best effort attempt.
if u.Host == "" && baseURL != "/" {
baseURL = "//" + baseURL
u, err = url.Parse(baseURL)
if err != nil {
return "", err
}
}
if useLocalhost {
if certsSet {
u.Scheme = "https"
} else if u.Scheme == "https" {
u.Scheme = "http"
}
u.Host = "localhost"
}
if c.serverAppend {
if strings.Contains(u.Host, ":") {
u.Host, _, err = net.SplitHostPort(u.Host)
if err != nil {
return "", fmt.Errorf("failed to split baseURL hostport: %w", err)
}
}
u.Host += fmt.Sprintf(":%d", port)
}
return u.String(), nil
}
func (c *serverCommand) partialReRender(urls ...string) (err error) {
defer func() {
c.errState.setWasErr(false)
}()
visited := types.NewEvictingQueue[string](len(urls))
for _, url := range urls {
visited.Add(url)
}
var h *hugolib.HugoSites
h, err = c.hugo()
if err != nil {
return
}
// Note: We do not set NoBuildLock as the file lock is not acquired at this stage.
err = h.Build(hugolib.BuildCfg{NoBuildLock: false, RecentlyTouched: visited, PartialReRender: true, ErrRecovery: c.errState.wasErr()})
return
}
func (c *serverCommand) serve() error {
var (
baseURLs []urls.BaseURL
roots []string
h *hugolib.HugoSites
)
err := c.withConfE(func(conf *commonConfig) error {
isMultihost := conf.configs.IsMultihost
var err error
h, err = c.r.HugFromConfig(conf)
if err != nil {
return err
}
// We need the server to share the same logger as the Hugo build (for error counts etc.)
c.r.logger = h.Log
if isMultihost {
for _, l := range conf.configs.ConfigLangs() {
baseURLs = append(baseURLs, l.BaseURL())
roots = append(roots, l.Language().(*langs.Language).Lang)
}
} else {
l := conf.configs.GetFirstLanguageConfig()
baseURLs = []urls.BaseURL{l.BaseURL()}
roots = []string{""}
}
return nil
})
if err != nil {
return err
}
// Cache it here. The HugoSites object may be unavailable later on due to intermittent configuration errors.
// To allow the en user to change the error template while the server is running, we use
// the freshest template we can provide.
var (
errTempl *tplimpl.TemplInfo
templHandler *tplimpl.TemplateStore
)
getErrorTemplateAndHandler := func(h *hugolib.HugoSites) (*tplimpl.TemplInfo, *tplimpl.TemplateStore) {
if h == nil {
return errTempl, templHandler
}
templHandler := h.GetTemplateStore()
errTempl := templHandler.LookupByPath("/_server/error.html")
if errTempl == nil {
panic("template server/error.html not found")
}
return errTempl, templHandler
}
errTempl, templHandler = getErrorTemplateAndHandler(h)
srv := &fileServer{
baseURLs: baseURLs,
roots: roots,
c: c,
errorTemplate: func(ctx any) (io.Reader, error) {
// hugoTry does not block, getErrorTemplateAndHandler will fall back
// to cached values if nil.
templ, handler := getErrorTemplateAndHandler(c.hugoTry())
b := &bytes.Buffer{}
err := handler.ExecuteWithContext(context.Background(), templ, b, ctx)
return b, err
},
}
doLiveReload := !c.disableLiveReload
if doLiveReload {
livereload.Initialize()
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
var servers []*http.Server
wg1, ctx := errgroup.WithContext(context.Background())
for i := range baseURLs {
mu, listener, serverURL, endpoint, err := srv.createEndpoint(i)
var srv *http.Server
if c.tlsCertFile != "" && c.tlsKeyFile != "" {
srv = &http.Server{
Addr: endpoint,
Handler: mu,
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
},
}
} else {
srv = &http.Server{
Addr: endpoint,
Handler: mu,
}
}
servers = append(servers, srv)
if doLiveReload {
baseURL := baseURLs[i]
mu.HandleFunc(baseURL.Path()+"livereload.js", livereload.ServeJS)
mu.HandleFunc(baseURL.Path()+"livereload", livereload.Handler)
}
c.r.Printf("Web Server is available at %s (bind address %s) %s\n", serverURL, c.serverInterface, roots[i])
wg1.Go(func() error {
if c.tlsCertFile != "" && c.tlsKeyFile != "" {
err = srv.ServeTLS(listener, c.tlsCertFile, c.tlsKeyFile)
} else {
err = srv.Serve(listener)
}
if err != nil && err != http.ErrServerClosed {
return err
}
return nil
})
}
if c.r.IsTestRun() {
// Write a .ready file to disk to signal ready status.
// This is where the test is run from.
var baseURLs []string
for _, baseURL := range srv.baseURLs {
baseURLs = append(baseURLs, baseURL.String())
}
testInfo := map[string]any{
"baseURLs": baseURLs,
}
dir := os.Getenv("WORK")
if dir != "" {
readyFile := filepath.Join(dir, ".ready")
// encode the test info as JSON into the .ready file.
b, err := json.Marshal(testInfo)
if err != nil {
return err
}
err = os.WriteFile(readyFile, b, 0o777)
if err != nil {
return err
}
}
}
c.r.Println("Press Ctrl+C to stop")
if c.openBrowser {
// There may be more than one baseURL in multihost mode, open the first.
if err := browser.OpenURL(baseURLs[0].String()); err != nil {
c.r.logger.Warnf("Failed to open browser: %s", err)
}
}
err = func() error {
for {
select {
case <-c.quit:
return nil
case <-sigs:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
}()
if err != nil {
c.r.Println("Error:", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
wg2, ctx := errgroup.WithContext(ctx)
for _, srv := range servers {
wg2.Go(func() error {
return srv.Shutdown(ctx)
})
}
err1, err2 := wg1.Wait(), wg2.Wait()
if err1 != nil {
return err1
}
return err2
}
type serverPortListener struct {
p int
ln net.Listener
}
type staticSyncer struct {
c *hugoBuilder
}
func (s *staticSyncer) isStatic(h *hugolib.HugoSites, filename string) bool {
return h.BaseFs.SourceFilesystems.IsStatic(filename)
}
func (s *staticSyncer) syncsStaticEvents(staticEvents []fsnotify.Event) error {
c := s.c
syncFn := func(sourceFs *filesystems.SourceFilesystem) (uint64, error) {
publishDir := helpers.FilePathSeparator
if sourceFs.PublishFolder != "" {
publishDir = filepath.Join(publishDir, sourceFs.PublishFolder)
}
syncer := fsync.NewSyncer()
c.withConf(func(conf *commonConfig) {
syncer.NoTimes = conf.configs.Base.NoTimes
syncer.NoChmod = conf.configs.Base.NoChmod
syncer.ChmodFilter = chmodFilter
syncer.SrcFs = sourceFs.Fs
syncer.DestFs = conf.fs.PublishDir
if c.s != nil && c.s.renderStaticToDisk {
syncer.DestFs = conf.fs.PublishDirStatic
}
})
logger := s.c.r.logger
for _, ev := range staticEvents {
// Due to our approach of layering both directories and the content's rendered output
// into one we can't accurately remove a file not in one of the source directories.
// If a file is in the local static dir and also in the theme static dir and we remove
// it from one of those locations we expect it to still exist in the destination
//
// If Hugo generates a file (from the content dir) over a static file
// the content generated file should take precedence.
//
// Because we are now watching and handling individual events it is possible that a static
// event that occupies the same path as a content generated file will take precedence
// until a regeneration of the content takes places.
//
// Hugo assumes that these cases are very rare and will permit this bad behavior
// The alternative is to track every single file and which pipeline rendered it
// and then to handle conflict resolution on every event.
fromPath := ev.Name
relPath, found := sourceFs.MakePathRelative(fromPath, true)
if !found {
// Not member of this virtual host.
continue
}
// Remove || rename is harder and will require an assumption.
// Hugo takes the following approach:
// If the static file exists in any of the static source directories after this event
// Hugo will re-sync it.
// If it does not exist in all of the static directories Hugo will remove it.
//
// This assumes that Hugo has not generated content on top of a static file and then removed
// the source of that static file. In this case Hugo will incorrectly remove that file
// from the published directory.
if ev.Op&fsnotify.Rename == fsnotify.Rename || ev.Op&fsnotify.Remove == fsnotify.Remove {
if _, err := sourceFs.Fs.Stat(relPath); herrors.IsNotExist(err) {
// If file doesn't exist in any static dir, remove it
logger.Println("File no longer exists in static dir, removing", relPath)
c.withConf(func(conf *commonConfig) {
_ = conf.fs.PublishDirStatic.RemoveAll(relPath)
})
} else if err == nil {
// If file still exists, sync it
logger.Println("Syncing", relPath, "to", publishDir)
if err := syncer.Sync(relPath, relPath); err != nil {
c.r.logger.Errorln(err)
}
} else {
c.r.logger.Errorln(err)
}
continue
}
// For all other event operations Hugo will sync static.
logger.Println("Syncing", relPath, "to", publishDir)
if err := syncer.Sync(filepath.Join(publishDir, relPath), relPath); err != nil {
c.r.logger.Errorln(err)
}
}
return 0, nil
}
_, err := c.doWithPublishDirs(syncFn)
return err
}
func chmodFilter(dst, src os.FileInfo) bool {
// Hugo publishes data from multiple sources, potentially
// with overlapping directory structures. We cannot sync permissions
// for directories as that would mean that we might end up with write-protected
// directories inside /public.
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | true |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/env.go | commands/env.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 commands
import (
"context"
"runtime"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/common/hugo"
"github.com/spf13/cobra"
)
func newEnvCommand() simplecobra.Commander {
return &simpleCommand{
name: "env",
short: "Display version and environment info",
long: "Display version and environment info. This is useful in Hugo bug reports",
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
r.Printf("%s\n", hugo.BuildVersionString())
r.Printf("GOOS=%q\n", runtime.GOOS)
r.Printf("GOARCH=%q\n", runtime.GOARCH)
r.Printf("GOVERSION=%q\n", runtime.Version())
if r.isVerbose() {
deps := hugo.GetDependencyList()
for _, dep := range deps {
r.Printf("%s\n", dep)
}
} else {
// These are also included in the GetDependencyList above;
// always print these as these are most likely the most useful to know about.
deps := hugo.GetDependencyListNonGo()
for _, dep := range deps {
r.Printf("%s\n", dep)
}
}
return nil
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
}
}
func newVersionCmd() simplecobra.Commander {
return &simpleCommand{
name: "version",
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
r.Println(hugo.BuildVersionString())
return nil
},
short: "Display version",
long: "Display version and environment info. This is useful in Hugo bug reports.",
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
},
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/new.go | commands/new.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 commands
import (
"bytes"
"context"
"path/filepath"
"strings"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/create"
"github.com/gohugoio/hugo/create/skeletons"
"github.com/spf13/cobra"
)
func newNewCommand() *newCommand {
var (
force bool
contentType string
format string
)
var c *newCommand
c = &newCommand{
commands: []simplecobra.Commander{
&simpleCommand{
name: "content",
use: "content [path]",
short: "Create new content",
long: `Create a new content file and automatically set the date and title.
It will guess which kind of file to create based on the path provided.
You can also specify the kind with ` + "`-k KIND`" + `.
If archetypes are provided in your theme or site, they will be used.
Ensure you run this within the root directory of your site.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
if len(args) < 1 {
return newUserError("path needs to be provided")
}
cfg := flagsToCfg(cd, nil)
cfg.Set("BuildFuture", true)
h, err := r.Hugo(cfg)
if err != nil {
return err
}
return create.NewContent(h, contentType, args[0], force)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return []string{}, cobra.ShellCompDirectiveNoFileComp
}
return []string{}, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveFilterDirs
}
cmd.Flags().StringVarP(&contentType, "kind", "k", "", "content type to create")
cmd.Flags().String("editor", "", "edit new content with this editor, if provided")
_ = cmd.RegisterFlagCompletionFunc("editor", cobra.NoFileCompletions)
cmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite file if it already exists")
applyLocalFlagsBuildConfig(cmd, r)
},
},
&simpleCommand{
name: "site",
use: "site [path]",
short: "Create a new site",
long: `Create a new site at the specified path.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
if len(args) < 1 {
return newUserError("path needs to be provided")
}
createpath, err := filepath.Abs(filepath.Clean(args[0]))
if err != nil {
return err
}
cfg := config.New()
cfg.Set("workingDir", createpath)
cfg.Set("publishDir", "public")
conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, cfg))
if err != nil {
return err
}
sourceFs := conf.fs.Source
err = skeletons.CreateSite(createpath, sourceFs, force, format)
if err != nil {
return err
}
r.Printf("Congratulations! Your new Hugo site was created in %s.\n\n", createpath)
r.Println(c.newSiteNextStepsText(createpath, format))
return nil
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return []string{}, cobra.ShellCompDirectiveNoFileComp
}
return []string{}, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveFilterDirs
}
cmd.Flags().BoolVarP(&force, "force", "f", false, "init inside non-empty directory")
cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)")
_ = cmd.RegisterFlagCompletionFunc("format", cobra.FixedCompletions([]string{"toml", "yaml", "json"}, cobra.ShellCompDirectiveNoFileComp))
},
},
&simpleCommand{
name: "theme",
use: "theme [name]",
short: "Create a new theme",
long: `Create a new theme with the specified name in the ./themes directory.
This generates a functional theme including template examples and sample content.`,
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
if len(args) < 1 {
return newUserError("theme name needs to be provided")
}
cfg := config.New()
cfg.Set("publishDir", "public")
conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, cfg))
if err != nil {
return err
}
sourceFs := conf.fs.Source
createpath := paths.AbsPathify(conf.configs.Base.WorkingDir, filepath.Join(conf.configs.Base.ThemesDir, args[0]))
r.Println("Creating new theme in", createpath)
err = skeletons.CreateTheme(createpath, sourceFs, format)
if err != nil {
return err
}
return nil
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return []string{}, cobra.ShellCompDirectiveNoFileComp
}
return []string{}, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveFilterDirs
}
cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)")
_ = cmd.RegisterFlagCompletionFunc("format", cobra.FixedCompletions([]string{"toml", "yaml", "json"}, cobra.ShellCompDirectiveNoFileComp))
},
},
},
}
return c
}
type newCommand struct {
rootCmd *rootCommand
commands []simplecobra.Commander
}
func (c *newCommand) Commands() []simplecobra.Commander {
return c.commands
}
func (c *newCommand) Name() string {
return "new"
}
func (c *newCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
return nil
}
func (c *newCommand) Init(cd *simplecobra.Commandeer) error {
cmd := cd.CobraCommand
cmd.Short = "Create new content"
cmd.Long = `Create a new content file and automatically set the date and title.
It will guess which kind of file to create based on the path provided.
You can also specify the kind with ` + "`-k KIND`" + `.
If archetypes are provided in your theme or site, they will be used.
Ensure you run this within the root directory of your site.`
cmd.RunE = nil
return nil
}
func (c *newCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
c.rootCmd = cd.Root.Command.(*rootCommand)
return nil
}
func (c *newCommand) newSiteNextStepsText(path string, format string) string {
format = strings.ToLower(format)
var nextStepsText bytes.Buffer
nextStepsText.WriteString(`Just a few more steps...
1. Change the current directory to ` + path + `.
2. Create or install a theme:
- Create a new theme with the command "hugo new theme <THEMENAME>"
- Or, install a theme from https://themes.gohugo.io/
3. Edit hugo.` + format + `, setting the "theme" property to the theme name.
4. Create new content with the command "hugo new content `)
nextStepsText.WriteString(filepath.Join("<SECTIONNAME>", "<FILENAME>.<FORMAT>"))
nextStepsText.WriteString(`".
5. Start the embedded web server with the command "hugo server --buildDrafts".
See documentation at https://gohugo.io/.`)
return nextStepsText.String()
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/helpers.go | commands/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 commands
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/config"
"github.com/spf13/pflag"
)
const (
ansiEsc = "\u001B"
clearLine = "\r\033[K"
hideCursor = ansiEsc + "[?25l"
showCursor = ansiEsc + "[?25h"
)
func newUserError(a ...any) *simplecobra.CommandError {
return &simplecobra.CommandError{Err: errors.New(fmt.Sprint(a...))}
}
func setValueFromFlag(flags *pflag.FlagSet, key string, cfg config.Provider, targetKey string, force bool) {
key = strings.TrimSpace(key)
if (force && flags.Lookup(key) != nil) || flags.Changed(key) {
f := flags.Lookup(key)
configKey := key
if targetKey != "" {
configKey = targetKey
}
// Gotta love this API.
switch f.Value.Type() {
case "bool":
bv, _ := flags.GetBool(key)
cfg.Set(configKey, bv)
case "string":
cfg.Set(configKey, f.Value.String())
case "stringSlice":
bv, _ := flags.GetStringSlice(key)
cfg.Set(configKey, bv)
case "int":
iv, _ := flags.GetInt(key)
cfg.Set(configKey, iv)
default:
panic(fmt.Sprintf("update switch with %s", f.Value.Type()))
}
}
}
func flagsToCfg(cd *simplecobra.Commandeer, cfg config.Provider) config.Provider {
return flagsToCfgWithAdditionalConfigBase(cd, cfg, "")
}
func flagsToCfgWithAdditionalConfigBase(cd *simplecobra.Commandeer, cfg config.Provider, additionalConfigBase string) config.Provider {
if cfg == nil {
cfg = config.New()
}
// Flags with a different name in the config.
keyMap := map[string]string{
"minify": "minify.minifyOutput",
"destination": "publishDir",
"editor": "newContentEditor",
}
// Flags that we for some reason don't want to expose in the site config.
internalKeySet := map[string]bool{
"quiet": true,
"verbose": true,
"watch": true,
"liveReloadPort": true,
"renderToMemory": true,
"clock": true,
}
cmd := cd.CobraCommand
flags := cmd.Flags()
flags.VisitAll(func(f *pflag.Flag) {
if f.Changed {
targetKey := f.Name
if internalKeySet[targetKey] {
targetKey = "internal." + targetKey
} else if mapped, ok := keyMap[targetKey]; ok {
targetKey = mapped
}
setValueFromFlag(flags, f.Name, cfg, targetKey, false)
if additionalConfigBase != "" {
setValueFromFlag(flags, f.Name, cfg, additionalConfigBase+"."+targetKey, true)
}
}
})
return cfg
}
func mkdir(x ...string) {
p := filepath.Join(x...)
err := os.MkdirAll(p, 0o777) // before umask
if err != nil {
log.Fatal(err)
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/deploy_flags.go | commands/deploy_flags.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 commands
import (
"github.com/gohugoio/hugo/deploy/deployconfig"
"github.com/spf13/cobra"
)
func applyDeployFlags(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.Flags().String("target", "", "target deployment from deployments section in config file; defaults to the first one")
_ = cmd.RegisterFlagCompletionFunc("target", cobra.NoFileCompletions)
cmd.Flags().Bool("confirm", false, "ask for confirmation before making changes to the target")
cmd.Flags().Bool("dryRun", false, "dry run")
cmd.Flags().Bool("force", false, "force upload of all files")
cmd.Flags().Bool("invalidateCDN", deployconfig.DefaultConfig.InvalidateCDN, "invalidate the CDN cache listed in the deployment target")
cmd.Flags().Int("maxDeletes", deployconfig.DefaultConfig.MaxDeletes, "maximum # of files to delete, or -1 to disable")
_ = cmd.RegisterFlagCompletionFunc("maxDeletes", cobra.NoFileCompletions)
cmd.Flags().Int("workers", deployconfig.DefaultConfig.Workers, "number of workers to transfer files. defaults to 10")
_ = cmd.RegisterFlagCompletionFunc("workers", cobra.NoFileCompletions)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/commands/import.go | commands/import.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 commands
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"github.com/bep/simplecobra"
"github.com/gohugoio/hugo/common/htime"
"github.com/gohugoio/hugo/common/hugio"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/parser"
"github.com/gohugoio/hugo/parser/metadecoders"
"github.com/gohugoio/hugo/parser/pageparser"
"github.com/spf13/afero"
"github.com/spf13/cobra"
)
func newImportCommand() *importCommand {
var c *importCommand
c = &importCommand{
commands: []simplecobra.Commander{
&simpleCommand{
name: "jekyll",
short: "hugo import from Jekyll",
long: `hugo import from Jekyll.
Import from Jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.",
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
if len(args) < 2 {
return newUserError(`import from jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.")
}
return c.importFromJekyll(args)
},
withc: func(cmd *cobra.Command, r *rootCommand) {
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.Flags().BoolVar(&c.force, "force", false, "allow import into non-empty target directory")
},
},
},
}
return c
}
type importCommand struct {
r *rootCommand
force bool
commands []simplecobra.Commander
}
func (c *importCommand) Commands() []simplecobra.Commander {
return c.commands
}
func (c *importCommand) Name() string {
return "import"
}
func (c *importCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
return nil
}
func (c *importCommand) Init(cd *simplecobra.Commandeer) error {
cmd := cd.CobraCommand
cmd.Short = "Import a site from another system"
cmd.Long = `Import a site from another system.
Import requires a subcommand, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`."
cmd.RunE = nil
return nil
}
func (c *importCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
c.r = cd.Root.Command.(*rootCommand)
return nil
}
func (i *importCommand) createConfigFromJekyll(fs afero.Fs, inpath string, kind metadecoders.Format, jekyllConfig map[string]any) (err error) {
title := "My New Hugo Site"
baseURL := "http://example.org/"
for key, value := range jekyllConfig {
lowerKey := strings.ToLower(key)
switch lowerKey {
case "title":
if str, ok := value.(string); ok {
title = str
}
case "url":
if str, ok := value.(string); ok {
baseURL = str
}
}
}
in := map[string]any{
"baseURL": baseURL,
"title": title,
"languageCode": "en-us",
"disablePathToLower": true,
}
var buf bytes.Buffer
err = parser.InterfaceToConfig(in, kind, &buf)
if err != nil {
return err
}
return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+string(kind)), &buf, fs)
}
func (c *importCommand) getJekyllDirInfo(fs afero.Fs, jekyllRoot string) (map[string]bool, bool) {
postDirs := make(map[string]bool)
hasAnyPost := false
if entries, err := os.ReadDir(jekyllRoot); err == nil {
for _, entry := range entries {
if entry.IsDir() {
subDir := filepath.Join(jekyllRoot, entry.Name())
if isPostDir, hasAnyPostInDir := c.retrieveJekyllPostDir(fs, subDir); isPostDir {
postDirs[entry.Name()] = hasAnyPostInDir
if hasAnyPostInDir {
hasAnyPost = true
}
}
}
}
}
return postDirs, hasAnyPost
}
func (c *importCommand) createSiteFromJekyll(jekyllRoot, targetDir string, jekyllPostDirs map[string]bool) error {
fs := &afero.OsFs{}
if exists, _ := helpers.Exists(targetDir, fs); exists {
if isDir, _ := helpers.IsDir(targetDir, fs); !isDir {
return errors.New("target path \"" + targetDir + "\" exists but is not a directory")
}
isEmpty, _ := helpers.IsEmpty(targetDir, fs)
if !isEmpty && !c.force {
return errors.New("target path \"" + targetDir + "\" exists and is not empty")
}
}
jekyllConfig := c.loadJekyllConfig(fs, jekyllRoot)
mkdir(targetDir, "layouts")
mkdir(targetDir, "content")
mkdir(targetDir, "archetypes")
mkdir(targetDir, "static")
mkdir(targetDir, "data")
mkdir(targetDir, "themes")
c.createConfigFromJekyll(fs, targetDir, "yaml", jekyllConfig)
c.copyJekyllFilesAndFolders(jekyllRoot, filepath.Join(targetDir, "static"), jekyllPostDirs)
return nil
}
func (c *importCommand) convertJekyllContent(m any, content string) (string, error) {
metadata, _ := maps.ToStringMapE(m)
lines := strings.Split(content, "\n")
var resultLines []string
for _, line := range lines {
resultLines = append(resultLines, strings.Trim(line, "\r\n"))
}
content = strings.Join(resultLines, "\n")
excerptSep := "<!--more-->"
if value, ok := metadata["excerpt_separator"]; ok {
if str, strOk := value.(string); strOk {
content = strings.Replace(content, strings.TrimSpace(str), excerptSep, -1)
}
}
replaceList := []struct {
re *regexp.Regexp
replace string
}{
{regexp.MustCompile("(?i)<!-- more -->"), "<!--more-->"},
{regexp.MustCompile(`\{%\s*raw\s*%\}\s*(.*?)\s*\{%\s*endraw\s*%\}`), "$1"},
{regexp.MustCompile(`{%\s*endhighlight\s*%}`), "{{< / highlight >}}"},
}
for _, replace := range replaceList {
content = replace.re.ReplaceAllString(content, replace.replace)
}
replaceListFunc := []struct {
re *regexp.Regexp
replace func(string) string
}{
// Octopress image tag: http://octopress.org/docs/plugins/image-tag/
{regexp.MustCompile(`{%\s+img\s*(.*?)\s*%}`), c.replaceImageTag},
{regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`), c.replaceHighlightTag},
}
for _, replace := range replaceListFunc {
content = replace.re.ReplaceAllStringFunc(content, replace.replace)
}
var buf bytes.Buffer
if len(metadata) != 0 {
err := parser.InterfaceToFrontMatter(m, metadecoders.YAML, &buf)
if err != nil {
return "", err
}
}
buf.WriteString(content)
return buf.String(), nil
}
func (c *importCommand) convertJekyllMetaData(m any, postName string, postDate time.Time, draft bool) (any, error) {
metadata, err := maps.ToStringMapE(m)
if err != nil {
return nil, err
}
if draft {
metadata["draft"] = true
}
for key, value := range metadata {
lowerKey := strings.ToLower(key)
switch lowerKey {
case "layout":
delete(metadata, key)
case "permalink":
if str, ok := value.(string); ok {
metadata["url"] = str
}
delete(metadata, key)
case "category":
if str, ok := value.(string); ok {
metadata["categories"] = []string{str}
}
delete(metadata, key)
case "excerpt_separator":
if key != lowerKey {
delete(metadata, key)
metadata[lowerKey] = value
}
case "date":
if str, ok := value.(string); ok {
re := regexp.MustCompile(`(\d+):(\d+):(\d+)`)
r := re.FindAllStringSubmatch(str, -1)
if len(r) > 0 {
hour, _ := strconv.Atoi(r[0][1])
minute, _ := strconv.Atoi(r[0][2])
second, _ := strconv.Atoi(r[0][3])
postDate = time.Date(postDate.Year(), postDate.Month(), postDate.Day(), hour, minute, second, 0, time.UTC)
}
}
delete(metadata, key)
}
}
metadata["date"] = postDate.Format(time.RFC3339)
return metadata, nil
}
func (c *importCommand) convertJekyllPost(path, relPath, targetDir string, draft bool) error {
log.Println("Converting", path)
filename := filepath.Base(path)
postDate, postName, err := c.parseJekyllFilename(filename)
if err != nil {
c.r.Printf("Failed to parse filename '%s': %s. Skipping.", filename, err)
return nil
}
log.Println(filename, postDate, postName)
targetFile := filepath.Join(targetDir, relPath)
targetParentDir := filepath.Dir(targetFile)
os.MkdirAll(targetParentDir, 0o777)
contentBytes, err := os.ReadFile(path)
if err != nil {
c.r.logger.Errorln("Read file error:", path)
return err
}
pf, err := pageparser.ParseFrontMatterAndContent(bytes.NewReader(contentBytes))
if err != nil {
return fmt.Errorf("failed to parse file %q: %s", filename, err)
}
newmetadata, err := c.convertJekyllMetaData(pf.FrontMatter, postName, postDate, draft)
if err != nil {
return fmt.Errorf("failed to convert metadata for file %q: %s", filename, err)
}
content, err := c.convertJekyllContent(newmetadata, string(pf.Content))
if err != nil {
return fmt.Errorf("failed to convert content for file %q: %s", filename, err)
}
fs := hugofs.Os
if err := helpers.WriteToDisk(targetFile, strings.NewReader(content), fs); err != nil {
return fmt.Errorf("failed to save file %q: %s", filename, err)
}
return nil
}
func (c *importCommand) copyJekyllFilesAndFolders(jekyllRoot, dest string, jekyllPostDirs map[string]bool) (err error) {
fs := hugofs.Os
fi, err := fs.Stat(jekyllRoot)
if err != nil {
return err
}
if !fi.IsDir() {
return errors.New(jekyllRoot + " is not a directory")
}
err = os.MkdirAll(dest, fi.Mode())
if err != nil {
return err
}
entries, err := os.ReadDir(jekyllRoot)
if err != nil {
return err
}
for _, entry := range entries {
sfp := filepath.Join(jekyllRoot, entry.Name())
dfp := filepath.Join(dest, entry.Name())
if entry.IsDir() {
if entry.Name()[0] != '_' && entry.Name()[0] != '.' {
if _, ok := jekyllPostDirs[entry.Name()]; !ok {
err = hugio.CopyDir(fs, sfp, dfp, nil)
if err != nil {
c.r.logger.Errorln(err)
}
}
}
} else {
lowerEntryName := strings.ToLower(entry.Name())
exceptSuffix := []string{
".md", ".markdown", ".html", ".htm",
".xml", ".textile", "rakefile", "gemfile", ".lock",
}
isExcept := false
for _, suffix := range exceptSuffix {
if strings.HasSuffix(lowerEntryName, suffix) {
isExcept = true
break
}
}
if !isExcept && entry.Name()[0] != '.' && entry.Name()[0] != '_' {
err = hugio.CopyFile(fs, sfp, dfp)
if err != nil {
c.r.logger.Errorln(err)
}
}
}
}
return nil
}
func (c *importCommand) importFromJekyll(args []string) error {
jekyllRoot, err := filepath.Abs(filepath.Clean(args[0]))
if err != nil {
return newUserError("path error:", args[0])
}
targetDir, err := filepath.Abs(filepath.Clean(args[1]))
if err != nil {
return newUserError("path error:", args[1])
}
c.r.Println("Import Jekyll from:", jekyllRoot, "to:", targetDir)
if strings.HasPrefix(filepath.Dir(targetDir), jekyllRoot) {
return newUserError("abort: target path should not be inside the Jekyll root")
}
fs := afero.NewOsFs()
jekyllPostDirs, hasAnyPost := c.getJekyllDirInfo(fs, jekyllRoot)
if !hasAnyPost {
return errors.New("abort: jekyll root contains neither posts nor drafts")
}
err = c.createSiteFromJekyll(jekyllRoot, targetDir, jekyllPostDirs)
if err != nil {
return newUserError(err)
}
c.r.Println("Importing...")
fileCount := 0
callback := func(ctx context.Context, path string, fi hugofs.FileMetaInfo) error {
if fi.IsDir() {
return nil
}
relPath, err := filepath.Rel(jekyllRoot, path)
if err != nil {
return newUserError("get rel path error:", path)
}
relPath = filepath.ToSlash(relPath)
draft := false
switch {
case strings.Contains(relPath, "_posts/"):
relPath = filepath.Join("content/post", strings.Replace(relPath, "_posts/", "", -1))
case strings.Contains(relPath, "_drafts/"):
relPath = filepath.Join("content/draft", strings.Replace(relPath, "_drafts/", "", -1))
draft = true
default:
return nil
}
fileCount++
return c.convertJekyllPost(path, relPath, targetDir, draft)
}
for jekyllPostDir, hasAnyPostInDir := range jekyllPostDirs {
if hasAnyPostInDir {
if err = helpers.Walk(hugofs.Os, filepath.Join(jekyllRoot, jekyllPostDir), callback); err != nil {
return err
}
}
}
c.r.Println("Congratulations!", fileCount, "post(s) imported!")
c.r.Println("Now, start Hugo by yourself:\n")
c.r.Println("cd " + args[1])
c.r.Println("git init")
c.r.Println("git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke themes/ananke")
c.r.Println("echo \"theme = 'ananke'\" > hugo.toml")
c.r.Println("hugo server")
return nil
}
func (c *importCommand) loadJekyllConfig(fs afero.Fs, jekyllRoot string) map[string]any {
path := filepath.Join(jekyllRoot, "_config.yml")
exists, err := helpers.Exists(path, fs)
if err != nil || !exists {
c.r.Println("_config.yaml not found: Is the specified Jekyll root correct?")
return nil
}
f, err := fs.Open(path)
if err != nil {
return nil
}
defer f.Close()
b, err := io.ReadAll(f)
if err != nil {
return nil
}
m, err := metadecoders.Default.UnmarshalToMap(b, metadecoders.YAML)
if err != nil {
return nil
}
return m
}
func (c *importCommand) parseJekyllFilename(filename string) (time.Time, string, error) {
re := regexp.MustCompile(`(\d+-\d+-\d+)-(.+)\..*`)
r := re.FindAllStringSubmatch(filename, -1)
if len(r) == 0 {
return htime.Now(), "", errors.New("filename not match")
}
postDate, err := time.Parse("2006-1-2", r[0][1])
if err != nil {
return htime.Now(), "", err
}
postName := r[0][2]
return postDate, postName, nil
}
func (c *importCommand) replaceHighlightTag(match string) string {
r := regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`)
parts := r.FindStringSubmatch(match)
lastQuote := rune(0)
f := func(c rune) bool {
switch {
case c == lastQuote:
lastQuote = rune(0)
return false
case lastQuote != rune(0):
return false
case unicode.In(c, unicode.Quotation_Mark):
lastQuote = c
return false
default:
return unicode.IsSpace(c)
}
}
// splitting string by space but considering quoted section
items := strings.FieldsFunc(parts[1], f)
result := bytes.NewBufferString("{{< highlight ")
result.WriteString(items[0]) // language
options := items[1:]
for i, opt := range options {
opt = strings.Replace(opt, "\"", "", -1)
if opt == "linenos" {
opt = "linenos=table"
}
if i == 0 {
opt = " \"" + opt
}
if i < len(options)-1 {
opt += ","
} else if i == len(options)-1 {
opt += "\""
}
result.WriteString(opt)
}
result.WriteString(" >}}")
return result.String()
}
func (c *importCommand) replaceImageTag(match string) string {
r := regexp.MustCompile(`{%\s+img\s*(\p{L}*)\s+([\S]*/[\S]+)\s+(\d*)\s*(\d*)\s*(.*?)\s*%}`)
result := bytes.NewBufferString("{{< figure ")
parts := r.FindStringSubmatch(match)
// Index 0 is the entire string, ignore
c.replaceOptionalPart(result, "class", parts[1])
c.replaceOptionalPart(result, "src", parts[2])
c.replaceOptionalPart(result, "width", parts[3])
c.replaceOptionalPart(result, "height", parts[4])
// title + alt
part := parts[5]
if len(part) > 0 {
splits := strings.Split(part, "'")
lenSplits := len(splits)
if lenSplits == 1 {
c.replaceOptionalPart(result, "title", splits[0])
} else if lenSplits == 3 {
c.replaceOptionalPart(result, "title", splits[1])
} else if lenSplits == 5 {
c.replaceOptionalPart(result, "title", splits[1])
c.replaceOptionalPart(result, "alt", splits[3])
}
}
result.WriteString(">}}")
return result.String()
}
func (c *importCommand) replaceOptionalPart(buffer *bytes.Buffer, partName string, part string) {
if len(part) > 0 {
buffer.WriteString(partName + "=\"" + part + "\" ")
}
}
func (c *importCommand) retrieveJekyllPostDir(fs afero.Fs, dir string) (bool, bool) {
if strings.HasSuffix(dir, "_posts") || strings.HasSuffix(dir, "_drafts") {
isEmpty, _ := helpers.IsEmpty(dir, fs)
return true, !isEmpty
}
if entries, err := os.ReadDir(dir); err == nil {
for _, entry := range entries {
if entry.IsDir() {
subDir := filepath.Join(dir, entry.Name())
if isPostDir, hasAnyPost := c.retrieveJekyllPostDir(fs, subDir); isPostDir {
return isPostDir, hasAnyPost
}
}
}
}
return false, true
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/publisher/htmlElementsCollector.go | publisher/htmlElementsCollector.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 publisher
import (
"bytes"
"regexp"
"sort"
"strings"
"sync"
"unicode"
"unicode/utf8"
"golang.org/x/net/html"
"github.com/gohugoio/hugo/common/hstrings"
"github.com/gohugoio/hugo/config"
)
const eof = -1
var (
htmlJsonFixer = strings.NewReplacer(", ", "\n")
jsonAttrRe = regexp.MustCompile(`'?(.*?)'?:\s.*`)
classAttrRe = regexp.MustCompile(`(?i)^class$|transition`)
skipInnerElementRe = regexp.MustCompile(`(?i)^(pre|textarea|script|style)`)
skipAllElementRe = regexp.MustCompile(`(?i)^!DOCTYPE`)
exceptionList = map[string]bool{
"thead": true,
"tbody": true,
"tfoot": true,
"td": true,
"tr": true,
}
)
func newHTMLElementsCollector(conf config.BuildStats) *htmlElementsCollector {
return &htmlElementsCollector{
conf: conf,
elementSet: make(map[string]bool),
}
}
func newHTMLElementsCollectorWriter(collector *htmlElementsCollector) *htmlElementsCollectorWriter {
w := &htmlElementsCollectorWriter{
collector: collector,
state: htmlLexStart,
}
w.defaultLexElementInside = w.lexElementInside(htmlLexStart)
return w
}
// HTMLElements holds lists of tags and attribute values for classes and id.
type HTMLElements struct {
Tags []string `json:"tags"`
Classes []string `json:"classes"`
IDs []string `json:"ids"`
}
func (h *HTMLElements) Merge(other HTMLElements) {
h.Tags = append(h.Tags, other.Tags...)
h.Classes = append(h.Classes, other.Classes...)
h.IDs = append(h.IDs, other.IDs...)
h.Tags = hstrings.UniqueStringsReuse(h.Tags)
h.Classes = hstrings.UniqueStringsReuse(h.Classes)
h.IDs = hstrings.UniqueStringsReuse(h.IDs)
}
func (h *HTMLElements) Sort() {
sort.Strings(h.Tags)
sort.Strings(h.Classes)
sort.Strings(h.IDs)
}
type htmlElement struct {
Tag string
Classes []string
IDs []string
}
type htmlElementsCollector struct {
conf config.BuildStats
// Contains the raw HTML string. We will get the same element
// several times, and want to avoid costly reparsing when this
// is used for aggregated data only.
elementSet map[string]bool
elements []htmlElement
mu sync.RWMutex
}
func (c *htmlElementsCollector) getHTMLElements() HTMLElements {
var (
classes []string
ids []string
tags []string
)
for _, el := range c.elements {
classes = append(classes, el.Classes...)
ids = append(ids, el.IDs...)
if !c.conf.DisableTags {
tags = append(tags, el.Tag)
}
}
classes = hstrings.UniqueStringsSorted(classes)
ids = hstrings.UniqueStringsSorted(ids)
tags = hstrings.UniqueStringsSorted(tags)
els := HTMLElements{
Classes: classes,
IDs: ids,
Tags: tags,
}
return els
}
type htmlElementsCollectorWriter struct {
collector *htmlElementsCollector
r rune // Current rune
width int // The width in bytes of r
input []byte // The current slice written to Write
pos int // The current position in input
err error
inQuote rune
buff bytes.Buffer
// Current state
state htmlCollectorStateFunc
// Precompiled state funcs
defaultLexElementInside htmlCollectorStateFunc
}
// Write collects HTML elements from p, which must contain complete runes.
func (w *htmlElementsCollectorWriter) Write(p []byte) (int, error) {
if p == nil {
return 0, nil
}
w.input = p
for {
w.r = w.next()
if w.r == eof || w.r == utf8.RuneError {
break
}
w.state = w.state(w)
}
w.pos = 0
w.input = nil
return len(p), nil
}
func (l *htmlElementsCollectorWriter) backup() {
l.pos -= l.width
l.r, _ = utf8.DecodeRune(l.input[l.pos:])
}
func (w *htmlElementsCollectorWriter) consumeBuffUntil(condition func() bool, resolve htmlCollectorStateFunc) htmlCollectorStateFunc {
var s htmlCollectorStateFunc
s = func(*htmlElementsCollectorWriter) htmlCollectorStateFunc {
w.buff.WriteRune(w.r)
if condition() {
w.buff.Reset()
return resolve
}
return s
}
return s
}
func (w *htmlElementsCollectorWriter) consumeRuneUntil(condition func(r rune) bool, resolve htmlCollectorStateFunc) htmlCollectorStateFunc {
var s htmlCollectorStateFunc
s = func(*htmlElementsCollectorWriter) htmlCollectorStateFunc {
if condition(w.r) {
return resolve
}
return s
}
return s
}
// Starts with e.g. "<body " or "<div"
func (w *htmlElementsCollectorWriter) lexElementInside(resolve htmlCollectorStateFunc) htmlCollectorStateFunc {
var s htmlCollectorStateFunc
s = func(w *htmlElementsCollectorWriter) htmlCollectorStateFunc {
w.buff.WriteRune(w.r)
// Skip any text inside a quote.
if w.r == '\'' || w.r == '"' {
if w.inQuote == w.r {
w.inQuote = 0
} else if w.inQuote == 0 {
w.inQuote = w.r
}
}
if w.inQuote != 0 {
return s
}
if w.r == '>' {
// Work with the bytes slice as long as it's practical,
// to save memory allocations.
b := w.buff.Bytes()
defer func() {
w.buff.Reset()
}()
// First check if we have processed this element before.
w.collector.mu.RLock()
seen := w.collector.elementSet[string(b)]
w.collector.mu.RUnlock()
if seen {
return resolve
}
s := w.buff.String()
if s == "" {
return resolve
}
// Parse each collected element.
el, err := w.parseHTMLElement(s)
if err != nil {
w.err = err
return resolve
}
// Write this tag to the element set.
w.collector.mu.Lock()
w.collector.elementSet[s] = true
w.collector.elements = append(w.collector.elements, el)
w.collector.mu.Unlock()
return resolve
}
return s
}
return s
}
func (l *htmlElementsCollectorWriter) next() rune {
if l.pos >= len(l.input) {
l.width = 0
return eof
}
runeValue, runeWidth := utf8.DecodeRune(l.input[l.pos:])
l.width = runeWidth
l.pos += l.width
return runeValue
}
// returns the next state in HTML element scanner.
type htmlCollectorStateFunc func(*htmlElementsCollectorWriter) htmlCollectorStateFunc
// At "<", buffer empty.
// Potentially starting a HTML element.
func htmlLexElementStart(w *htmlElementsCollectorWriter) htmlCollectorStateFunc {
if w.r == '>' || unicode.IsSpace(w.r) {
if w.buff.Len() < 2 || bytes.HasPrefix(w.buff.Bytes(), []byte("</")) {
w.buff.Reset()
return htmlLexStart
}
tagName := w.buff.Bytes()[1:]
isSelfClosing := tagName[len(tagName)-1] == '/'
switch {
case !isSelfClosing && skipInnerElementRe.Match(tagName):
// pre, script etc. We collect classes etc. on the surrounding
// element, but skip the inner content.
w.backup()
// tagName will be overwritten, so make a copy.
tagNameCopy := make([]byte, len(tagName))
copy(tagNameCopy, tagName)
return w.lexElementInside(
w.consumeBuffUntil(
func() bool {
if w.r != '>' {
return false
}
return isClosedByTag(w.buff.Bytes(), tagNameCopy)
},
htmlLexStart,
))
case skipAllElementRe.Match(tagName):
// E.g. "<!DOCTYPE ..."
w.buff.Reset()
return w.consumeRuneUntil(func(r rune) bool {
return r == '>'
}, htmlLexStart)
default:
w.backup()
return w.defaultLexElementInside
}
}
w.buff.WriteRune(w.r)
// If it's a comment, skip to its end.
if w.r == '-' && bytes.Equal(w.buff.Bytes(), []byte("<!--")) {
w.buff.Reset()
return htmlLexToEndOfComment
}
return htmlLexElementStart
}
// Entry state func.
// Looks for a opening bracket, '<'.
func htmlLexStart(w *htmlElementsCollectorWriter) htmlCollectorStateFunc {
if w.r == '<' {
w.backup()
w.buff.Reset()
return htmlLexElementStart
}
return htmlLexStart
}
// After "<!--", buff empty.
func htmlLexToEndOfComment(w *htmlElementsCollectorWriter) htmlCollectorStateFunc {
w.buff.WriteRune(w.r)
if w.r == '>' && bytes.HasSuffix(w.buff.Bytes(), []byte("-->")) {
// Done, start looking for HTML elements again.
return htmlLexStart
}
return htmlLexToEndOfComment
}
func (w *htmlElementsCollectorWriter) parseHTMLElement(elStr string) (el htmlElement, err error) {
conf := w.collector.conf
tagName := parseStartTag(elStr)
el.Tag = strings.ToLower(tagName)
tagNameToParse := el.Tag
// The net/html parser does not handle single table elements as input, e.g. tbody.
// We only care about the element/class/ids, so just store away the original tag name
// and pretend it's a <div>.
if exceptionList[el.Tag] {
elStr = strings.Replace(elStr, tagName, "div", 1)
tagNameToParse = "div"
}
n, err := html.Parse(strings.NewReader(elStr))
if err != nil {
return
}
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == tagNameToParse {
for _, a := range n.Attr {
switch {
case strings.EqualFold(a.Key, "id"):
// There should be only one, but one never knows...
if !conf.DisableIDs {
el.IDs = append(el.IDs, a.Val)
}
default:
if conf.DisableClasses {
continue
}
if classAttrRe.MatchString(a.Key) {
el.Classes = append(el.Classes, strings.Fields(a.Val)...)
} else {
key := strings.ToLower(a.Key)
val := strings.TrimSpace(a.Val)
if strings.Contains(key, ":class") {
if strings.HasPrefix(val, "{") {
// This looks like a Vue or AlpineJS class binding.
val = htmlJsonFixer.Replace(strings.Trim(val, "{}"))
lines := strings.Split(val, "\n")
for i, l := range lines {
lines[i] = strings.TrimSpace(l)
}
val = strings.Join(lines, "\n")
val = jsonAttrRe.ReplaceAllString(val, "$1")
el.Classes = append(el.Classes, strings.Fields(val)...)
}
// Also add single quoted strings.
// This may introduce some false positives, but it covers some missing cases in the above.
// E.g. AlpinesJS' :class="isTrue 'class1' : 'class2'"
el.Classes = append(el.Classes, extractSingleQuotedStrings(val)...)
}
}
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(n)
return
}
// Variants of s
//
// <body class="b a">
// <div>
func parseStartTag(s string) string {
spaceIndex := strings.IndexFunc(s, func(r rune) bool {
return unicode.IsSpace(r)
})
if spaceIndex == -1 {
s = s[1 : len(s)-1]
} else {
s = s[1:spaceIndex]
}
if s[len(s)-1] == '/' {
// Self closing.
s = s[:len(s)-1]
}
return s
}
// isClosedByTag reports whether b ends with a closing tag for tagName.
func isClosedByTag(b, tagName []byte) bool {
if len(b) == 0 {
return false
}
if b[len(b)-1] != '>' {
return false
}
var (
lo int
hi int
state int
inWord bool
)
LOOP:
for i := len(b) - 2; i >= 0; i-- {
switch {
case b[i] == '<':
if state != 1 {
return false
}
state = 2
break LOOP
case b[i] == '/':
if state != 0 {
return false
}
state++
if inWord {
lo = i + 1
inWord = false
}
case isSpace(b[i]):
if inWord {
lo = i + 1
inWord = false
}
default:
if !inWord {
hi = i + 1
inWord = true
}
}
}
if state != 2 || lo >= hi {
return false
}
return bytes.EqualFold(tagName, b[lo:hi])
}
func isSpace(b byte) bool {
return b == ' ' || b == '\t' || b == '\n'
}
func extractSingleQuotedStrings(s string) []string {
var (
inQuote bool
lo int
hi int
)
var words []string
for i, r := range s {
switch {
case r == '\'':
if !inQuote {
inQuote = true
lo = i + 1
} else {
inQuote = false
hi = i
words = append(words, strings.Fields(s[lo:hi])...)
}
}
}
return words
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/publisher/htmlElementsCollector_test.go | publisher/htmlElementsCollector_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 publisher
import (
"bytes"
"fmt"
"io"
"math/rand"
"strings"
"testing"
"time"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/config/testconfig"
"github.com/gohugoio/hugo/media"
"github.com/gohugoio/hugo/minifiers"
"github.com/gohugoio/hugo/output"
qt "github.com/frankban/quicktest"
)
func TestClassCollector(t *testing.T) {
c := qt.New((t))
rnd := rand.New(rand.NewSource(time.Now().Unix()))
f := func(tags, classes, ids string) HTMLElements {
var tagss, classess, idss []string
if tags != "" {
tagss = strings.Split(tags, " ")
}
if classes != "" {
classess = strings.Split(classes, " ")
}
if ids != "" {
idss = strings.Split(ids, " ")
}
return HTMLElements{
Tags: tagss,
Classes: classess,
IDs: idss,
}
}
skipMinifyTest := map[string]bool{
"Script tags content should be skipped": true, // https://github.com/tdewolff/minify/issues/396
}
for _, test := range []struct {
name string
html string
expect HTMLElements
}{
{"basic", `<body class="b a"></body>`, f("body", "a b", "")},
{"duplicates", `<div class="b a b"></div><div class="b a b"></div>x'`, f("div", "a b", "")},
{"single quote", `<body class='b a'></body>`, f("body", "a b", "")},
{"no quote", `<body class=b id=myelement></body>`, f("body", "b", "myelement")},
{"short", `<i>`, f("i", "", "")},
{"invalid", `< body class="b a"></body><div></div>`, f("div", "", "")},
// https://github.com/gohugoio/hugo/issues/7318
{"thead", `<table class="cl1">
<thead class="cl2"><tr class="cl3"><td class="cl4"></td></tr></thead>
<tbody class="cl5"><tr class="cl6"><td class="cl7"></td></tr></tbody>
</table>`, f("table tbody td thead tr", "cl1 cl2 cl3 cl4 cl5 cl6 cl7", "")},
{"thead uppercase", `<TABLE class="CL1">
<THEAD class="CL2"><TR class="CL3"><TD class="CL4"></TD></TR></THEAD>
<TBODY class="CL5"><TR class="CL6"><TD class="CL7"></TD></TR></TBODY>
</TABLE>`, f("table tbody td thead tr", "CL1 CL2 CL3 CL4 CL5 CL6 CL7", "")},
// https://github.com/gohugoio/hugo/issues/7161
{"minified a href", `<a class="b a" href=/></a>`, f("a", "a b", "")},
{"AlpineJS bind 1", `<body>
<div x-bind:class="{
'class1': data.open,
'class2 class3': data.foo == 'bar'
}">
</div>
</body>`, f("body div", "class1 class2 class3", "")},
{
"AlpineJS bind 2", `<div x-bind:class="{ 'bg-black': filter.checked }" class="inline-block mr-1 mb-2 rounded bg-gray-300 px-2 py-2">FOO</div>`,
f("div", "bg-black bg-gray-300 inline-block mb-2 mr-1 px-2 py-2 rounded", ""),
},
{"AlpineJS bind 3", `<div x-bind:class="{ 'text-gray-800': !checked, 'text-white': checked }"></div>`, f("div", "text-gray-800 text-white", "")},
{"AlpineJS bind 4", `<div x-bind:class="{ 'text-gray-800': !checked,
'text-white': checked }"></div>`, f("div", "text-gray-800 text-white", "")},
{"AlpineJS bind 5", `<a x-bind:class="{
'text-a': a && b,
'text-b': !a && b || c,
'pl-3': a === 1,
pl-2: b == 3,
'text-gray-600': (a > 1)
}" class="block w-36 cursor-pointer pr-3 no-underline capitalize"></a>`, f("a", "block capitalize cursor-pointer no-underline pl-2 pl-3 pr-3 text-a text-b text-gray-600 w-36", "")},
{"AlpineJS bind 6", `<button :class="isActive(32) ? 'border-gray-500 bg-white pt border-t-2' : 'border-transparent hover:bg-gray-100'"></button>`, f("button", "bg-white border-gray-500 border-t-2 border-transparent hover:bg-gray-100 pt", "")},
{"AlpineJS bind 7", `<button :class="{ 'border-gray-500 bg-white pt border-t-2': isActive(32), 'border-transparent hover:bg-gray-100': !isActive(32) }"></button>`, f("button", "bg-white border-gray-500 border-t-2 border-transparent hover:bg-gray-100 pt", "")},
{"AlpineJS transition 1", `<div x-transition:enter-start="opacity-0 transform mobile:-translate-x-8 sm:-translate-y-8">`, f("div", "mobile:-translate-x-8 opacity-0 sm:-translate-y-8 transform", "")},
{"Vue bind", `<div v-bind:class="{ active: isActive }"></div>`, f("div", "active", "")},
// Issue #7746
{"Apostrophe inside attribute value", `<a class="missingclass" title="Plus d'information">my text</a><div></div>`, f("a div", "missingclass", "")},
// Issue #7567
{"Script tags content should be skipped", `<script><span>foo</span><span>bar</span></script><div class="foo"></div>`, f("div script", "foo", "")},
{"Style tags content should be skipped", `<style>p{color: red;font-size: 20px;}</style><div class="foo"></div>`, f("div style", "foo", "")},
{"Pre tags content should be skipped", `<pre class="preclass"><span>foo</span><span>bar</span></pre><div class="foo"></div>`, f("div pre", "foo preclass", "")},
{"Textarea tags content should be skipped", `<textarea class="textareaclass"><span>foo</span><span>bar</span></textarea><div class="foo"></div>`, f("div textarea", "foo textareaclass", "")},
{"DOCTYPE should beskipped", `<!DOCTYPE html>`, f("", "", "")},
{"Comments should be skipped", `<!-- example comment -->`, f("", "", "")},
{"Comments with elements before and after", `<div></div><!-- example comment --><span><span>`, f("div span", "", "")},
{"Self closing tag", `<div><hr/></div>`, f("div hr", "", "")},
// svg with self closing style tag.
{"SVG with self closing style tag", `<svg><style/><g><path class="foo"/></g></svg>`, f("g path style svg", "foo", "")},
// Issue #8530
{"Comment with single quote", `<!-- Hero Area Image d'accueil --><i class="foo">`, f("i", "foo", "")},
{"Uppercase tags", `<DIV></DIV>`, f("div", "", "")},
{"Predefined tags with distinct casing", `<script>if (a < b) { nothing(); }</SCRIPT><div></div>`, f("div script", "", "")},
// Issue #8417
{"Tabs inline", `<hr id="a" class="foo"><div class="bar">d</div>`, f("div hr", "bar foo", "a")},
{"Tabs on multiple rows", `<form
id="a"
action="www.example.com"
method="post"
></form>
<div id="b" class="foo">d</div>`, f("div form", "foo", "a b")},
{"Big input, multibyte runes", strings.Repeat(`神真美好 `, rnd.Intn(500)+1) + "<div id=\"神真美好\" class=\"foo\">" + strings.Repeat(`神真美好 `, rnd.Intn(100)+1) + " <span>神真美好</span>", f("div span", "foo", "神真美好")},
} {
for _, variant := range []struct {
minify bool
}{
{minify: false},
{minify: true},
} {
name := fmt.Sprintf("%s--minify-%t", test.name, variant.minify)
c.Run(name, func(c *qt.C) {
w := newHTMLElementsCollectorWriter(newHTMLElementsCollector(
config.BuildStats{Enable: true},
))
if variant.minify {
if skipMinifyTest[test.name] {
c.Skip("skip minify test")
}
m, _ := minifiers.New(media.DefaultTypes, output.DefaultFormats, testconfig.GetTestConfig(nil, nil))
m.Minify(media.Builtin.HTMLType, w, strings.NewReader(test.html))
} else {
var buff bytes.Buffer
buff.WriteString(test.html)
io.Copy(w, &buff)
}
got := w.collector.getHTMLElements()
c.Assert(got, qt.DeepEquals, test.expect)
})
}
}
}
func TestEndsWithTag(t *testing.T) {
c := qt.New((t))
for _, test := range []struct {
name string
s string
tagName string
expect bool
}{
{"empty", "", "div", false},
{"no match", "foo", "div", false},
{"no close", "foo<div>", "div", false},
{"no close 2", "foo/div>", "div", false},
{"no close 2", "foo//div>", "div", false},
{"no tag", "foo</>", "div", false},
{"match", "foo</div>", "div", true},
{"match space", "foo< / div>", "div", true},
{"match space 2", "foo< / div \n>", "div", true},
{"match case", "foo</DIV>", "div", true},
{"self closing", `</defs><g><g><path fill="#010101" d=asdf"/>`, "div", false},
} {
c.Run(test.name, func(c *qt.C) {
got := isClosedByTag([]byte(test.s), []byte(test.tagName))
c.Assert(got, qt.Equals, test.expect)
})
}
}
func BenchmarkElementsCollectorWriter(b *testing.B) {
const benchHTML = `
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<style>
a {color: red;}
.c {color: blue;}
</style>
</head>
<body id="i1" class="a b c d">
<a class="c d e"></a>
<hr>
<a class="c d e"></a>
<a class="c d e"></a>
<hr>
<a id="i2" class="c d e f"></a>
<a id="i3" class="c d e"></a>
<a class="c d e"></a>
<p>To force<br> line breaks<br> in a text,<br> use the br<br> element.</p>
<hr>
<a class="c d e"></a>
<a class="c d e"></a>
<a class="c d e"></a>
<a class="c d e"></a>
<table>
<thead class="ch">
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody class="cb">
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$200</td>
</tr>
</tbody>
<tfoot class="cf">
<tr>
<td></td>
<td>$300</td>
</tr>
</tfoot>
</table>
</body>
</html>
`
for b.Loop() {
w := newHTMLElementsCollectorWriter(newHTMLElementsCollector(
config.BuildStats{Enable: true},
))
fmt.Fprint(w, benchHTML)
}
}
func BenchmarkElementsCollectorWriterPre(b *testing.B) {
const benchHTML = `
<pre class="preclass">
<span>foo</span><span>bar</span>
<!-- many more span elements -->
<span class="foo">foo</span>
<span class="bar">bar</span>
<span class="baz">baz</span>
<span class="qux">qux</span>
<span class="quux">quux</span>
<span class="quuz">quuz</span>
<span class="corge">corge</span>
</pre>
<div class="foo"></div>
`
w := newHTMLElementsCollectorWriter(newHTMLElementsCollector(
config.BuildStats{Enable: true},
))
for b.Loop() {
fmt.Fprint(w, benchHTML)
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/publisher/publisher.go | publisher/publisher.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 publisher
import (
"errors"
"fmt"
"io"
"net/url"
"sync/atomic"
"github.com/gohugoio/hugo/resources"
"github.com/gohugoio/hugo/media"
"github.com/gohugoio/hugo/minifiers"
bp "github.com/gohugoio/hugo/bufferpool"
"github.com/gohugoio/hugo/helpers"
"github.com/spf13/afero"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/transform"
"github.com/gohugoio/hugo/transform/livereloadinject"
"github.com/gohugoio/hugo/transform/metainject"
"github.com/gohugoio/hugo/transform/urlreplacers"
)
// Descriptor describes the needed publishing chain for an item.
type Descriptor struct {
// The content to publish.
Src io.Reader
// The OutputFormat of the this content.
OutputFormat output.Format
// Where to publish this content. This is a filesystem-relative path.
TargetPath string
// Counter for the end build summary.
StatCounter *uint64
// Configuration that trigger pre-processing.
// LiveReload script will be injected if this is != nil
LiveReloadBaseURL *url.URL
// Enable to inject the Hugo generated tag in the header. Is currently only
// injected on the home page for HTML type of output formats.
AddHugoGeneratorTag bool
// If set, will replace all relative URLs with this one.
AbsURLPath string
// Enable to minify the output using the OutputFormat defined above to
// pick the correct minifier configuration.
Minify bool
}
// DestinationPublisher is the default and currently only publisher in Hugo. This
// publisher prepares and publishes an item to the defined destination, e.g. /public.
type DestinationPublisher struct {
fs afero.Fs
min minifiers.Client
htmlElementsCollector *htmlElementsCollector
}
// NewDestinationPublisher creates a new DestinationPublisher.
func NewDestinationPublisher(rs *resources.Spec, outputFormats output.Formats, mediaTypes media.Types) (pub DestinationPublisher, err error) {
fs := rs.BaseFs.PublishFs
cfg := rs.Cfg
var classCollector *htmlElementsCollector
if rs.BuildConfig().BuildStats.Enabled() {
classCollector = newHTMLElementsCollector(rs.BuildConfig().BuildStats)
}
pub = DestinationPublisher{fs: fs, htmlElementsCollector: classCollector}
pub.min, err = minifiers.New(mediaTypes, outputFormats, cfg)
return
}
// Publish applies any relevant transformations and writes the file
// to its destination, e.g. /public.
func (p DestinationPublisher) Publish(d Descriptor) error {
if d.TargetPath == "" {
return errors.New("Publish: must provide a TargetPath")
}
src := d.Src
transformers := p.createTransformerChain(d)
if len(transformers) != 0 {
b := bp.GetBuffer()
defer bp.PutBuffer(b)
if err := transformers.Apply(b, d.Src); err != nil {
return fmt.Errorf("failed to process %q: %w", d.TargetPath, err)
}
// This is now what we write to disk.
src = b
}
f, err := helpers.OpenFileForWriting(p.fs, d.TargetPath)
if err != nil {
return err
}
defer f.Close()
var w io.Writer = f
if p.htmlElementsCollector != nil && d.OutputFormat.IsHTML {
w = io.MultiWriter(w, newHTMLElementsCollectorWriter(p.htmlElementsCollector))
}
_, err = io.Copy(w, src)
if err == nil && d.StatCounter != nil {
atomic.AddUint64(d.StatCounter, uint64(1))
}
return err
}
func (p DestinationPublisher) PublishStats() PublishStats {
if p.htmlElementsCollector == nil {
return PublishStats{}
}
return PublishStats{
HTMLElements: p.htmlElementsCollector.getHTMLElements(),
}
}
type PublishStats struct {
HTMLElements HTMLElements `json:"htmlElements"`
}
// Publisher publishes a result file.
type Publisher interface {
Publish(d Descriptor) error
PublishStats() PublishStats
}
// XML transformer := transform.New(urlreplacers.NewAbsURLInXMLTransformer(path))
func (p DestinationPublisher) createTransformerChain(f Descriptor) transform.Chain {
transformers := transform.NewEmpty()
isHTML := f.OutputFormat.IsHTML
if f.AbsURLPath != "" {
if isHTML {
transformers = append(transformers, urlreplacers.NewAbsURLTransformer(f.AbsURLPath))
} else {
// Assume XML.
transformers = append(transformers, urlreplacers.NewAbsURLInXMLTransformer(f.AbsURLPath))
}
}
if isHTML {
if f.LiveReloadBaseURL != nil {
transformers = append(transformers, livereloadinject.New(f.LiveReloadBaseURL))
}
// This is only injected on the home page.
if f.AddHugoGeneratorTag {
transformers = append(transformers, metainject.HugoGenerator)
}
}
if p.min.MinifyOutput {
minifyTransformer := p.min.Transformer(f.OutputFormat.MediaType)
if minifyTransformer != nil {
transformers = append(transformers, minifyTransformer)
}
}
return transformers
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/compare/compare_strings.go | compare/compare_strings.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 compare
import (
"strings"
"unicode"
"unicode/utf8"
)
// Strings returns an integer comparing two strings lexicographically.
func Strings(s, t string) int {
c := compareFold(s, t)
if c == 0 {
// "B" and "b" would be the same so we need a tiebreaker.
return strings.Compare(s, t)
}
return c
}
// This function is derived from strings.EqualFold in Go's stdlib.
// https://github.com/golang/go/blob/ad4a58e31501bce5de2aad90a620eaecdc1eecb8/src/strings/strings.go#L893
func compareFold(s, t string) int {
for s != "" && t != "" {
var sr, tr rune
if s[0] < utf8.RuneSelf {
sr, s = rune(s[0]), s[1:]
} else {
r, size := utf8.DecodeRuneInString(s)
sr, s = r, s[size:]
}
if t[0] < utf8.RuneSelf {
tr, t = rune(t[0]), t[1:]
} else {
r, size := utf8.DecodeRuneInString(t)
tr, t = r, t[size:]
}
if tr == sr {
continue
}
c := 1
if tr < sr {
tr, sr = sr, tr
c = -c
}
// ASCII only.
if tr < utf8.RuneSelf {
if sr >= 'A' && sr <= 'Z' {
if tr <= 'Z' {
// Same case.
return -c
}
diff := tr - (sr + 'a' - 'A')
if diff == 0 {
continue
}
if diff < 0 {
return c
}
if diff > 0 {
return -c
}
}
}
// Unicode.
r := unicode.SimpleFold(sr)
for r != sr && r < tr {
r = unicode.SimpleFold(r)
}
if r == tr {
continue
}
return -c
}
if s == "" && t == "" {
return 0
}
if s == "" {
return -1
}
return 1
}
// LessStrings returns whether s is less than t lexicographically.
func LessStrings(s, t string) bool {
return Strings(s, t) < 0
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/compare/compare_test.go | compare/compare_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 compare
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/compare/compare.go | compare/compare.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 compare
// Eqer can be used to determine if this value is equal to the other.
// The semantics of equals is that the two value are interchangeable
// in the Hugo templates.
type Eqer interface {
// Eq returns whether this value is equal to the other.
// This is for internal use.
Eq(other any) bool
}
// ProbablyEqer is an equal check that may return false positives, but never
// a false negative.
type ProbablyEqer interface {
// For internal use.
ProbablyEq(other any) bool
}
// Comparer can be used to compare two values.
// This will be used when using the le, ge etc. operators in the templates.
// Compare returns -1 if the given version is less than, 0 if equal and 1 if greater than
// the running version.
type Comparer interface {
Compare(other any) int
}
// Eq returns whether v1 is equal to v2.
// It will use the Eqer interface if implemented, which
// defines equals when two value are interchangeable
// in the Hugo templates.
func Eq(v1, v2 any) bool {
if v1 == nil || v2 == nil {
return v1 == v2
}
if eqer, ok := v1.(Eqer); ok {
return eqer.Eq(v2)
}
return v1 == v2
}
// ProbablyEq returns whether v1 is probably equal to v2.
func ProbablyEq(v1, v2 any) bool {
if Eq(v1, v2) {
return true
}
if peqer, ok := v1.(ProbablyEqer); ok {
return peqer.ProbablyEq(v2)
}
return false
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/compare/compare_strings_test.go | compare/compare_strings_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 compare
import (
"sort"
"strings"
"testing"
qt "github.com/frankban/quicktest"
)
func TestCompare(t *testing.T) {
c := qt.New(t)
for _, test := range []struct {
a string
b string
}{
{"a", "a"},
{"A", "a"},
{"Ab", "Ac"},
{"az", "Za"},
{"C", "D"},
{"B", "a"},
{"C", ""},
{"", ""},
{"αβδC", "ΑΒΔD"},
{"αβδC", "ΑΒΔ"},
{"αβδ", "ΑΒΔD"},
{"αβδ", "ΑΒΔ"},
{"β", "δ"},
{"好", strings.ToLower("好")},
} {
expect := strings.Compare(strings.ToLower(test.a), strings.ToLower(test.b))
got := compareFold(test.a, test.b)
c.Assert(got, qt.Equals, expect)
}
}
func TestLexicographicSort(t *testing.T) {
c := qt.New(t)
s := []string{"b", "Bz", "ba", "A", "Ba", "ba"}
sort.Slice(s, func(i, j int) bool {
return LessStrings(s[i], s[j])
})
c.Assert(s, qt.DeepEquals, []string{"A", "b", "Ba", "ba", "ba", "Bz"})
}
// // Note that this cannot use b.Loop() because of golang/go#27217.
func BenchmarkStringSort(b *testing.B) {
prototype := []string{"b", "Bz", "zz", "ba", "αβδ αβδ αβδ", "A", "Ba", "ba", "nnnnasdfnnn", "AAgæåz", "αβδC"}
b.Run("LessStrings", func(b *testing.B) {
ss := make([][]string, b.N)
for i := 0; i < b.N; i++ {
ss[i] = make([]string, len(prototype))
copy(ss[i], prototype)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
sss := ss[i]
sort.Slice(sss, func(i, j int) bool {
return LessStrings(sss[i], sss[j])
})
}
})
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/metrics/metrics.go | metrics/metrics.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 metrics provides simple metrics tracking features.
package metrics
import (
"fmt"
"io"
"math"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/gohugoio/hugo/common/hashing"
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/compare"
)
// The Provider interface defines an interface for measuring metrics.
type Provider interface {
// MeasureSince adds a measurement for key to the metric store.
// Used with defer and time.Now().
MeasureSince(key string, start time.Time)
// WriteMetrics will write a summary of the metrics to w.
WriteMetrics(w io.Writer)
// TrackValue tracks the value for diff calculations etc.
TrackValue(key string, value any, cached bool)
// Reset clears the metric store.
Reset()
}
type diff struct {
baseline any
count int
simSum int
}
func (d *diff) add(v any) *diff {
if types.IsNil(d.baseline) {
d.baseline = v
d.count = 1
d.simSum = 100 // If we get only one it is very cache friendly.
return d
}
adder := howSimilar(v, d.baseline)
d.simSum += adder
d.count++
return d
}
// Store provides storage for a set of metrics.
type Store struct {
calculateHints bool
metrics map[string][]time.Duration
mu sync.Mutex
diffs map[string]*diff
diffmu sync.Mutex
cached map[string]int
cachedmu sync.Mutex
}
// NewProvider returns a new instance of a metric store.
func NewProvider(calculateHints bool) Provider {
return &Store{
calculateHints: calculateHints,
metrics: make(map[string][]time.Duration),
diffs: make(map[string]*diff),
cached: make(map[string]int),
}
}
// Reset clears the metrics store.
func (s *Store) Reset() {
s.mu.Lock()
s.metrics = make(map[string][]time.Duration)
s.mu.Unlock()
s.diffmu.Lock()
s.diffs = make(map[string]*diff)
s.diffmu.Unlock()
s.cachedmu.Lock()
s.cached = make(map[string]int)
s.cachedmu.Unlock()
}
// TrackValue tracks the value for diff calculations etc.
func (s *Store) TrackValue(key string, value any, cached bool) {
if !s.calculateHints {
return
}
s.diffmu.Lock()
d, found := s.diffs[key]
if !found {
d = &diff{}
s.diffs[key] = d
}
d.add(value)
s.diffmu.Unlock()
if cached {
s.cachedmu.Lock()
s.cached[key] = s.cached[key] + 1
s.cachedmu.Unlock()
}
}
// MeasureSince adds a measurement for key to the metric store.
func (s *Store) MeasureSince(key string, start time.Time) {
s.mu.Lock()
s.metrics[key] = append(s.metrics[key], time.Since(start))
s.mu.Unlock()
}
// WriteMetrics writes a summary of the metrics to w.
func (s *Store) WriteMetrics(w io.Writer) {
s.mu.Lock()
results := make([]result, len(s.metrics))
var i int
for k, v := range s.metrics {
var sum time.Duration
var max time.Duration
diff, found := s.diffs[k]
cacheFactor := 0
if found {
cacheFactor = int(math.Floor(float64(diff.simSum) / float64(diff.count)))
}
for _, d := range v {
sum += d
if d > max {
max = d
}
}
avg := time.Duration(int(sum) / len(v))
cacheCount := s.cached[k]
results[i] = result{key: k, count: len(v), max: max, sum: sum, avg: avg, cacheCount: cacheCount, cacheFactor: cacheFactor}
i++
}
s.mu.Unlock()
if s.calculateHints {
fmt.Fprintf(w, " %15s %12s %12s %9s %7s %6s %5s %s\n", "cumulative", "average", "maximum", "cache", "percent", "cached", "total", "")
fmt.Fprintf(w, " %15s %12s %12s %9s %7s %6s %5s %s\n", "duration", "duration", "duration", "potential", "cached", "count", "count", "template")
fmt.Fprintf(w, " %15s %12s %12s %9s %7s %6s %5s %s\n", "----------", "--------", "--------", "---------", "-------", "------", "-----", "--------")
} else {
fmt.Fprintf(w, " %15s %12s %12s %5s %s\n", "cumulative", "average", "maximum", "", "")
fmt.Fprintf(w, " %15s %12s %12s %5s %s\n", "duration", "duration", "duration", "count", "template")
fmt.Fprintf(w, " %15s %12s %12s %5s %s\n", "----------", "--------", "--------", "-----", "--------")
}
sort.Sort(bySum(results))
for _, v := range results {
if s.calculateHints {
fmt.Fprintf(w, " %15s %12s %12s %9d %7.f %6d %5d %s\n", v.sum, v.avg, v.max, v.cacheFactor, float64(v.cacheCount)/float64(v.count)*100, v.cacheCount, v.count, v.key)
} else {
fmt.Fprintf(w, " %15s %12s %12s %5d %s\n", v.sum, v.avg, v.max, v.count, v.key)
}
}
}
// A result represents the calculated results for a given metric.
type result struct {
key string
count int
cacheCount int
cacheFactor int
sum time.Duration
max time.Duration
avg time.Duration
}
type bySum []result
func (b bySum) Len() int { return len(b) }
func (b bySum) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b bySum) Less(i, j int) bool { return b[i].sum > b[j].sum }
// howSimilar is a naive diff implementation that returns
// a number between 0-100 indicating how similar a and b are.
func howSimilar(a, b any) int {
t1, t2 := reflect.TypeOf(a), reflect.TypeOf(b)
if t1 != t2 {
return 0
}
if t1.Comparable() && t2.Comparable() {
if a == b {
return 100
}
}
as, ok1 := types.TypeToString(a)
bs, ok2 := types.TypeToString(b)
if ok1 && ok2 {
return howSimilarStrings(as, bs)
}
if ok1 != ok2 {
return 0
}
e1, ok1 := a.(compare.Eqer)
e2, ok2 := b.(compare.Eqer)
if ok1 && ok2 && e1.Eq(e2) {
return 100
}
pe1, pok1 := a.(compare.ProbablyEqer)
pe2, pok2 := b.(compare.ProbablyEqer)
if pok1 && pok2 && pe1.ProbablyEq(pe2) {
return 90
}
h1, h2 := hashing.HashString(a), hashing.HashString(b)
if h1 == h2 {
return 100
}
return 0
}
// howSimilar is a naive diff implementation that returns
// a number between 0-100 indicating how similar a and b are.
// 100 is when all words in a also exists in b.
func howSimilarStrings(a, b string) int {
if a == b {
return 100
}
// Give some weight to the word positions.
const partitionSize = 4
af, bf := strings.Fields(a), strings.Fields(b)
if len(bf) > len(af) {
af, bf = bf, af
}
m1 := make(map[string]bool)
for i, x := range bf {
partition := partition(i, partitionSize)
key := x + "/" + strconv.Itoa(partition)
m1[key] = true
}
common := 0
for i, x := range af {
partition := partition(i, partitionSize)
key := x + "/" + strconv.Itoa(partition)
if m1[key] {
common++
}
}
if common == 0 && common == len(af) {
return 100
}
return int(math.Floor((float64(common) / float64(len(af)) * 100)))
}
func partition(d, scale int) int {
return int(math.Floor((float64(d) / float64(scale)))) * scale
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/metrics/metrics_test.go | metrics/metrics_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 metrics
import (
"html/template"
"strings"
"testing"
"github.com/gohugoio/hugo/resources/page"
qt "github.com/frankban/quicktest"
)
func TestSimilarPercentage(t *testing.T) {
c := qt.New(t)
sentence := "this is some words about nothing, Hugo!"
words := strings.Fields(sentence)
for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
words[i], words[j] = words[j], words[i]
}
sentenceReversed := strings.Join(words, " ")
c.Assert(howSimilar("Hugo Rules", "Hugo Rules"), qt.Equals, 100)
c.Assert(howSimilar("Hugo Rules", "Hugo Rocks"), qt.Equals, 50)
c.Assert(howSimilar("The Hugo Rules", "The Hugo Rocks"), qt.Equals, 66)
c.Assert(howSimilar("The Hugo Rules", "The Hugo"), qt.Equals, 66)
c.Assert(howSimilar("The Hugo", "The Hugo Rules"), qt.Equals, 66)
c.Assert(howSimilar("Totally different", "Not Same"), qt.Equals, 0)
c.Assert(howSimilar(sentence, sentenceReversed), qt.Equals, 14)
c.Assert(howSimilar(template.HTML("Hugo Rules"), template.HTML("Hugo Rules")), qt.Equals, 100)
c.Assert(howSimilar(map[string]any{"a": 32, "b": 33}, map[string]any{"a": 32, "b": 33}), qt.Equals, 100)
c.Assert(howSimilar(map[string]any{"a": 32, "b": 33}, map[string]any{"a": 32, "b": 34}), qt.Equals, 0)
c.Assert(howSimilar("\n", ""), qt.Equals, 100)
}
type testStruct struct {
Name string
}
func TestSimilarPercentageNonString(t *testing.T) {
c := qt.New(t)
c.Assert(howSimilar(page.NopPage, page.NopPage), qt.Equals, 100)
c.Assert(howSimilar(page.Pages{}, page.Pages{}), qt.Equals, 90)
c.Assert(howSimilar(testStruct{Name: "A"}, testStruct{Name: "B"}), qt.Equals, 0)
c.Assert(howSimilar(testStruct{Name: "A"}, testStruct{Name: "A"}), qt.Equals, 100)
}
func BenchmarkHowSimilar(b *testing.B) {
s1 := "Hugo is cool and " + strings.Repeat("fun ", 10) + "!"
s2 := "Hugo is cool and " + strings.Repeat("cool ", 10) + "!"
for b.Loop() {
howSimilar(s1, s2)
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/source/fileInfo.go | source/fileInfo.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 source
import (
"path/filepath"
"sync"
"github.com/bep/gitmap"
"github.com/bep/logg"
"github.com/gohugoio/hugo/common/hashing"
"github.com/gohugoio/hugo/common/hugo"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/hugofs/files"
"github.com/gohugoio/hugo/common/hugio"
"github.com/gohugoio/hugo/hugofs"
)
// File describes a source file.
type File struct {
fim hugofs.FileMetaInfo
uniqueID string
lazyInit sync.Once
}
// IsContentAdapter returns whether the file represents a content adapter.
// This means that there may be more than one Page associated with this file.
func (fi *File) IsContentAdapter() bool {
return fi.fim.Meta().PathInfo.IsContentData()
}
// Filename returns a file's absolute path and filename on disk.
func (fi *File) Filename() string { return fi.fim.Meta().Filename }
// Path gets the relative path including file name and extension. The directory
// is relative to the content root.
func (fi *File) Path() string { return filepath.Join(fi.p().Dir()[1:], fi.p().Name()) }
// Dir gets the name of the directory that contains this file. The directory is
// relative to the content root.
func (fi *File) Dir() string {
return fi.pathToDir(fi.p().Dir())
}
// Ext returns a file's extension without the leading period (e.g. "md").
func (fi *File) Ext() string { return fi.p().Ext() }
// Lang returns a file's language (e.g. "sv").
// Deprecated: Use .Page.Language.Lang instead.
func (fi *File) Lang() string {
// From Hugo 0.149.0 a file may have multiple languages.
hugo.DeprecateLevelMin(".File.Lang", "Use e.g. Page.Site.Language.Lang", "v0.149.0", logg.LevelError)
return ""
}
// LogicalName returns a file's name and extension (e.g. "page.sv.md").
func (fi *File) LogicalName() string {
return fi.p().Name()
}
// BaseFileName returns a file's name without extension (e.g. "page.sv").
func (fi *File) BaseFileName() string {
return fi.p().NameNoExt()
}
// TranslationBaseName returns a file's translation base name without the
// language segment (e.g. "page").
func (fi *File) TranslationBaseName() string { return fi.p().NameNoIdentifier() }
// ContentBaseName is a either TranslationBaseName or name of containing folder
// if file is a bundle.
func (fi *File) ContentBaseName() string {
return fi.p().BaseNameNoIdentifier()
}
// Section returns a file's section.
func (fi *File) Section() string {
return fi.p().Section()
}
// UniqueID returns a file's unique, MD5 hash identifier.
func (fi *File) UniqueID() string {
fi.init()
return fi.uniqueID
}
// FileInfo returns a file's underlying os.FileInfo.
func (fi *File) FileInfo() hugofs.FileMetaInfo { return fi.fim }
func (fi *File) String() string { return fi.BaseFileName() }
// Open implements ReadableFile.
func (fi *File) Open() (hugio.ReadSeekCloser, error) {
f, err := fi.fim.Meta().Open()
return f, err
}
func (fi *File) IsZero() bool {
return fi == nil
}
// We create a lot of these FileInfo objects, but there are parts of it used only
// in some cases that is slightly expensive to construct.
func (fi *File) init() {
fi.lazyInit.Do(func() {
fi.uniqueID = hashing.MD5FromStringHexEncoded(filepath.ToSlash(fi.Path()))
})
}
func (fi *File) pathToDir(s string) string {
if s == "" {
return s
}
return filepath.FromSlash(s[1:] + "/")
}
func (fi *File) p() *paths.Path {
return fi.fim.Meta().PathInfo.Unnormalized()
}
var contentPathParser = &paths.PathParser{
IsContentExt: func(ext string) bool {
return true
},
}
// Used in tests.
func NewContentFileInfoFrom(path, filename string) *File {
meta := &hugofs.FileMeta{
Filename: filename,
PathInfo: contentPathParser.Parse(files.ComponentFolderContent, filepath.ToSlash(path)),
}
return NewFileInfo(hugofs.NewFileMetaInfo(nil, meta))
}
func NewFileInfo(fi hugofs.FileMetaInfo) *File {
return &File{
fim: fi,
}
}
// GitInfo provides information about a version controlled source file.
type GitInfo = gitmap.GitInfo
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/source/content_directory_test.go | source/content_directory_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 source_test
import (
"fmt"
"path/filepath"
"testing"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/config/testconfig"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/source"
"github.com/spf13/afero"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugofs"
)
func TestIgnoreDotFilesAndDirectories(t *testing.T) {
c := qt.New(t)
tests := []struct {
path string
ignore bool
ignoreFilesRegexpes any
}{
{".foobar/", true, nil},
{"foobar/.barfoo/", true, nil},
{"barfoo.md", false, nil},
{"foobar/barfoo.md", false, nil},
{"foobar/.barfoo.md", true, nil},
{".barfoo.md", true, nil},
{".md", true, nil},
{"foobar/barfoo.md~", true, nil},
{".foobar/barfoo.md~", true, nil},
{"foobar~/barfoo.md", false, nil},
{"foobar/bar~foo.md", false, nil},
{"foobar/foo.md", true, []string{"\\.md$", "\\.boo$"}},
{"foobar/foo.html", false, []string{"\\.md$", "\\.boo$"}},
{"foobar/foo.md", true, []string{"foo.md$"}},
{"foobar/foo.md", true, []string{".*", "\\.md$", "\\.boo$"}},
{"foobar/.#content.md", true, []string{"/\\.#"}},
{".#foobar.md", true, []string{"^\\.#"}},
}
for i, test := range tests {
c.Run(fmt.Sprintf("[%d] %s", i, test.path), func(c *qt.C) {
c.Parallel()
v := config.New()
v.Set("ignoreFiles", test.ignoreFilesRegexpes)
v.Set("publishDir", "public")
afs := afero.NewMemMapFs()
conf := testconfig.GetTestConfig(afs, v)
fs := hugofs.NewFromOld(afs, v)
ps, err := helpers.NewPathSpec(fs, conf, nil, nil)
c.Assert(err, qt.IsNil)
s := source.NewSourceSpec(ps, nil, fs.Source)
if ignored := s.IgnoreFile(filepath.FromSlash(test.path)); test.ignore != ignored {
t.Errorf("[%d] File not ignored", i)
}
})
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/source/sourceSpec.go | source/sourceSpec.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 source contains the types and functions related to source files.
package source
import (
"path/filepath"
"runtime"
"github.com/spf13/afero"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs/hglob"
)
// SourceSpec abstracts language-specific file creation.
// TODO(bep) rename to Spec
type SourceSpec struct {
*helpers.PathSpec
SourceFs afero.Fs
shouldInclude func(filename string) bool
}
// NewSourceSpec initializes SourceSpec using languages the given filesystem and PathSpec.
func NewSourceSpec(ps *helpers.PathSpec, inclusionFilter *hglob.FilenameFilter, fs afero.Fs) *SourceSpec {
shouldInclude := func(filename string) bool {
if !inclusionFilter.Match(filename, false) {
return false
}
if ps.Cfg.IgnoreFile(filename) {
return false
}
return true
}
return &SourceSpec{shouldInclude: shouldInclude, PathSpec: ps, SourceFs: fs}
}
// IgnoreFile returns whether a given file should be ignored.
func (s *SourceSpec) IgnoreFile(filename string) bool {
if filename == "" {
if _, ok := s.SourceFs.(*afero.OsFs); ok {
return true
}
return false
}
base := filepath.Base(filename)
if len(base) > 0 {
first := base[0]
last := base[len(base)-1]
if first == '.' ||
first == '#' ||
last == '~' {
return true
}
}
if !s.shouldInclude(filename) {
return true
}
if runtime.GOOS == "windows" {
// Also check the forward slash variant if different.
unixFilename := filepath.ToSlash(filename)
if unixFilename != filename {
if !s.shouldInclude(unixFilename) {
return true
}
}
}
return false
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/common/docs.go | common/docs.go | // Package common provides common helper functionality for Hugo.
package common
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/common/htime/time.go | common/htime/time.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 htime
import (
"log"
"strings"
"time"
"github.com/bep/clocks"
"github.com/spf13/cast"
"github.com/gohugoio/locales"
)
var (
longDayNames = []string{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
}
shortDayNames = []string{
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
}
shortMonthNames = []string{
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
}
longMonthNames = []string{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
}
Clock = clocks.System()
)
func NewTimeFormatter(ltr locales.Translator) TimeFormatter {
if ltr == nil {
panic("must provide a locales.Translator")
}
return TimeFormatter{
ltr: ltr,
}
}
// TimeFormatter is locale aware.
type TimeFormatter struct {
ltr locales.Translator
}
func (f TimeFormatter) Format(t time.Time, layout string) string {
if layout == "" {
return ""
}
if layout[0] == ':' {
// It may be one of Hugo's custom layouts.
switch strings.ToLower(layout[1:]) {
case "date_full":
return f.ltr.FmtDateFull(t)
case "date_long":
return f.ltr.FmtDateLong(t)
case "date_medium":
return f.ltr.FmtDateMedium(t)
case "date_short":
return f.ltr.FmtDateShort(t)
case "time_full":
return f.ltr.FmtTimeFull(t)
case "time_long":
return f.ltr.FmtTimeLong(t)
case "time_medium":
return f.ltr.FmtTimeMedium(t)
case "time_short":
return f.ltr.FmtTimeShort(t)
}
}
s := t.Format(layout)
monthIdx := t.Month() - 1 // Month() starts at 1.
dayIdx := t.Weekday()
if strings.Contains(layout, "January") {
s = strings.ReplaceAll(s, longMonthNames[monthIdx], f.ltr.MonthWide(t.Month()))
} else if strings.Contains(layout, "Jan") {
s = strings.ReplaceAll(s, shortMonthNames[monthIdx], f.ltr.MonthAbbreviated(t.Month()))
}
if strings.Contains(layout, "Monday") {
s = strings.ReplaceAll(s, longDayNames[dayIdx], f.ltr.WeekdayWide(t.Weekday()))
} else if strings.Contains(layout, "Mon") {
s = strings.ReplaceAll(s, shortDayNames[dayIdx], f.ltr.WeekdayAbbreviated(t.Weekday()))
}
return s
}
func ToTimeInDefaultLocationE(i any, location *time.Location) (tim time.Time, err error) {
switch vv := i.(type) {
case AsTimeProvider:
return vv.AsTime(location), nil
// issue #8895
// datetimes parsed by `go-toml` have empty zone name
// convert back them into string and use `cast`
// TODO(bep) add tests, make sure we really need this.
case time.Time:
i = vv.Format(time.RFC3339)
}
return cast.ToTimeInDefaultLocationE(i, location)
}
// Now returns time.Now() or time value based on the `clock` flag.
// Use this function to fake time inside hugo.
func Now() time.Time {
return Clock.Now()
}
func Since(t time.Time) time.Duration {
return Clock.Since(t)
}
// AsTimeProvider is implemented by go-toml's LocalDate and LocalDateTime.
type AsTimeProvider interface {
AsTime(zone *time.Location) time.Time
}
// StopWatch is a simple helper to measure time during development.
func StopWatch(name string) func() {
start := time.Now()
return func() {
log.Printf("StopWatch %q took %s", name, time.Since(start))
}
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/common/htime/time_test.go | common/htime/time_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 htime
import (
"testing"
"time"
qt "github.com/frankban/quicktest"
translators "github.com/gohugoio/localescompressed"
)
func TestTimeFormatter(t *testing.T) {
c := qt.New(t)
june06, _ := time.Parse("2006-Jan-02", "2018-Jun-06")
june06 = june06.Add(7777 * time.Second)
jan06, _ := time.Parse("2006-Jan-02", "2018-Jan-06")
jan06 = jan06.Add(32 * time.Second)
mondayNovemberFirst, _ := time.Parse("2006-Jan-02", "2021-11-01")
mondayNovemberFirst = mondayNovemberFirst.Add(33 * time.Second)
c.Run("Norsk nynorsk", func(c *qt.C) {
f := NewTimeFormatter(translators.GetTranslator("nn"))
c.Assert(f.Format(june06, "Monday Jan 2 2006"), qt.Equals, "onsdag juni 6 2018")
c.Assert(f.Format(june06, "Mon January 2 2006"), qt.Equals, "on. juni 6 2018")
c.Assert(f.Format(june06, "Mon Mon"), qt.Equals, "on. on.")
})
c.Run("Custom layouts Norsk nynorsk", func(c *qt.C) {
f := NewTimeFormatter(translators.GetTranslator("nn"))
c.Assert(f.Format(june06, ":date_full"), qt.Equals, "onsdag 6. juni 2018")
c.Assert(f.Format(june06, ":date_long"), qt.Equals, "6. juni 2018")
c.Assert(f.Format(june06, ":date_medium"), qt.Equals, "6. juni 2018")
c.Assert(f.Format(june06, ":date_short"), qt.Equals, "06.06.2018")
c.Assert(f.Format(june06, ":time_full"), qt.Equals, "kl. 02:09:37 UTC")
c.Assert(f.Format(june06, ":time_long"), qt.Equals, "02:09:37 UTC")
c.Assert(f.Format(june06, ":time_medium"), qt.Equals, "02:09:37")
c.Assert(f.Format(june06, ":time_short"), qt.Equals, "02:09")
})
c.Run("Custom layouts English", func(c *qt.C) {
f := NewTimeFormatter(translators.GetTranslator("en"))
c.Assert(f.Format(june06, ":date_full"), qt.Equals, "Wednesday, June 6, 2018")
c.Assert(f.Format(june06, ":date_long"), qt.Equals, "June 6, 2018")
c.Assert(f.Format(june06, ":date_medium"), qt.Equals, "Jun 6, 2018")
c.Assert(f.Format(june06, ":date_short"), qt.Equals, "6/6/18")
c.Assert(f.Format(june06, ":time_full"), qt.Equals, "2:09:37 am UTC")
c.Assert(f.Format(june06, ":time_long"), qt.Equals, "2:09:37 am UTC")
c.Assert(f.Format(june06, ":time_medium"), qt.Equals, "2:09:37 am")
c.Assert(f.Format(june06, ":time_short"), qt.Equals, "2:09 am")
})
c.Run("English", func(c *qt.C) {
f := NewTimeFormatter(translators.GetTranslator("en"))
c.Assert(f.Format(june06, "Monday Jan 2 2006"), qt.Equals, "Wednesday Jun 6 2018")
c.Assert(f.Format(june06, "Mon January 2 2006"), qt.Equals, "Wed June 6 2018")
c.Assert(f.Format(june06, "Mon Mon"), qt.Equals, "Wed Wed")
})
c.Run("Weekdays German", func(c *qt.C) {
tr := translators.GetTranslator("de")
f := NewTimeFormatter(tr)
// Issue #9107
for i, weekDayWideGerman := range []string{"Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"} {
date := mondayNovemberFirst.Add(time.Duration(i*24) * time.Hour)
c.Assert(tr.WeekdayWide(date.Weekday()), qt.Equals, weekDayWideGerman)
c.Assert(f.Format(date, "Monday"), qt.Equals, weekDayWideGerman)
}
for i, weekDayAbbreviatedGerman := range []string{"Mo.", "Di.", "Mi.", "Do.", "Fr.", "Sa.", "So."} {
date := mondayNovemberFirst.Add(time.Duration(i*24) * time.Hour)
c.Assert(tr.WeekdayAbbreviated(date.Weekday()), qt.Equals, weekDayAbbreviatedGerman)
c.Assert(f.Format(date, "Mon"), qt.Equals, weekDayAbbreviatedGerman)
}
})
c.Run("Months German", func(c *qt.C) {
tr := translators.GetTranslator("de")
f := NewTimeFormatter(tr)
// Issue #9107
for i, monthWideNorway := range []string{"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli"} {
date := jan06.Add(time.Duration(i*24*31) * time.Hour)
c.Assert(tr.MonthWide(date.Month()), qt.Equals, monthWideNorway)
c.Assert(f.Format(date, "January"), qt.Equals, monthWideNorway)
}
})
}
func BenchmarkTimeFormatter(b *testing.B) {
june06, _ := time.Parse("2006-Jan-02", "2018-Jun-06")
b.Run("Native", func(b *testing.B) {
for b.Loop() {
got := june06.Format("Monday Jan 2 2006")
if got != "Wednesday Jun 6 2018" {
b.Fatalf("invalid format, got %q", got)
}
}
})
b.Run("Localized", func(b *testing.B) {
f := NewTimeFormatter(translators.GetTranslator("nn"))
b.ResetTimer()
for b.Loop() {
got := f.Format(june06, "Monday Jan 2 2006")
if got != "onsdag juni 6 2018" {
b.Fatalf("invalid format, got %q", got)
}
}
})
b.Run("Localized Custom", func(b *testing.B) {
f := NewTimeFormatter(translators.GetTranslator("nn"))
b.ResetTimer()
for b.Loop() {
got := f.Format(june06, ":date_medium")
if got != "6. juni 2018" {
b.Fatalf("invalid format, got %q", got)
}
}
})
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.