Compare commits

...

37 Commits

Author SHA1 Message Date
hugoreleaser dd0d3fdbbe releaser: Bump versions for release of 0.90.0
[ci skip]
2021-12-08 09:33:46 +00:00
hugoreleaser b921752331 releaser: Add release notes for 0.90.0
[ci skip]
2021-12-08 09:33:46 +00:00
Bjørn Erik Pedersen 0fa40ce58f releaser: Simplify the release process
Make it into a one step even for major releases.
2021-12-08 09:38:15 +01:00
Bjørn Erik Pedersen bf537f1c6d releaser: Remove unused code 2021-12-08 09:02:45 +01:00
Bjørn Erik Pedersen e86b331138 docs: Regenerate docs helper 2021-12-08 08:56:16 +01:00
Bjørn Erik Pedersen 6c841a691e Merge commit '8d9511a08f14260cbfb73119e4afae50e5a9966d' 2021-12-08 08:54:25 +01:00
Bjørn Erik Pedersen 8d9511a08f Squashed 'docs/' changes from 39a7fac34..316cec249
316cec249 Update future events template example (#1595)
3bde7d489 Install mage outside module (#1592)
762e27eff Clarify ignoreFiles regex matching
4d0032051 Add id attribute to h2 elements (#1590)
8262b077c Improve inline resource examples (#1587)
2eae7c7ec fix disqus example name (#1588)
a772f4804 Added install instructions for openSUSE Tumbleweed (#1459)
7ad1c301b Remove screen capture from Hosting on GitHub page (#1586)
a58541f49 add more details on about gh-pages and baseURL on hosting-on-github.md (#1346)
3bd0b46dc Update configuration page (#1585)
4cf1f013e Update OS functions
2c45a95c2 Remove getting-started/code-toggle/
40fdff598 Describe artificial language private use subtags (#1577)
91011d210 Remove google_news from list of internal templates (#1576)
36c7879e4 Update the .Unix function
731063488 Remove a showcase
818c371a0 Update index.md
3136d39d9 netlify: Hugo 0.89.4
092bc9278 Merge branch 'tempv0.89.4'
18e01f105 releaser: Add release notes to /docs for release of 0.89.4
79135281f Correct and sort list of target image formats (#1574)
af4170c7e netlify: Hugo 0.89.3
7f5444251 Merge branch 'tempv0.89.3'
a32e4a6c2 releaser: Add release notes to /docs for release of 0.89.3
6dd3dc3f9 Update configuration.md
5fbe741d7 Update index.md (#1570)
37a69496f netlify: Bump to Hugo 0.89.2
3b293f1f4 Merge branch 'tempv0.89.2'
64c934e7a releaser: Add release notes to /docs for release of 0.89.2
919c51c7d Update index.md
13dd463b1 netlify: Hugo 0.89.1
d8cda1474 releaser: Add release notes to /docs for release of 0.89.1
a2adf7742 releaser: Add release notes to /docs for release of 0.89.1
c3088c4fc Add code toggle to menus page (#1568)
2d0f38978 Remove blank lines from code-toggle output (#1564)
7cf058bfd Add localization examples (#1563)
cf8627c2e Fixing typos, fixing incomplete link (#1561)
c78cc014b Document the removePathAccents setting
70beddaf4 Make corrections to 0.89.0 release notes (#1560)
1917195f0 Update index.md
7fb8e070c Run hugo --gc
1772d45fb Release 0.89.0
d9006179b Merge branch 'tempv0.89.0'
8db86b61e releaser: Add release notes to /docs for release of 0.89.0
abf268571 docs: Regen CLI docs
fbbdb0ab1 Update the timeout default
9cbd1c15a Fix description of lang.FormatNumberCustom
6043b54cc Remove "render" keyword from Host on Render page
f8ea8e84f Clarify description of front matter url (#1557)
91a0c9954 Update Twitter shortcode oEmbed endpoint
79a7405b8 Merge commit 'aa5ac36a3eb68b86c803caec703869efefc8447e'
57667bae6 hugofs: Add includeFiles and excludeFiles to mount configuration
0c9ee0a04 Allow multiple plugins in the PostCSS options map
155799e6b docs: Create path.Clean documentation

git-subtree-dir: docs
git-subtree-split: 316cec2494
2021-12-08 08:42:31 +01:00
Bjørn Erik Pedersen e71d715b9b Add custom font support to images.Text
Fixes #9253
2021-12-07 16:53:02 +01:00
Bjørn Erik Pedersen e61cdf335f images: Fix cache busting of image text filter
See #9238
2021-12-07 16:53:02 +01:00
dependabot[bot] 6c3bc5ebad build(deps): bump github.com/getkin/kin-openapi from 0.80.0 to 0.85.0
Bumps [github.com/getkin/kin-openapi](https://github.com/getkin/kin-openapi) from 0.80.0 to 0.85.0.
- [Release notes](https://github.com/getkin/kin-openapi/releases)
- [Commits](https://github.com/getkin/kin-openapi/compare/v0.80.0...v0.85.0)

---
updated-dependencies:
- dependency-name: github.com/getkin/kin-openapi
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-12-07 13:12:42 +01:00
Paul van Brouwershaven 283394a4fd images: Text filter that draws text with the given options (#9239)
Fixes #9238
2021-12-07 11:29:55 +01:00
Joe Mooring 5538507e90 tpl/transform: Optional options for highlight func
Closes #9249
Fixes gohugoio/hugoDocs#63
2021-12-07 11:26:56 +01:00
Bjørn Erik Pedersen b4f27ef8e7 deps: Upgrade github.com/evanw/esbuild v0.13.12 => v0.14.2 (note)
Note: ESBuild v0.14.0 contains backwards-incompatible changes, see https://github.com/evanw/esbuild/releases/tag/v0.14.0

Fixes #9244
2021-12-04 16:28:50 +01:00
Bjørn Erik Pedersen 3473e31eb1 releaser: Add "note" to Note regexp 2021-12-04 16:27:56 +01:00
dependabot[bot] fa0da004a9 build(deps): bump github.com/mitchellh/mapstructure from 1.4.2 to 1.4.3
Bumps [github.com/mitchellh/mapstructure](https://github.com/mitchellh/mapstructure) from 1.4.2 to 1.4.3.
- [Release notes](https://github.com/mitchellh/mapstructure/releases)
- [Changelog](https://github.com/mitchellh/mapstructure/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mitchellh/mapstructure/compare/v1.4.2...v1.4.3)

---
updated-dependencies:
- dependency-name: github.com/mitchellh/mapstructure
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-12-03 18:16:50 +01:00
Bjørn Erik Pedersen 24a893cf83 releaser: Rework and simplify to use GitHub only for release notes 2021-12-03 17:02:20 +01:00
dependabot[bot] bf1564bd2c build(deps): bump google.golang.org/api from 0.51.0 to 0.61.0
Bumps [google.golang.org/api](https://github.com/googleapis/google-api-go-client) from 0.51.0 to 0.61.0.
- [Release notes](https://github.com/googleapis/google-api-go-client/releases)
- [Changelog](https://github.com/googleapis/google-api-go-client/blob/main/CHANGES.md)
- [Commits](https://github.com/googleapis/google-api-go-client/compare/v0.51.0...v0.61.0)

---
updated-dependencies:
- dependency-name: google.golang.org/api
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-12-03 17:01:37 +01:00
Paul van Brouwershaven cd44d409ba media: Add rss suffix for application/rss+xml
Closes #9233
2021-12-03 12:45:49 +01:00
Bjørn Erik Pedersen 9a326d5636 parser: Add a test case in format resolution
See #9233
2021-12-03 10:34:34 +01:00
Bjørn Erik Pedersen b10381fbe0 lazy: Reset error in Reset
To prevent sticky errors on server rebuilds.

Fixes #7043
Closes #9194
2021-12-02 18:06:19 +01:00
Paul van Brouwershaven 0eaaa8fee3 Implement XML data support
Example:

```
{{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }}
    {{ range .channel.item }}
        <strong>{{ .title | plainify | htmlUnescape }}</strong><br />
        <p>{{ .description | plainify | htmlUnescape }}</p>
        {{ $link := .link | plainify | htmlUnescape }}
        <a href="{{ $link }}">{{ $link }}</a><br />
        <hr>
    {{ end }}
{{ end }}
```

Closes #4470
2021-12-02 17:30:36 +01:00
Joe Mooring 58adbeef88 Validate private use language tags
Fixes #9119
2021-12-02 16:30:53 +01:00
Bjørn Erik Pedersen 93572e5318 resources: Add timeout to the HTTP request in Get
Workaround for https://github.com/golang/go/issues/49366
2021-12-02 16:11:14 +01:00
Bjørn Erik Pedersen 94f149b21e Add a remote retry for resources.Get 2021-12-02 16:11:14 +01:00
Paul van Brouwershaven 66753416b5 Make resources.Get use a file cache for remote resources
Closes #9228
2021-12-02 12:56:25 +01:00
Joe Mooring 133e4bfbee Remove empty href element from pagination template
Closes #9149
2021-12-02 09:14:30 +01:00
Joe Mooring f122771fb1 Check for empty deployment targets and matchers
Fixes #9220
2021-12-01 10:17:42 +01:00
Bjørn Erik Pedersen 08a863e1e8 resources: Adjust the remote Get cache so it does not get evicted on restarts
We fill improve this, soon.
2021-11-30 16:54:01 +01:00
Paul van Brouwershaven 8aa7257f65 Add remote support to resources.Get
Closes #5255
Supports #9044
2021-11-30 11:49:51 +01:00
Joe Mooring 75a823a36a Add deprecation warning to google_news template
Closes #9172
2021-11-21 11:25:17 +01:00
Bjørn Erik Pedersen 5e0947c5b5 helpers: Make UniqueStringsReuse allocation free
This should be faster for all of our use cases (small string slices), but more important, it makes UniqueStringsReuse allocation free.

```bash
name                                 old time/op    new time/op    delta
UniqueStrings/Safe-16                   776ns ± 0%     305ns ± 0%   -60.68%  (p=0.029 n=4+4)
UniqueStrings/Reuse_slice-16            621ns ± 3%     174ns ± 0%   -72.01%  (p=0.029 n=4+4)
UniqueStrings/Reuse_slice_sorted-16     319ns ± 4%     313ns ± 0%    -2.01%  (p=0.029 n=4+4)

name                                 old alloc/op   new alloc/op   delta
UniqueStrings/Safe-16                    224B ± 0%      128B ± 0%   -42.86%  (p=0.029 n=4+4)
UniqueStrings/Reuse_slice-16            96.0B ± 0%      0.0B       -100.00%  (p=0.029 n=4+4)
UniqueStrings/Reuse_slice_sorted-16     24.0B ± 0%     24.0B ± 0%      ~     (all equal)

name                                 old allocs/op  new allocs/op  delta
UniqueStrings/Safe-16                    7.00 ± 0%      1.00 ± 0%   -85.71%  (p=0.029 n=4+4)
UniqueStrings/Reuse_slice-16             6.00 ± 0%      0.00       -100.00%  (p=0.029 n=4+4)
UniqueStrings/Reuse_slice_sorted-16      1.00 ± 0%      1.00 ± 0%      ~     (all equal)
```
2021-11-17 10:44:03 +01:00
hugoreleaser 0b70b46aad releaser: Prepare repository for 0.90.0-DEV
[ci skip]
2021-11-17 09:05:38 +00:00
hugoreleaser ab01ba6e7e releaser: Add release notes to /docs for release of 0.89.4
[ci skip]
2021-11-17 08:24:08 +00:00
hugoreleaser cc08c09592 releaser: Bump versions for release of 0.89.4
[ci skip]
2021-11-17 08:24:08 +00:00
hugoreleaser f97da9eca9 releaser: Add release notes for 0.89.4
[ci skip]
2021-11-17 08:24:08 +00:00
Bjørn Erik Pedersen 2e70f61fb0 Fix content dir resolution when main project is a Hugo Module
Fixes #9177
2021-11-16 20:42:34 +01:00
hugoreleaser 1ed8069a3a releaser: Prepare repository for 0.90.0-DEV
[ci skip]
2021-11-15 12:56:41 +00:00
110 changed files with 1794 additions and 899 deletions
+1
View File
@@ -1,6 +1,7 @@
/hugo
docs/public*
/.idea
.vscode/*
hugo.exe
*.test
*.prof
+32 -4
View File
@@ -48,6 +48,9 @@ type Cache struct {
// 0 is effectively turning this cache off.
maxAge time.Duration
// Number of retries on create error.
retries int
// When set, we just remove this entire root directory on expiration.
pruneAllRootDir string
@@ -84,11 +87,12 @@ type ItemInfo struct {
}
// NewCache creates a new file cache with the given filesystem and max age.
func NewCache(fs afero.Fs, maxAge time.Duration, pruneAllRootDir string) *Cache {
func NewCache(fs afero.Fs, maxAge time.Duration, retries int, pruneAllRootDir string) *Cache {
return &Cache{
Fs: fs,
nlocker: &lockTracker{Locker: locker.NewLocker(), seen: make(map[string]struct{})},
maxAge: maxAge,
retries: retries,
pruneAllRootDir: pruneAllRootDir,
}
}
@@ -175,7 +179,19 @@ func (c *Cache) GetOrCreate(id string, create func() (io.ReadCloser, error)) (It
return info, r, nil
}
r, err := create()
var (
r io.ReadCloser
err error
)
for i := -1; i < c.retries; i++ {
r, err = create()
if err == nil || c.retries == 0 {
break
}
time.Sleep(1 * time.Second)
}
if err != nil {
return info, nil, err
}
@@ -206,7 +222,19 @@ func (c *Cache) GetOrCreateBytes(id string, create func() ([]byte, error)) (Item
return info, b, err
}
b, err := create()
var (
b []byte
err error
)
for i := -1; i < c.retries; i++ {
b, err = create()
if err == nil || c.retries == 0 {
break
}
time.Sleep(1 * time.Second)
}
if err != nil {
return info, nil, err
}
@@ -360,7 +388,7 @@ func NewCaches(p *helpers.PathSpec) (Caches, error) {
pruneAllRootDir = "pkg"
}
m[k] = NewCache(bfs, v.MaxAge, pruneAllRootDir)
m[k] = NewCache(bfs, v.MaxAge, v.retries, pruneAllRootDir)
}
return m, nil
+22 -6
View File
@@ -34,19 +34,21 @@ const (
cachesConfigKey = "caches"
resourcesGenDir = ":resourceDir/_gen"
cacheDirProject = ":cacheDir/:project"
)
var defaultCacheConfig = Config{
MaxAge: -1, // Never expire
Dir: ":cacheDir/:project",
Dir: cacheDirProject,
}
const (
cacheKeyGetJSON = "getjson"
cacheKeyGetCSV = "getcsv"
cacheKeyImages = "images"
cacheKeyAssets = "assets"
cacheKeyModules = "modules"
cacheKeyGetJSON = "getjson"
cacheKeyGetCSV = "getcsv"
cacheKeyImages = "images"
cacheKeyAssets = "assets"
cacheKeyModules = "modules"
cacheKeyGetResource = "getresource"
)
type Configs map[string]Config
@@ -70,6 +72,11 @@ var defaultCacheConfigs = Configs{
MaxAge: -1,
Dir: resourcesGenDir,
},
cacheKeyGetResource: Config{
MaxAge: -1, // Never expire
Dir: cacheDirProject,
retries: 3, // Retries on error getting the remote resource.
},
}
type Config struct {
@@ -84,6 +91,10 @@ type Config struct {
// Will resources/_gen will get its own composite filesystem that
// also checks any theme.
isResourceDir bool
// Number of retries when errors occurs when creating the element,
// only used for remote resources.
retries int
}
// GetJSONCache gets the file cache for getJSON.
@@ -111,6 +122,11 @@ func (f Caches) AssetsCache() *Cache {
return f[cacheKeyAssets]
}
// GetResourceCache gets the file cache for remote resources.
func (f Caches) GetResourceCache() *Cache {
return f[cacheKeyGetResource]
}
func DecodeConfig(fs afero.Fs, cfg config.Provider) (Configs, error) {
c := make(Configs)
valid := make(map[string]bool)
+11 -5
View File
@@ -50,7 +50,8 @@ maxAge = "11h"
dir = "/path/to/c2"
[caches.images]
dir = "/path/to/c3"
[caches.getResource]
dir = "/path/to/c4"
`
cfg, err := config.FromConfigString(configStr, "toml")
@@ -59,7 +60,7 @@ dir = "/path/to/c3"
decoded, err := DecodeConfig(fs, cfg)
c.Assert(err, qt.IsNil)
c.Assert(len(decoded), qt.Equals, 5)
c.Assert(len(decoded), qt.Equals, 6)
c2 := decoded["getcsv"]
c.Assert(c2.MaxAge.String(), qt.Equals, "11h0m0s")
@@ -68,6 +69,10 @@ dir = "/path/to/c3"
c3 := decoded["images"]
c.Assert(c3.MaxAge, qt.Equals, time.Duration(-1))
c.Assert(c3.Dir, qt.Equals, filepath.FromSlash("/path/to/c3/filecache/images"))
c4 := decoded["getresource"]
c.Assert(c4.MaxAge, qt.Equals, time.Duration(-1))
c.Assert(c4.Dir, qt.Equals, filepath.FromSlash("/path/to/c4/filecache/getresource"))
}
func TestDecodeConfigIgnoreCache(t *testing.T) {
@@ -94,7 +99,8 @@ maxAge = 3456
dir = "/path/to/c2"
[caches.images]
dir = "/path/to/c3"
[caches.getResource]
dir = "/path/to/c4"
`
cfg, err := config.FromConfigString(configStr, "toml")
@@ -103,7 +109,7 @@ dir = "/path/to/c3"
decoded, err := DecodeConfig(fs, cfg)
c.Assert(err, qt.IsNil)
c.Assert(len(decoded), qt.Equals, 5)
c.Assert(len(decoded), qt.Equals, 6)
for _, v := range decoded {
c.Assert(v.MaxAge, qt.Equals, time.Duration(0))
@@ -129,7 +135,7 @@ func TestDecodeConfigDefault(t *testing.T) {
c.Assert(err, qt.IsNil)
c.Assert(len(decoded), qt.Equals, 5)
c.Assert(len(decoded), qt.Equals, 6)
imgConfig := decoded[cacheKeyImages]
jsonConfig := decoded[cacheKeyGetJSON]
+1 -1
View File
@@ -276,7 +276,7 @@ func TestFileCacheReadOrCreateErrorInRead(t *testing.T) {
}
}
cache := NewCache(afero.NewMemMapFs(), 100*time.Hour, "")
cache := NewCache(afero.NewMemMapFs(), 100*time.Hour, 0, "")
const id = "a32"
+5
View File
@@ -31,6 +31,11 @@ type ReadSeekCloser interface {
io.Closer
}
// ReadSeekCloserProvider provides a ReadSeekCloser.
type ReadSeekCloserProvider interface {
ReadSeekCloser() (ReadSeekCloser, error)
}
// ReadSeekerNoOpCloser implements ReadSeekCloser by doing nothing in Close.
// TODO(bep) rename this and similar to ReadSeekerNopCloser, naming used in stdlib, which kind of makes sense.
type ReadSeekerNoOpCloser struct {
+2 -2
View File
@@ -16,7 +16,7 @@ package hugo
// CurrentVersion represents the current build version.
// This should be the only one.
var CurrentVersion = Version{
Number: 0.89,
PatchLevel: 3,
Number: 0.90,
PatchLevel: 0,
Suffix: "",
}
+8
View File
@@ -11,6 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !nodeploy
// +build !nodeploy
package deploy
@@ -24,6 +25,7 @@ import (
hglob "github.com/gohugoio/hugo/hugofs/glob"
"github.com/gohugoio/hugo/media"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
)
const deploymentConfigKey = "deployment"
@@ -124,12 +126,18 @@ func decodeConfig(cfg config.Provider) (deployConfig, error) {
return dcfg, err
}
for _, tgt := range dcfg.Targets {
if tgt == nil {
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 == nil {
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)
+31 -1
View File
@@ -11,6 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !nodeploy
// +build !nodeploy
package deploy
@@ -21,7 +22,6 @@ import (
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config"
)
func TestDecodeConfigFromTOML(t *testing.T) {
@@ -169,3 +169,33 @@ func TestDecodeConfigDefault(t *testing.T) {
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))
fmt.Printf("JMM-1: %s", err)
}
@@ -65,7 +65,7 @@ audio
: an array of paths to audio files related to the page; used by the `opengraph` [internal template](/templates/internal) to populate `og:audio`.
cascade
: a map of Front Matter keys whose values are passed down to the page's descendents unless overwritten by self or a closer ancestor's cascade. See [Front Matter Cascade](#front-matter-cascade) for details.
: a map of Front Matter keys whose values are passed down to the page's descendants unless overwritten by self or a closer ancestor's cascade. See [Front Matter Cascade](#front-matter-cascade) for details.
date
: the datetime assigned to this page. This is usually fetched from the `date` field in front matter, but this behaviour is configurable.
@@ -128,8 +128,7 @@ type
: the type of the content; this value will be automatically derived from the directory (i.e., the [section][]) if not specified in front matter.
url
: the full path to the content from the web root. It makes no assumptions about the path of the content file. It also ignores any language prefixes of
the multilingual feature.
: the full path to the content from the web root. It makes no assumptions about the path of the content file. See [URL Management](/content-management/urls/#set-url-in-front-matter).
videos
: an array of paths to videos related to the page; used by the `opengraph` [internal template](/templates/internal) to populate `og:video`.
@@ -157,7 +156,7 @@ show_comments: false
## Front Matter Cascade
Any node or section can pass down to descendents a set of Front Matter values as long as defined underneath the reserved `cascade` Front Matter key.
Any node or section can pass down to descendants a set of Front Matter values as long as defined underneath the reserved `cascade` Front Matter key.
### Target Specific Pages
@@ -202,9 +201,9 @@ cascade:
banner: images/typewriter.jpg
{{</ code-toggle >}}
With the above example the Blog section page and its descendents will return `images/typewriter.jpg` when `.Params.banner` is invoked unless:
With the above example the Blog section page and its descendants will return `images/typewriter.jpg` when `.Params.banner` is invoked unless:
- Said descendent has its own `banner` value set
- Said descendant has its own `banner` value set
- Or a closer ancestor node has its own `cascade.banner` value set.
@@ -229,7 +229,7 @@ See https://github.com/disintegration/imaging for more. If you want to trade qua
By default the images is encoded in the source format, but you can set the target format as an option.
Valid values are `jpg`, `png`, `tif`, `bmp`, `gif` and `webp`.
Valid values are `bmp`, `gif`, `jpeg`, `jpg`, `png`, `tif`, `tiff`, and `webp`.
```go
{{ $image.Resize "600x jpg" }}
+8 -16
View File
@@ -12,7 +12,7 @@ menu:
docs:
parent: "content-management"
weight: 120
weight: 120 #rem
weight: 120
aliases: [/extras/menus/]
toc: true
---
@@ -48,31 +48,24 @@ If all you need to do is add an entry to a menu, the simple form works well.
#### A Single Menu
```
---
{{< code-toggle >}}
menu: "main"
---
```
{{< /code-toggle >}}
#### Multiple Menus
```
---
{{< code-toggle >}}
menu: ["main", "footer"]
---
```
{{< /code-toggle >}}
#### Advanced
```
---
{{< code-toggle >}}
menu:
docs:
parent: 'extras'
weight: 20
---
```
{{< /code-toggle >}}
## Add Non-content Entries to a Menu
@@ -115,7 +108,7 @@ In this example, the top level of the menu is defined in your [site `config` fil
## Params
You can also add user-defined content to menu items via the `params` field.
You can also add user-defined content to menu items via the `params` field.
A common use case is to define a custom param to add a css class to a specific menu item.
@@ -130,7 +123,6 @@ A common use case is to define a custom param to add a css class to a specific m
class = "highlight-menu-item"
{{</ code-toggle >}}
## Render Menus
See [Menu Templates](/templates/menu-templates/) for information on how to render your site menus within your templates.
@@ -19,7 +19,7 @@ toc: true
You should define the available languages in a `languages` section in your site configuration.
> Also See [Hugo Multilingual Part 1: Content translation](https://regisphilibert.com/blog/2018/08/hugo-multilingual-part-1-managing-content-translation/)
> Also See [Hugo Multilingual Part 1: Content translation]
## Configure Languages
@@ -63,7 +63,7 @@ Anything not defined in a `languages` block will fall back to the global value f
With the configuration above, all content, sitemap, RSS feeds, paginations,
and taxonomy pages will be rendered below `/` in English (your default content language) and then below `/fr` in French.
When working with front matter `Params` in [single page templates][singles], omit the `params` in the key for the translation.
When working with front matter `Params` in [single page templates], omit the `params` in the key for the translation.
`defaultContentLanguage` sets the project's default language. If not set, the default language will be `en`.
@@ -83,25 +83,24 @@ disableLanguages = ["fr", "ja"]
Note that you cannot disable the default content language.
We kept this as a standalone setting to make it easier to set via [OS environment](/getting-started/configuration/#configure-with-environment-variables):
We kept this as a standalone setting to make it easier to set via [OS environment]:
```bash
HUGO_DISABLELANGUAGES="fr ja" hugo
```
If you have already a list of disabled languages in `config.toml`, you can enable them in development like this:
```bash
HUGO_DISABLELANGUAGES=" " hugo server
```
### Configure Multilingual Multihost
From **Hugo 0.31** we support multiple languages in a multihost configuration. See [this issue](https://github.com/gohugoio/hugo/issues/4027) for details.
This means that you can now configure a `baseURL` per `language`:
> If a `baseURL` is set on the `language` level, then all languages must have one and they must all be different.
Example:
@@ -123,7 +122,7 @@ title = "In English"
With the above, the two sites will be generated into `public` with their own root:
```bash
```text
public
├── en
└── fr
@@ -133,7 +132,7 @@ public
When you run `hugo server` we will start multiple HTTP servers. You will typically see something like this in the console:
```bash
```text
Web Server is available at 127.0.0.1:1313 (bind address 127.0.0.1)
Web Server is available at 127.0.0.1:1314 (bind address 127.0.0.1)
Press Ctrl+C to stop
@@ -145,7 +144,6 @@ Live reload and `--navigateToChanged` between the servers work as expected.
Taxonomies and [Blackfriday configuration][config] can also be set per language:
{{< code-toggle file="config" >}}
[Taxonomies]
tag = "tags"
@@ -182,7 +180,7 @@ Considering the following example:
The first file is assigned the English language and is linked to the second.
The second file is assigned the French language and is linked to the first.
Their language is __assigned__ according to the language code added as a __suffix to the filename__.
Their language is __assigned__ according to the language code added as a __suffix to the filename__.
By having the same **path and base filename**, the content pieces are __linked__ together as translated pages.
@@ -195,7 +193,6 @@ If a file has no language code, it will be assigned the default language.
This system uses different content directories for each of the languages. Each language's content directory is set using the `contentDir` param.
{{< code-toggle file="config" >}}
languages:
en:
weight: 10
@@ -205,7 +202,6 @@ languages:
weight: 20
languageName: "Français"
contentDir: "content/french"
{{< /code-toggle >}}
The value of `contentDir` can be any valid path -- even absolute path references. The only restriction is that the content directories cannot overlap.
@@ -222,7 +218,7 @@ Their language is __assigned__ according to the content directory they are __pla
By having the same **path and basename** (relative to their language content directory), the content pieces are __linked__ together as translated pages.
### Bypassing default linking.
### Bypassing default linking
Any pages sharing the same `translationKey` set in front matter will be linked as translated pages regardless of basename or location.
@@ -232,19 +228,17 @@ Considering the following example:
2. `/content/om.nn.md`
3. `/content/presentation/a-propos.fr.md`
```yaml
# set in all three pages
{{< code-toggle >}}
translationKey: "about"
```
{{< /code-toggle >}}
By setting the `translationKey` front matter param to `about` in all three pages, they will be __linked__ as translated pages.
### Localizing permalinks
Because paths and filenames are used to handle linking, all translated pages will share the same URL (apart from the language subdirectory).
To localize the URLs, the [`slug`]({{< ref "/content-management/organization/index.md#slug" >}}) or [`url`]({{< ref "/content-management/organization/index.md#url" >}}) front matter param can be set in any of the non-default language file.
To localize the URLs, the [`slug`]({{< ref "/content-management/organization/index.md#slug" >}}) or [`url`]({{< ref "/content-management/organization/index.md#url" >}}) front matter param can be set in any of the non-default language file.
For example, a French translation (`content/about.fr.md`) can have its own localized slug.
@@ -253,7 +247,6 @@ Title: A Propos
slug: "a-propos"
{{< /code-toggle >}}
At render, Hugo will build both `/about/` and `/fr/a-propos/` while maintaining their translation linking.
{{% note %}}
@@ -283,16 +276,16 @@ To create a list of links to translated content, use a template similar to the f
{{ if .IsTranslated }}
<h4>{{ i18n "translations" }}</h4>
<ul>
{{ range .Translations }}
<li>
<a href="{{ .Permalink }}">{{ .Lang }}: {{ .Title }}{{ if .IsPage }} ({{ i18n "wordCount" . }}){{ end }}</a>
</li>
{{ end }}
{{ range .Translations }}
<li>
<a href="{{ .Permalink }}">{{ .Lang }}: {{ .Title }}{{ if .IsPage }} ({{ i18n "wordCount" . }}){{ end }}</a>
</li>
{{ end }}
</ul>
{{ end }}
{{< /code >}}
The above can be put in a `partial` (i.e., inside `layouts/partials/`) and included in any template, whether a [single content page][contenttemplate] or the [homepage][]. It will not print anything if there are no translations for a given page.
The above can be put in a `partial` (i.e., inside `layouts/partials/`) and included in any template, whether a [single content page][contenttemplate] or the [homepage]. It will not print anything if there are no translations for a given page.
The above also uses the [`i18n` function][i18func] described in the next section.
@@ -300,7 +293,6 @@ The above also uses the [`i18n` function][i18func] described in the next section
`.AllTranslations` on a `Page` can be used to list all translations, including the page itself. On the home page it can be used to build a language navigator:
{{< code file="layouts/partials/allLanguages.html" >}}
<ul>
{{ range $.Site.Home.AllTranslations }}
@@ -311,22 +303,24 @@ The above also uses the [`i18n` function][i18func] described in the next section
## Translation of Strings
Hugo uses [go-i18n][] to support string translations. [See the project's source repository][go-i18n-source] to find tools that will help you manage your translation workflows.
Hugo uses [go-i18n] to support string translations. [See the project's source repository][go-i18n-source] to find tools that will help you manage your translation workflows.
Translations are collected from the `themes/<THEME>/i18n/` folder (built into the theme), as well as translations present in `i18n/` at the root of your project. In the `i18n`, the translations will be merged and take precedence over what is in the theme folder. Language files should be named according to [RFC 5646][] with names such as `en-US.toml`, `fr.toml`, etc.
Translations are collected from the `themes/<THEME>/i18n/` folder (built into the theme), as well as translations present in `i18n/` at the root of your project. In the `i18n`, the translations will be merged and take precedence over what is in the theme folder. Language files should be named according to [RFC 5646] with names such as `en-US.toml`, `fr.toml`, etc.
{{% note %}}
From **Hugo 0.31** you no longer need to use a valid language code. It can be anything.
Artificial languages with private use subtags as defined in [RFC 5646 &#167; 2.2.7](https://datatracker.ietf.org/doc/html/rfc5646#section-2.2.7) are also supported. You may omit the `art-x-` prefix for brevity. For example:
See https://github.com/gohugoio/hugo/issues/3564
```text
art-x-hugolang
hugolang
```
{{% /note %}}
Private use subtags must not exceed 8 alphanumeric characters.
### Query basic translation
From within your templates, use the `i18n` function like this:
```
```go-html-template
{{ i18n "home" }}
```
@@ -339,7 +333,7 @@ other = "Home"
The result will be
```
```text
Home
```
@@ -347,7 +341,7 @@ Home
Often you will want to use the page variables in the translation strings. To do so, pass the `.` context when calling `i18n`:
```
```go-html-template
{{ i18n "wordCount" . }}
```
@@ -360,7 +354,7 @@ other = "This article has {{ .WordCount }} words."
Assume `.WordCount` in the context has value is 101. The result will be:
```
```text
This article has 101 words.
```
@@ -368,7 +362,7 @@ This article has 101 words.
In order to meet singular/plural requirement, you must pass a dictionary (map) with a numeric `.Count` property to the `i18n` function. The below example uses `.ReadingTime` variable which has a built-in `.Count` property.
```
```go-html-template
{{ i18n "readingTime" .ReadingTime }}
```
@@ -382,52 +376,122 @@ other = "{{.Count}} minutes to read"
Assume `.ReadingTime.Count` in the context has value of 525600. The result will be:
```
```text
525600 minutes to read
```
If `.ReadingTime.Count` in the context has value is 1. The result is:
```
```text
One minute to read
```
In case you need to pass custom data: (`(dict "Count" 25)` is minimum requirement)
```
```go-html-template
{{ i18n "readingTime" (dict "Count" 25 "FirstArgument" true "SecondArgument" false "Etc" "so on, so far") }}
```
## Localization
## Customize Dates
The following localization examples assume your site's primary language is English, with translations to French and German.
At the time of this writing, Go does not yet have support for internationalized locales for dates, but if you do some work, you can simulate it. For example, if you want to use French month names, you can add a data file like ``data/mois.yaml`` with this content:
{{< code-toggle file="config" >}}
defaultContentLang = 'en'
~~~yaml
1: "janvier"
2: "février"
3: "mars"
4: "avril"
5: "mai"
6: "juin"
7: "juillet"
8: "août"
9: "septembre"
10: "octobre"
11: "novembre"
12: "décembre"
~~~
[languages]
[languages.en]
contentDir = 'content/en'
languageName = 'English'
weight = 1
[languages.fr]
contentDir = 'content/fr'
languageName = 'Français'
weight = 2
[languages.de]
contentDir = 'content/de'
languageName = 'Deutsch'
weight = 3
...then index the non-English date names in your templates like so:
{{< /code-toggle >}}
~~~html
<time class="post-date" datetime="{{ .Date.Format `2006-01-02T15:04:05Z07:00` | safeHTML }}">
Article publié le {{ .Date.Day }} {{ index $.Site.Data.mois (printf "%d" .Date.Month) }} {{ .Date.Year }} (dernière modification le {{ .Lastmod.Day }} {{ index $.Site.Data.mois (printf "%d" .Lastmod.Month) }} {{ .Lastmod.Year }})
</time>
~~~
### Dates
This technique extracts the day, month and year by specifying ``.Date.Day``, ``.Date.Month``, and ``.Date.Year``, and uses the month number as a key, when indexing the month name data file.
With this front matter:
{{< code-toggle >}}
date = 2021-11-03T12:34:56+01:00
{{< /code-toggle >}}
And this template code:
```go-html-template
{{ .Date | time.Format ":date_full" }}
```
The rendered page displays:
Language|Value
:--|:--
English|Wednesday, November 3, 2021
Français|mercredi 3 novembre 2021
Deutsch|Mittwoch, 3. November 2021
See [time.Format] for details.
### Currency
With this template code:
```go-html-template
{{ 512.5032 | lang.FormatCurrency 2 "USD" }}
```
The rendered page displays:
Language|Value
:--|:--
English|$512.50
Français|512,50 $US
Deutsch|512,50 $
See [lang.FormatCurrency] and [lang.FormatAccounting] for details.
### Numbers
With this template code:
```go-html-template
{{ 512.5032 | lang.FormatNumber 2 }}
```
The rendered page displays:
Language|Value
:--|:--
English|512.50
Français|512,50
Deutsch|512,50
See [lang.FormatNumber] and [lang.FormatNumberCustom] for details.
### Percentages
With this template code:
```go-html-template
{{ 512.5032 | lang.FormatPercent 2 }} ---> 512.50%
```
The rendered page displays:
Language|Value
:--|:--
English|512.50%
Français|512,50 %
Deutsch|512,50 %
See [lang.FormatPercent] for details.
## Menus
@@ -445,7 +509,6 @@ url = "/"
name = "Home"
weight = 0
[languages.de]
weight = 10
languageName = "Deutsch"
@@ -458,7 +521,7 @@ weight = 0
The rendering of the main navigation works as usual. `.Site.Menus` will just contain the menu in the current language. Note that `absLangURL` below will link to the correct locale of your website. Without it, menu entries in all languages would link to the English version, since it's the default content language that resides in the root directory.
```
```go-html-template
<ul>
{{- $currentPage := . -}}
{{ range .Site.Menus.main -}}
@@ -467,7 +530,6 @@ The rendering of the main navigation works as usual. `.Site.Menus` will just con
</li>
{{- end }}
</ul>
```
## Missing Translations
@@ -480,12 +542,12 @@ While translating a Hugo website, it can be handy to have a visual indicator of
Hugo will generate your website with these missing translation placeholders. It might not be suitable for production environments.
{{% /note %}}
For merging of content from other languages (i.e. missing content translations), see [lang.Merge](/functions/lang.merge/).
For merging of content from other languages (i.e. missing content translations), see [lang.Merge].
To track down missing translation strings, run Hugo with the `--i18n-warnings` flag:
```
hugo --i18n-warnings | grep i18n
```bash
hugo --i18n-warnings | grep i18n
i18n|MISSING_TRANSLATION|en|wordCount
```
@@ -504,8 +566,17 @@ If there is more than one language defined, the `LanguagePrefix` variable will e
[go-i18n-source]: https://github.com/nicksnyder/go-i18n
[go-i18n]: https://github.com/nicksnyder/go-i18n
[homepage]: /templates/homepage/
[Hugo Multilingual Part 1: Content translation]: https://regisphilibert.com/blog/2018/08/hugo-multilingual-part-1-managing-content-translation/
[i18func]: /functions/i18n/
[lang.FormatAccounting]: /functions/lang/#langformataccounting
[lang.FormatCurrency]: /functions/lang/#langformatcurrency
[lang.FormatNumber]: /functions/lang/#langformatnumber
[lang.FormatNumberCustom]: functions/lang/#langformatnumbercustom
[lang.FormatPercent]: /functions/lang/#langformatpercent
[lang.Merge]: /functions/lang.merge/
[menus]: /content-management/menus/
[OS environment]: /getting-started/configuration/#configure-with-environment-variables
[rellangurl]: /functions/rellangurl
[RFC 5646]: https://tools.ietf.org/html/rfc5646
[singles]: /templates/single-page-templates/
[single page templates]: /templates/single-page-templates/
[time.Format]: /functions/dateformat
@@ -24,12 +24,12 @@ Hugo `0.32` announced page-relative images and other resources packaged into `Pa
These terms are connected, and you also need to read about [Page Resources]({{< relref "/content-management/page-resources" >}}) and [Image Processing]({{< relref "/content-management/image-processing" >}}) to get the full picture.
{{< imgproc 1-featured Resize "300x" >}}
The illustration shows 3 bundles. Note that the home page bundle cannot contain other content pages, but other files (images etc.) are fine.
The illustration shows three bundles. Note that the home page bundle cannot contain other content pages, although other files (images etc.) are allowed.
{{< /imgproc >}}
{{% note %}}
The bundle documentation is **work in progress**. We will publish more comprehensive docs about this soon.
The bundle documentation is a **work in progress**. We will publish more comprehensive docs about this soon.
{{% /note %}}
@@ -40,7 +40,7 @@ In Hugo, your content should be organized in a manner that reflects the rendered
While Hugo supports content nested at any level, the top levels (i.e. `content/<DIRECTORIES>`) are special in Hugo and are considered the content type used to determine layouts etc. To read more about sections, including how to nest them, see [sections][].
Without any additional configuration, the following will just work:
Without any additional configuration, the following will automatically work:
```
.
@@ -70,7 +70,7 @@ The following demonstrates the relationships between your content organization a
**Tip:** You can get a reference to the content and metadata in `_index.md` using the [`.Site.GetPage` function](/functions/getpage/).
{{% /note %}}
You can keep one `_index.md` for your homepage and one in each of your content sections, taxonomies, and taxonomy terms. The following shows typical placement of an `_index.md` that would contain content and front matter for a `posts` section list page on a Hugo website:
You can create one `_index.md` for your homepage and one in each of your content sections, taxonomies, and taxonomy terms. The following shows typical placement of an `_index.md` that would contain content and front matter for a `posts` section list page on a Hugo website:
```
@@ -96,12 +96,12 @@ At build, this will output to the following destination with the associated valu
https://example.com/posts/index.html
```
The [sections][] can be nested as deeply as you need. The important part to understand is, that to make the section tree fully navigational, at least the lower-most section needs a content file. (i.e. `_index.md`).
The [sections] can be nested as deeply as you want. The important thing to understand is that to make the section tree fully navigational, at least the lower-most section must include a content file. (i.e. `_index.md`).
### Single Pages in Sections
Single content files in each of your sections are going to be rendered as [single page templates][singles]. Here is an example of a single `post` within `posts`:
Single content files in each of your sections will be rendered as [single page templates][singles]. Here is an example of a single `post` within `posts`:
```
@@ -112,7 +112,7 @@ Single content files in each of your sections are going to be rendered as [singl
content/posts/my-first-hugo-post.md
```
When Hugo builds your site, the content will be outputted to the following destination:
When Hugo builds your site, the content will be output to the following destination:
```
@@ -128,11 +128,11 @@ https://example.com/posts/my-first-hugo-post/index.html
## Paths Explained
The following concepts will provide more insight into the relationship between your project's organization and the default behaviors of Hugo when building the output website.
The following concepts provide more insight into the relationship between your project's organization and the default Hugo behavior when building output for the website.
### `section`
A default content type is determined by a piece of content's section. `section` is determined by the location within the project's `content` directory. `section` *cannot* be specified or overridden in front matter.
A default content type is determined by the section in which a content item is stored. `section` is determined by the location within the project's `content` directory. `section` *cannot* be specified or overridden in front matter.
### `slug`
@@ -152,24 +152,24 @@ A content's `path` is determined by the section's path to the file. The file `pa
The `url` is the relative URL for the piece of content. The `url`
* is based on the content's location within the directory structure OR
* is defined in front matter and *overrides all the above*
* is based on the content item's location within the directory structure OR
* is defined in front matter, in which case it *overrides all the above*
## Override Destination Paths via Front Matter
Hugo believes that you organize your content with a purpose. The same structure that works to organize your source content is used to organize the rendered site. As displayed above, the organization of the source content will be mirrored in the destination.
Hugo assumes that your content is organized with a purpose. The same structure that you use to organize your source content is used to organize the rendered site. As displayed above, the organization of the source content will be mirrored at the destination.
There are times where you may need more control over your content. In these cases, there are fields that can be specified in the front matter to determine the destination of a specific piece of content.
There are times when you may need more fine-grained control over the content organization. In such cases, the front matter field can be used to determine the destination of a specific piece of content.
The following items are defined in this order for a specific reason: items explained further down in the list will override earlier items, and not all of these items can be defined in front matter:
The following items are defined in a specific order for a reason: items explained lower down in the list override higher items. Note that not all items can be defined in front matter.
### `filename`
This isn't in the front matter, but is the actual name of the file minus the extension. This will be the name of the file in the destination (e.g., `content/posts/my-post.md` becomes `example.com/posts/my-post/`).
`filename` is not a front matter field. It is the actual file name, minus the extension. This will be the name of the file in the destination (e.g., `content/posts/my-post.md` becomes `example.com/posts/my-post/`).
### `slug`
When defined in the front matter, the `slug` can take the place of the filename for the destination.
When defined in the front matter, the `slug` can take the place of the filename in the destination.
{{< code file="content/posts/old-post.md" >}}
---
@@ -186,11 +186,11 @@ example.com/posts/new-post/
### `section`
`section` is determined by a content's location on disk and *cannot* be specified in the front matter. See [sections][] for more information.
`section` is determined by a content item's location on disk and *cannot* be specified in the front matter. See [sections] for more information.
### `type`
A content's `type` is also determined by its location on disk but, unlike `section`, it *can* be specified in the front matter. See [types][]. This can come in especially handy when you want a piece of content to render using a different layout. In the following example, you can create a layout at `layouts/new/mylayout.html` that Hugo will use to render this piece of content, even in the midst of many other posts.
A content item's `type` is also determined by its location on disk but, unlike `section`, it *can* be specified in the front matter. See [types]. This can come in especially handy when you want a piece of content to render using a different layout. In the following example, you can create a layout at `layouts/new/mylayout.html` that Hugo will use to render this piece of content, even in the midst of many other posts.
{{< code file="content/posts/my-post.md" >}}
---
@@ -206,7 +206,7 @@ layout: mylayout
### `url`
A complete URL can be provided. This will override all the above as it pertains to the end destination. This must be the path from the baseURL (starting with a `/`). `url` will be used exactly as it provided in the front matter and will ignore the `--uglyURLs` setting in your site configuration:
A complete URL can be provided. This will override all the above as it pertains to the end destination. This must be the path from the baseURL (starting with a `/`). `url` will be used exactly as it is defined in the front matter, and will ignore the `--uglyURLs` setting in your site configuration:
{{< code file="content/posts/old-url.md" >}}
---
@@ -60,7 +60,22 @@ RelPermalink
: The relative URL to the resource. Resources of type `page` will have no value.
Content
: The content of the resource itself. For most resources, this returns a string with the contents of the file. This can be used to inline some resources, such as `<script>{{ (.Resources.GetMatch "myscript.js").Content | safeJS }}</script>` or `<img src="{{ (.Resources.GetMatch "mylogo.png").Content | base64Encode }}">`.
: The content of the resource itself. For most resources, this returns a string
with the contents of the file. Use this to create inline resources.
```go-html-template
{{ with .Resources.GetMatch "script.js" }}
<script>{{ .Content | safeJS }}</script>
{{ end }}
{{ with .Resources.GetMatch "style.css" }}
<style>{{ .Content | safeCSS }}</style>
{{ end }}
{{ with .Resources.GetMatch "img.png" }}
<img src="data:{{ .MediaType }};base64,{{ .Content | base64Encode }}">
{{ end }}
```
MediaType
: The MIME type of the resource, such as `image/jpeg`.
+1 -1
View File
@@ -154,7 +154,7 @@ go install
Hugo relies on [mage](https://github.com/magefile/mage) for some convenient build and test targets. If you don't already have it, get it:
```
go get github.com/magefile/mage
go install github.com/magefile/mage@latest
```
### Fork the repository
+2 -2
View File
@@ -20,7 +20,7 @@ aliases: []
`.GetPage` returns a page of a given `path`. Both `Site` and `Page` implements this method. The `Page` variant will, if given a relative path -- i.e. a path without a leading `/` -- try look for the page relative to the current page.
{{% note %}}
**Note:** We overhauled and simplified the `.GetPage` API in Hugo 0.45. Before that you needed to provide a `Kind` attribute in addition to the path, e.g. `{{ .Site.GetPage "section" "blog" }}`. This will still work, but is now superflous.
**Note:** We overhauled and simplified the `.GetPage` API in Hugo 0.45. Before that you needed to provide a `Kind` attribute in addition to the path, e.g. `{{ .Site.GetPage "section" "blog" }}`. This will still work, but is now superfluous.
{{% /note %}}
@@ -28,7 +28,7 @@ aliases: []
{{ with .Site.GetPage "/blog" }}{{ .Title }}{{ end }}
```
This method wil return `nil` when no page could be found, so the above will not print anything if the blog section is not found.
This method will return `nil` when no page could be found, so the above will not print anything if the blog section is not found.
To find a regular page in the blog section::
+1 -1
View File
@@ -19,7 +19,7 @@ aliases: []
`dict` is especially useful for passing more than one value to a partial template.
Note that the `key` can be either a `string` or a `string slice`. The latter is useful to create a deply nested structure, e.g.:
Note that the `key` can be either a `string` or a `string slice`. The latter is useful to create a deeply nested structure, e.g.:
```go-text-template
{{ $m := dict (slice "a" "b" "c") "value" }}
+24 -10
View File
@@ -2,27 +2,41 @@
title: "fileExists"
linktitle: "fileExists"
date: 2017-08-31T22:38:22+02:00
description: Checks whether a file exists under the given path.
description: Checks for file or directory existence.
publishdate: 2017-08-31T22:38:22+02:00
lastmod: 2017-08-31T22:38:22+02:00
lastmod: 2021-11-26
categories: [functions]
menu:
docs:
parent: "functions"
signature: ["fileExists PATH"]
signature: ["os.FileExists PATH","fileExists PATH"]
workson: []
hugoversion:
relatedfuncs: []
relatedfuncs: ['os.ReadDir','os.ReadFile','os.Stat']
deprecated: false
aliases: []
---
The `os.FileExists` function attempts to resolve the path relative to the root of your project directory. If a matching file or directory is not found, it will attempt to resolve the path relative to the [`contentDir`]({{< relref "getting-started/configuration#contentdir">}}). A leading path separator (`/`) is optional.
`fileExists` allows you to check if a file exists under a given path, e.g. before inserting code into a template:
With this directory structure:
```
{{ if (fileExists "static/img/banner.jpg") -}}
<img src="{{ "img/banner.jpg" | absURL }}" />
{{- end }}
```text
content/
├── about.md
├── contact.md
└── news/
├── article-1.md
└── article-2.md
```
In the example above, a banner from the `static` folder should be shown if the given path points to an existing file.
The function returns these values:
```go-html-template
{{ os.FileExists "content" }} --> true
{{ os.FileExists "content/news" }} --> true
{{ os.FileExists "content/news/article-1" }} --> false
{{ os.FileExists "content/news/article-1.md" }} --> true
{{ os.FileExists "news" }} --> true
{{ os.FileExists "news/article-1" }} --> false
{{ os.FileExists "news/article-1.md" }} --> true
```
+25 -12
View File
@@ -1,30 +1,43 @@
---
title: getenv
description: Returns the value of an environment variable.
description: Returns the value of an environment variable, or an empty string if the environment variable is not set.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
lastmod: 2021-11-26
categories: [functions]
menu:
docs:
parent: "functions"
keywords: []
signature: ["getenv VARIABLE"]
signature: ["os.Getenv VARIABLE", "getenv VARIABLE"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
Examples:
Takes a string containing the name of the variable as input. Returns
an empty string if the variable is not set, otherwise returns the
value of the variable.
```
{{ getenv "HOME" }}
```go-html-template
{{ os.Getenv "HOME" }} --> /home/victor
{{ os.Getenv "USER" }} --> victor
```
{{% note %}}
In Unix-like environments, the variable must also be exported in order to be seen by `hugo`.
{{% /note %}}
You can pass values when building your site:
```bash
MY_VAR1=foo MY_VAR2=bar hugo
OR
export MY_VAR1=foo
export MY_VAR2=bar
hugo
```
And then retrieve the values within a template:
```go-html-template
{{ os.Getenv "MY_VAR1" }} --> foo
{{ os.Getenv "MY_VAR2" }} --> bar
```
+88 -7
View File
@@ -1,23 +1,104 @@
---
title: highlight
linktitle: highlight
description: Takes a string of code and language declaration and uses Chroma to return syntax-highlighted HTML.
description: Renders code with a syntax highlighter.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
lastmod: 2021-12-06
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [highlighting,code blocks,syntax]
signature: ["highlight INPUT LANG OPTIONS"]
workson: []
hugoversion:
signature: ["transform.Highlight INPUT LANG [OPTIONS]","highlight INPUT LANG [OPTIONS]"]
relatedfuncs: []
deprecated: false
toc: true
---
The `highlight` function uses the [Chroma] syntax highlighter, supporting over 200 languages with more than 40 available styles.
[`highlight` is used in Hugo's built-in `highlight` shortcode][highlight].
## Parameters
INPUT
: The code to highlight.
[highlight]: /content-management/shortcodes/#highlight
LANG
: The language of the code to highlight. Choose from one of the [supported languages]. Case-insensitive.
OPTIONS
: An optional, comma-separated list of zero or more [options]. Set default values in [site configuration].
## Options
lineNos
: Boolean. Default is `false`.\
Display a number at the beginning of each line.
lineNumbersInTable
: Boolean. Default is `true`.\
Render the highlighted code in an HTML table with two cells. The left table cell contains the line numbers. The right table cell contains the code, allowing a user to select and copy the code without line numbers. Irrelevant if `lineNos` is false.
anchorLineNos
: Boolean. Default is `false`.\
Render each line number as an HTML anchor element, and set the `id` attribute of the surrounding `<span>` to the line number. Irrelevant if `lineNos` is false.
lineAnchors
: String. Default is `""`.\
When rendering a line number as an HTML anchor element, prepend this value to the `id` attribute of the surrounding `<span>`. This provides unique `id` attributes when a page contains two or more code blocks. Irrelevant if `lineNos` or `anchorLineNos` is false.
lineNoStart
: Integer. Default is `1`.\
The number to display at the beginning of the first line. Irrelevant if `lineNos` is false.
hl_Lines
: String. Default is `""`.\
A space-separated list of lines to emphasize within the highlighted code. To emphasize lines 2, 3, 4, and 7, set this value to `2-4 7`. This option is independent of the `lineNoStart` option.
style
: String. Default is `monokai`.\
The CSS styles to apply to the highlighted code. See the [style gallery] for examples. Case-sensitive.
noClasses
: Boolean. Default is `true`.\
Use inline CSS styles instead of an external CSS file. To use an external CSS file, set this value to `false` and [generate the file with the hugo client][hugo client].
tabWidth
: Integer. Default is `4`.\
Substitute this number of spaces for each tab character in your highlighted code.
guessSyntax
: Boolean. Default is `false`.\
If the `LANG` parameter is blank or an unrecognized language, auto-detect the language if possible, otherwise use a fallback language.
{{% note %}}
Instead of specifying both `lineNos` and `lineNumbersInTable`, you can use the following shorthand notation:
`lineNos=inline`
: equivalent to `lineNos=true` and `lineNumbersInTable=false`
`lineNos=table`
: equivalent to `lineNos=true` and `lineNumbersInTable=true`
{{% /note %}}
## Examples
```go-html-template
{{ $input := `fmt.Println("Hello World!")` }}
{{ transform.Highlight $input "go" }}
{{ $input := `console.log('Hello World!');` }}
{{ $lang := "js" }}
{{ transform.Highlight $input $lang "lineNos=table, style=api" }}
{{ $input := `echo "Hello World!"` }}
{{ $lang := "bash" }}
{{ $options := slice "lineNos=table" "style=dracula" }}
{{ transform.Highlight $input $lang (delimit $options ",") }}
```
[Chroma]: https://github.com/alecthomas/chroma
[hugo client]: {{< relref "commands/hugo_gen_chromastyles" >}}
[options]: {{< relref "#options" >}}
[site configuration]: {{< relref "getting-started/configuration-markup#highlight">}}
[style gallery]: https://xyproto.github.io/splash/docs/
[supported languages]: {{< relref "content-management/syntax-highlighting#list-of-chroma-highlighting-languages" >}}
+35
View File
@@ -40,6 +40,41 @@ A shorter version of the above, if you only need to apply the filter once:
The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`).
### Text
{{< new-in "0.90.0" >}}
Using the `Text` filter, you can add text to an image.
{{% funcsig %}}
images.Text TEXT DICT)
{{% /funcsig %}}
The following example will add the text `Hugo rocks!` to the image with the specified color, size and position.
```go-html-template
{{ $img := resources.Get "/images/background.png"}}
{{ $img = $img.Filter (images.Text "Hugo rocks!" (dict
"color" "#ffffff"
"size" 60
"linespacing" 2
"x" 10
"y" 20
))}}
```
You can load a custom font if needed. Load the font as a Hugo `Resource` and set it as an option:
```go-html-template
{{ $font := resources.Get "https://github.com/google/fonts/raw/main/apache/roboto/static/Roboto-Black.ttf" }}
{{ $img := resources.Get "/images/background.png"}}
{{ $img = $img.Filter (images.Text "Hugo rocks!" (dict
"font" $font
))}}
```
### Brightness
{{% funcsig %}}
+14 -14
View File
@@ -1,9 +1,9 @@
---
title: os.Stat
description: Gets a file information of a given path.
description: Returns a FileInfo structure describing a file or directory.
date: 2018-08-07
publishdate: 2018-08-07
lastmod: 2018-08-07
lastmod: 2021-11-26
categories: [functions]
menu:
docs:
@@ -12,21 +12,21 @@ keywords: [files]
signature: ["os.Stat PATH"]
workson: []
hugoversion:
relatedfuncs: [readDir]
relatedfuncs: ['os.FileExists','os.ReadDir','os.ReadFile']
deprecated: false
aliases: []
---
The `os.Stat` function attempts to resolve the path relative to the root of your project directory. If a matching file or directory is not found, it will attempt to resolve the path relative to the [`contentDir`]({{< relref "getting-started/configuration#contentdir">}}). A leading path separator (`/`) is optional.
If your current project working directory has a single file named `README.txt` (30 bytes):
```
{{ $stat := os.Stat "README.txt" }}
{{ $stat.Name }} → "README.txt"
{{ $stat.Size }} → 30
```go-html-template
{{ $f := os.Stat "README.md" }}
{{ $f.IsDir }} --> false (bool)
{{ $f.ModTime }} --> 2021-11-25 10:06:49.315429236 -0800 PST (time.Time)
{{ $f.Name }} --> README.md (string)
{{ $f.Size }} --> 241 (int64)
{{ $d := os.Stat "content" }}
{{ $d.IsDir }} --> true (bool)
```
Function [`os.Stat`][Stat] returns [`os.FileInfo`][osfileinfo].
For further information of `os.FileInfo`, see [golang page][osfileinfo].
[Stat]: /functions/os.Stat/
[osfileinfo]: https://golang.org/pkg/os/#FileInfo
Details of the `FileInfo` structure are available in the [Go documentation](https://pkg.go.dev/io/fs#FileInfo).
+33 -10
View File
@@ -1,28 +1,51 @@
---
title: readDir
description: Gets a directory listing from a directory relative to the current working directory.
date: 2017-02-01
description: Returns an array of FileInfo structures sorted by filename, one element for each directory entry.
publishdate: 2017-02-01
lastmod: 2017-02-01
lastmod: 2021-11-26
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [files]
signature: ["readDir PATH"]
signature: ["os.ReadDir PATH", "readDir PATH"]
workson: []
hugoversion:
relatedfuncs: [readFile]
relatedfuncs: ['os.FileExists','os.ReadFile','os.Stat']
deprecated: false
aliases: []
---
The `os.ReadDir` function resolves the path relative to the root of your project directory. A leading path separator (`/`) is optional.
If your current project working directory has a single file named `README.txt`:
With this directory structure:
```
{{ range (readDir ".") }}{{ .Name }}{{ end }} → "README.txt"
```text
content/
├── about.md
├── contact.md
└── news/
├── article-1.md
└── article-2.md
```
For more information on using `readDir` and `readFile` in your templates, see [Local File Templates][local].
This template code:
[local]: /templates/files/
```go-html-template
{{ range os.ReadDir "content" }}
{{ .Name }} --> {{ .IsDir }}
{{ end }}
```
Produces:
```html
about.md --> false
contact.md --> false
news --> true
```
Note that `os.ReadDir` is not recursive.
Details of the `FileInfo` structure are available in the [Go documentation](https://pkg.go.dev/io/fs#FileInfo).
For more information on using `readDir` and `readFile` in your templates, see [Local File Templates]({{< relref "/templates/files" >}}).
+21 -12
View File
@@ -1,32 +1,41 @@
---
title: readFile
description: Reads a file from disk relative to the current project working directory and returns a string.
description: Returns the contents of a file.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-30
lastmod: 2021-11-26
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [files]
signature: ["readFile PATH"]
signature: ["os.ReadFile PATH", "readFile PATH"]
workson: []
hugoversion:
relatedfuncs: [readDir]
relatedfuncs: ['os.FileExists','os.ReadDir','os.Stat']
deprecated: false
aliases: []
---
The `os.ReadFile` function attempts to resolve the path relative to the root of your project directory. If a matching file is not found, it will attempt to resolve the path relative to the [`contentDir`]({{< relref "getting-started/configuration#contentdir">}}). A leading path separator (`/`) is optional.
Note that the filename must be relative to the current project working directory, or the project's `/content` folder.
With a file named README.md in the root of your project directory:
So, if you have a file with the name `README.txt` in the root of your project with the content `Hugo Rocks!`:
```
{{readFile "README.txt"}} → "Hugo Rocks!"
```text
This is **bold** text.
```
If you receive a "file doesn't exist" error with a path listed, do take note that the path is the last one checked by the function, and may not accurately reflect your target. You should generally double-check your path for mistakes.
This template code:
For more information on using `readDir` and `readFile` in your templates, see [Local File Templates][local].
```go-html-template
{{ os.ReadFile "README.md" }}
```
[local]: /templates/files/
Produces:
```html
This is **bold** text.
```
Note that `os.ReadFile` returns raw (uninterpreted) content.
For more information on using `readDir` and `readFile` in your templates, see [Local File Templates]({{< relref "/templates/files" >}}).
+1 -1
View File
@@ -22,7 +22,7 @@ It normally takes two parameters: `start` and `length`. It can also take one par
To extract characters from the end of the string, use a negative start number.
In addition, borrowing from the extended behavior described at https://php.net substr, if `length` is given and is negative, that number of characters will be omitted from the end of string.
If `length` is given and is negative, that number of characters will be omitted from the end of string.
```
{{ substr "abcdef" 0 }} → "abcdef"
@@ -1,6 +1,6 @@
---
title: "transform.Unmarshal"
description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV."
description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV."
date: 2018-12-23
categories: [functions]
menu:
@@ -45,3 +45,32 @@ Example:
```go-html-template
{{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }}
```
## XML data
As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data.
To get the contents of `<title>` in the document below, you use `{{ .message.title }}`:
```
<root>
<message>
<title>Hugo rocks!</title>
<description>Thanks for using Hugo</description>
</message>
</root>
```
The following example lists the items of an RSS feed:
```
{{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }}
{{ range .channel.item }}
<strong>{{ .title | plainify | htmlUnescape }}</strong><br />
<p>{{ .description | plainify | htmlUnescape }}</p>
{{ $link := .link | plainify | htmlUnescape }}
<a href="{{ $link }}">{{ $link }}</a><br />
<hr>
{{ end }}
{{ end }}
```
+17 -21
View File
@@ -1,35 +1,31 @@
---
title: .Unix
draft: false
description: .Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC.
description: Converts a time.Time value to the number of seconds elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00&nbsp;UTC on 1 January 1970.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
keywords: [dates,time]
categories: [functions]
menu:
docs:
parent: "functions"
signature: [".Unix"]
workson: [times]
hugoversion:
signature: [".Unix",".UnixMilli",".UnixMicro",".UnixNano"]
relatedfuncs: [Format,dateFormat,now,time]
deprecated: false
aliases: []
---
## Example: Time Passed Since Last Modification
The `Milli`, `Micro`, and `Nano` variants return the number of milliseconds, microseconds, and nanoseconds (respectively) elapsed since the Unix epoch.
This very simple one-liner uses `now.Unix` to calculate the amount of time that has passed between the `.LastMod` for the current page and the last build of the current page.
```go-html-template
.Date.Unix --> 1637259694
.ExpiryDate.Unix --> 1672559999
.Lastmod.Unix --> 1637361786
.PublishDate.Unix --> 1637421261
{{< code file="time-passed.html" >}}
{{ div (sub now.Unix .Lastmod.Unix) 86400 }}
{{< /code >}}
("1970-01-01T00:00:00-00:00" | time.AsTime).Unix --> 0
("1970-01-01T00:00:42-00:00" | time.AsTime).Unix --> 42
("1970-04-11T01:48:29-08:00" | time.AsTime).Unix --> 8675309
("2026-05-02T20:09:31-07:00" | time.AsTime).Unix --> 1777777771
Since both values are integers, they can be subtracted and then divided by the number of seconds in a day (i.e., `60 * 60 * 24 == 86400`).
{{% note %}}
Hugo's output is *static*. For the example above to be realistic, the site needs to be built every day.
{{% /note %}}
[partial template]: /templates/partials/
now.Unix --> 1637447841
now.UnixMilli --> 1637447841347
now.UnixMicro --> 1637447841347378
now.UnixNano --> 1637447841347378799
```
@@ -1,79 +0,0 @@
---
title: Code Toggle
description: Code Toggle tryout and showcase.
date: 2018-03-16
categories: [getting started,fundamentals]
keywords: [configuration,toml,yaml,json]
weight: 60
sections_weight: 60
draft: false
toc: true
---
## The Config Toggler!
This is an example for the Config Toggle shortcode.
Its purpose is to let users choose a Config language by clicking on its corresponding tab. Upon doing so, every Code toggler on the page will be switched to the target language. Also, target language will be saved in user's `localStorage` so when they go to a different pages, Code Toggler display their last "toggled" config language.
{{% note %}}
The `code-toggler` shortcode is not an internal Hugo shortcode. This page's purpose is to test out a custom feature that we use throughout this site. See: https://github.com/gohugoio/gohugoioTheme/blob/master/layouts/shortcodes/code-toggle.html
{{% /note %}}
## That Config Toggler
{{< code-toggle file="config">}}
baseURL: "https://yoursite.example.com/"
title: "My Hugo Site"
footnoteReturnLinkContents: "↩"
permalinks:
posts: /:year/:month/:title/
params:
Subtitle: "Hugo is Absurdly Fast!"
AuthorName: "Jon Doe"
GitHubUser: "spf13"
ListOfFoo:
- "foo1"
- "foo2"
SidebarRecentLimit: 5
{{< /code-toggle >}}
## Another Config Toggler!
{{< code-toggle file="theme">}}
# theme.toml template for a Hugo theme
name = "Hugo Theme"
license = "MIT"
licenselink = "https://github.com/budparr/gohugo.io/blob/master/LICENSE.md"
description = ""
homepage = "https://github.com/budparr/gohugo.io"
tags = ["website"]
features = ["", ""]
min_version = 0.18
[author]
name = "Bud Parr"
homepage = "https://github.com/budparr"
{{< /code-toggle >}}
## Two regular code blocks
{{< code file="bf-config.toml" >}}
[blackfriday]
angledQuotes = true
fractions = false
plainIDAnchors = true
extensions = ["hardLineBreak"]
{{< /code >}}
{{< code file="bf-config.yml" >}}
blackfriday:
angledQuotes: true
fractions: false
plainIDAnchors: true
extensions:
- hardLineBreak
{{< /code >}}
@@ -166,6 +166,12 @@ Enable to turn relative URLs into absolute.
The directory from where Hugo reads content files. {{% module-mounts-note %}}
### copyright
**Default value:** ""
Copyright notice for your site, typically displayed in the footer.
### dataDir
**Default value:** "data"
@@ -275,6 +281,12 @@ If true, auto-detect Chinese/Japanese/Korean Languages in the content. This will
### imaging
See [Image Processing Config](/content-management/image-processing/#image-processing-config).
### languageCode
**Default value:** ""
A language tag as defined by [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646). The internal [RSS template](https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/rss.xml) populates its `<language>` element with this value. The value is not used elsewhere.
### languages
See [Configure Languages](/content-management/multilingual/#configure-languages).
@@ -351,6 +363,17 @@ When using `ref` or `relref` to resolve page links and a link cannot resolved, i
### refLinksNotFoundURL
URL to be used as a placeholder when a page reference cannot be found in `ref` or `relref`. Is used as-is.
### removePathAccents
**Default value:** false
Removes [non-spacing marks](https://www.compart.com/en/unicode/category/Mn) from [composite characters](https://en.wikipedia.org/wiki/Precomposed_character) in content paths.
```text
content/post/hügó.md --> https://example.org/post/hugo/
```
### rssLimit
Maximum number of items in the RSS feed.
@@ -381,9 +404,9 @@ The directory where Hugo reads the themes from.
### timeout
**Default value:** 10000
**Default value:** "30s"
Timeout for generating page contents, in milliseconds (defaults to 10&nbsp;seconds). *Note:* this is used to bail out of recursive content generation, if your pages are slow to generate (e.g., because they require large image processing or depend on remote contents) you might need to raise this limit.
Timeout for generating page contents, specified as a [duration](https://pkg.go.dev/time#Duration) or in milliseconds. *Note:*&nbsp;this is used to bail out of recursive content generation. You might need to raise this limit if your pages are slow to generate (e.g., because they require large image processing or depend on remote contents).
### timeZone
@@ -456,7 +479,7 @@ This is only relevant when running `hugo server`, and it allows to set HTTP head
{{< code-toggle file="config">}}
[server]
[[server.headers]]
for = "/**.html"
for = "/**"
[server.headers.values]
X-Frame-Options = "DENY"
@@ -471,7 +494,7 @@ Since this is is "development only", it may make sense to put it below the `deve
{{< code-toggle file="config/development/server">}}
[[headers]]
for = "/**.html"
for = "/**"
[headers.values]
X-Frame-Options = "DENY"
@@ -564,12 +587,18 @@ Test and document setting params via JSON env var.
## Ignore Content and Data Files when Rendering
To exclude specific files from the content and data directories when rendering your site, set `ignoreFiles` to one or more regular expressions.
To exclude specific files from the `content` and `data` directories when rendering your site, set `ignoreFiles` to one or more regular expressions to match against the absolute file path.
For example, to ignore content and data files ending with `.foo` and `.boo`:
To ignore files ending with `.foo` or `.boo`:
{{< code-toggle >}}
ignoreFiles = [ "\\.foo$","\\.boo$"]
{{< code-toggle copy="false" >}}
ignoreFiles = ['\.foo$', '\.boo$']
{{< /code-toggle >}}
To ignore a file using the absolute file path:
{{< code-toggle copy="false" >}}
ignoreFiles = ['^/home/user/project/content/test\.md$']
{{< /code-toggle >}}
## Configure Front Matter
@@ -657,6 +686,9 @@ maxAge = -1
[caches.getcsv]
dir = ":cacheDir/:project"
maxAge = -1
[caches.getresource]
dir = ":cacheDir/:project"
maxAge = -1
[caches.images]
dir = ":resourceDir/_gen"
maxAge = -1
@@ -516,6 +516,14 @@ For the latest version, the Hugo package maintained by [@daftaupe](https://githu
See the [related discussion in the Hugo forums][redhatforum].
### openSUSE Tumbleweed
openSUSE maintains an [official package](https://software.opensuse.org/package/hugo) for the Tumbleweed rolling release distribution, it may be installed with:
````
sudo zypper install hugo
````
### Solus
Solus includes Hugo in its package repository, it may be installed with:
@@ -86,6 +86,14 @@ jobs:
For more advanced settings [actions-hugo](https://github.com/marketplace/actions/hugo-setup) and [actions-gh-pages](https://github.com/marketplace/actions/github-pages-action).
## Github pages setting
By default, the GitHub action pushes the generated content to the `gh-pages` branch. This means GitHub has to serve your `gh-pages` branch as a GitHub Pages branch. You can change this setting by going to Settings > GitHub Pages, and change the source branch to `gh-pages`.
## Change baseURL in config.toml
Don't forget to rename your `baseURL` in `config.toml` with the value `https://<USERNAME>.github.io` for your user repository or `https://<USERNAME>.github.io/<REPOSITORY_NAME>` for a project repository.
Unless this is present in your `config.toml`, your website won't work.
## Use a Custom Domain
If you'd like to use a custom domain for your GitHub Pages site, create a file `static/CNAME`. Your custom domain name should be the only contents inside `CNAME`. Since it's inside `static`, the published site will contain the CNAME file at the root of the published site, which is a requirement of GitHub Pages.
@@ -6,7 +6,7 @@ date: 2019-06-06
publishdate: 2019-06-06
lastmod: 2020-01-01
categories: [hosting and deployment]
keywords: [render,hosting,deployment]
keywords: [hosting,deployment]
authors: [Anurag Goel]
menu:
docs:
+39 -2
View File
@@ -20,14 +20,51 @@ aliases: [/assets/]
Asset files must be stored in the asset directory. This is `/assets` by default, but can be configured via the configuration file's `assetDir` key.
### From file to resource
### From file or URL to resource
In order to process an asset with Hugo Pipes, it must be retrieved as a resource using `resources.Get`, which takes one argument: the filepath of the file relative to the asset directory.
In order to process an asset with Hugo Pipes, it must be retrieved as a resource using `resources.Get`. The first argument can be the filepath of the file relative to the asset directory or the URL of the file.
```go-html-template
{{ $style := resources.Get "sass/main.scss" }}
{{ $remoteStyle := resources.Get "https://www.example.com/styles.scss" }}
```
#### Request options
When using an URL, the `resources.Get` function takes an optional options map as the last argument, e.g.:
```
{{ $resource := resources.Get "https://example.org/api" (dict "headers" (dict "Authorization" "Bearer abcd")) }}
```
If you need multiple values for the same header key, use a slice:
```
{{ $resource := resources.Get "https://example.org/api" (dict "headers" (dict "X-List" (slice "a" "b" "c"))) }}
```
You can also change the request method and set the request body:
```
{{ $postResponse := resources.Get "https://example.org/api" (dict
"method" "post"
"body" `{"complete": true}`
"headers" (dict
"Content-Type" "application/json"
)
)}}
```
#### Cache of remote resources
Each downloaded URL will be cached in the default folder `$TMPDIR/hugo_cache/`. The variable `$TMPDIR` will be resolved to your system-dependent temporary directory.
With the command-line flag `--cacheDir`, you can specify any folder on your system as a caching directory.
You can also set `cacheDir` or `caches.getresource` in the [main configuration file][config].
If you don't like caching at all, you can fully disable caching with the command line flag `--ignoreCache`.
### Asset publishing
Assets will only be published (to `/public`) if `.Permalink` or `.RelPermalink` is used.
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

+7 -13
View File
@@ -1,13 +1,12 @@
---
date: 2021-11-02
title: "0.89.0"
description: "0.89.0"
title: "Fine Grained File Filters"
description: "Hugo 0.89.0 brings fine grained file filters, archetype rewrite, dependency refresh, and more ..."
categories: ["Releases"]
---
This release is a dependency refresh (the new Goldmark verion comes with a lot of bug fixes, as one example), many bug fixes, but also some nice new features:
This release is a dependency refresh (the new Goldmark version comes with a lot of bug fixes, as one example), many bug fixes, but also some nice new features:
We have added the [configuration settings](https://gohugo.io/hugo-modules/configuration/#module-config-mounts) **includeFiles** and **excludeFiles** to the mount configuration. This allows fine grained control over what files to include, and it works for all of Hugo's file systems (including `/static`).
@@ -17,7 +16,7 @@ We have also [reimplemented archetypes](https://github.com/gohugoio/hugo/pull/90
hugo new content/en/posts/my-first-post.md
```
This release represents **50 contributions by 13 contributors** to the main Hugo code base.[@bep](https://github.com/bep) leads the Hugo development with a significant amount of contributions, but also a big shoutout to [@dependabot[bot]](https://github.com/apps/dependabot), [@jmooring](https://github.com/jmooring), and [@anthonyfok](https://github.com/anthonyfok) for their ongoing contributions.
This release represents **50 contributions by 13 contributors** to the main Hugo code base. [@bep](https://github.com/bep) leads the Hugo development with a significant amount of contributions, but also a big shoutout to [@dependabot[bot]](https://github.com/apps/dependabot), [@jmooring](https://github.com/jmooring), and [@anthonyfok](https://github.com/anthonyfok) for their ongoing contributions.
And thanks to [@digitalcraftsman](https://github.com/digitalcraftsman) for his ongoing work on keeping the themes site in pristine condition.
Many have also been busy writing and fixing the documentation in [hugoDocs](https://github.com/gohugoio/hugoDocs),
@@ -35,10 +34,10 @@ Hugo now has:
* Hugo now writes an empty file named `.hugo_build.lock` to the root of the project when building (also when doing `hugo new mypost.md` and other commands that requires a build). We recommend you just leave this file alone. Put it in `.gitignore` or similar if you don't want the file in your source repository.
* We have updated to ESBuild `v0.13.12`. The release notes for [v0.13.0](https://github.com/evanw/esbuild/releases/tag/v0.13.0) mentions a potential breaking change.
* We now only build AMD64 release binaries (see [this issue](https://github.com/gohugoio/hugo/issues/9102)) for the Unix OSes (e.g. NetBSD). If need, say, a binary for ARM64, you need to build it yourself.
* We now build only one release binary/archive for MacOS, see [this issue](https://github.com/gohugoio/hugo/issues/9035) that works on both Intel and the new Arm M1 systems.
* We now only build AMD64 release binaries (see [this issue](https://github.com/gohugoio/hugo/issues/9102)) for the Unix OSes (e.g. NetBSD). If you need, say, a binary for ARM64, you need to build it yourself.
* We now build only one release binary/archive for MacOS (see [this issue](https://github.com/gohugoio/hugo/issues/9035)) that works on both Intel and the new Arm M1 systems.
* `.File.ContentBaseName` now returns the owning directory name for all bundles (branch an leaf). This is a bug fix, but worth mentioning. See [this issue](https://github.com/gohugoio/hugo/issues/9112).
* We have updated the Twitter shortcode to use Twitter's new API. See [thiss issue] for details.
* We have updated the Twitter shortcode to use Twitter's new API. See [this issue](https://github.com/gohugoio/hugo/pull/9106) for details.
## Enhancements
@@ -105,8 +104,3 @@ Hugo now has:
* Fix the "page picker" logic in --navigateToChanged [096f5e19](https://github.com/gohugoio/hugo/commit/096f5e19217e985bccbf6c539e1b220541ffa6f6) [@bep](https://github.com/bep) [#9051](https://github.com/gohugoio/hugo/issues/9051)
* Fix a typo on OpenBSD [c7957c90](https://github.com/gohugoio/hugo/commit/c7957c90e83ff2b2cc958bd61486a244f0fd8891) [@nabbisen](https://github.com/nabbisen)
* Fix value of useResourceCacheWhen in TestResourceChainPostCSS [e6e44b7c](https://github.com/gohugoio/hugo/commit/e6e44b7c41a9b517ffc3775ea0a6aec2b1d4591b) [@jmooring](https://github.com/jmooring)
@@ -0,0 +1,19 @@
---
date: 2021-11-17
title: "Hugo 0.89.4: One Bug Fix"
description: "This version fixes one bug introduced in 0.89.0."
categories: ["Releases"]
images:
- images/blog/hugo-bug-poster.png
---
This is a bug-fix release with one important fix for people using `hugo new` to create new content:
* Fix content dir resolution when main project is a Hugo Module [2e70f61f](https://github.com/gohugoio/hugo/commit/2e70f61fb04cea08ef6598728a57637ae2cc199c) [@bep](https://github.com/bep) [#9177](https://github.com/gohugoio/hugo/issues/9177)
-9
View File
@@ -1,9 +0,0 @@
[**Aether**](https://getaether.net) is an open-source peer-to-peer network that hosts self-moderating online-communities.
[**Aether Pro**](https://aether.app), based on Aether, is a collaboration tool for remote-friendly companies.
The site is built by:
* [Burak Nehbit](https://twitter.com/nehbit)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 269 KiB

-39
View File
@@ -1,39 +0,0 @@
---
title: Aether
date: 2020-02-26
description: "Showcase: \"Hugo is not just a static site generator for us, it's the core framework at the heart of our entire web front-end.\""
# The URL to the site on the internet.
siteURL: https://getaether.net
# Add credit to the article author. Leave blank or remove if not needed/wanted.
byline: "[Burak Nehbit](https://twitter.com/nehbit), Maintainer, Aether"
---
To say that this website, our main online presence, needed to do a lot would be an understatement.
Our site is home to both *Aether* and *Aether Pro*, our **knowledgebase for each product**, a **server for static assets that we use in our emails**, the **interactive sign-up flows**, **payments client**, **downloads provider**, and even a **mechanism for delivering auto-update notifications** to our native clients. We are using a single Hugo site for all these — it's not a static site generator for us, it's the core framework at the heart of our *entire* web front-end.
Not only that, this had to work with one developer crunched for time who spends most of his time working on two separate apps across 3 desktop platforms — someone whose main job is very far from building static websites. We only had scraps of time to design and build this Hugo site, make it performant and scalable, and Hugo did a phenomenal job delivering on that promise.
The last piece is, funnily enough, moving our blog to Hugo, which it is not as of now. This was an inherited mistake we are currently rectifying. Soon, our entire web footprint will be living in Hugo.
### Structure
Our website is built in such a way that there is a separate Vue.js instance for each of the contexts since we are not using JS-based single-page navigation. We use Hugo for navigation and to build most pages. For the pages we need to make interactive, we use Vue.js to build individual, self-contained single-page Javascript apps. One such example is our sign-up flow at [aether.app](https://aether.app), an individual Vue app living within a Hugo page, with its own JS-based navigation.
This is a relatively complex setup, and somewhat out of the ordinary. Yet, even with this custom setup, using Hugo was painless.
### Tools
**CMS**: Hugo
**Theme**: Custom-designed
**Hosting**: Netlify, pushed to production via `git push`.
**Javascript runtime**: Vue.js
@@ -1,6 +0,0 @@
[Camping Arolla](https://www.camping-arolla.com) is located in the heart of the Swiss Alps, at an altitude of 1.950 meters.
The site is built by:
* [Didier Divinerites](https://github.com/divinerites)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 441 KiB

@@ -1,29 +0,0 @@
---
title: Cocoon & Cosy
date: 2018-08-10
description: "Showcase: \"Emergency setup a dedicated site in an afternoon.\""
siteURL: https://www.cocoon-arolla.com
byline: "[Didier Divinerites](https://github.com/divinerites)"
---
Swiss [Arolla campsite](https://www.camping-arolla.com) runs the highest campsite in Europe and I'm completely re-doing their actual Website with Hugo.
But they just launch a brand new offer (luxury tents with bed and fire oven), and we couldn't wait for the proper new website for having this promoted: we needed the website up and running within 24h!
So we decided to quickly launch a dedicated [independent web site](https://www.cocoon-arolla.com) using all the powerful tools included with [gohugo.io](https://gohugo.io) and some things we already knew & used:
- Choose a spectacular landing theme in the rich [Hugo Themes](https://themes.gohugo.io/) collection : [Airspace Theme](https://themes.gohugo.io/airspace-hugo/) by Themefisher.
- Replace the main images.
- Add a [hugo-easy-gallery / photoswipe](https://github.com/liwenyip/hugo-easy-gallery) on the main page with attractive images.
- Add the promo video with a simple *vimeo* shortcode.
- Replace the Google Maps widget by the [OpenStreetMap](https://www.openstreetmap.org/) equivalent
- Use a [Zotabox](https://www.zotabox.com) contact form.
- Write the content in French & in English directly on the content pages, describe their services, add fun facts and true testimonies.
- Setup a GDPR compliant site with the new Hugo options.
- Use [Netlify](https://www.netlify.com) for publishing it in a breeze.
The first version was up in 4 hours, and the polished 2 languages version was published on Netlify the next day.
This would have been impossible to do it in such a short time without all the powerful Hugo tools and Netlify simplicity.
@@ -1,4 +0,0 @@
Pace was started in 2016 to give hotels the super-power to always have the right price.
We've been using **Hugo+Gulp** from the very beginning and the workflow is proving to scale incredibly well with us as we grow the team and business.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 292 KiB

@@ -1,28 +0,0 @@
---
title: Pace Revenue Management
date: 2018-02-08
description: "Showcase: \"When we came across Hugo we were blown away.\""
siteURL: https://www.paceup.com/
# Link to the site's Hugo source code if public and you can/want to share.
# Remove or leave blank if not needed/wanted.
# Add credit to the article author. Leave blank or remove if not needed/wanted.
---
From the beginning, at Pace, we were focused on solving customer needs and didn't want to over-engineer our marketing or sales. At the same time we didn't want to lock ourselves into a WordPress, Squarespace or the like.
The ideal was a fast, simple, static site builder. When we came across Hugo we were blown away. Being a European company we wanted to be multi-lingual from the get-go and allow multiple team-members to collaborate and own their content. We also felt that a tech-company in 2018 should be capable of hosting its own blog in a simple way.
Here was Hugo, that allowed us to completely separate content from layout. Our sales-team edit a markdown-file, the engineers commit and off we go -- immediately deployable or pre-viewable.
The only other way to have all that Hugo offers is to go down the full rabbit-hole of building your own server-side React or some such. Possibly Jekyll but again very complex to work with. The alternatives come with too much work for what should be quite simple.
**Hugo + Gulp + Netlify for the win! Don't over engineer your web presence!**
Huge thanks to [@bep](https://github.com/bep) and [community](https://discourse.gohugo.io/) for Hugo.
+6 -4
View File
@@ -6,7 +6,7 @@ date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-03-12
categories: [templates]
keywords: [data,dynamic,csv,json,toml,yaml]
keywords: [data,dynamic,csv,json,toml,yaml,xml]
menu:
docs:
parent: "templates"
@@ -20,7 +20,7 @@ toc: true
<!-- begin data files -->
Hugo supports loading data from YAML, JSON, and TOML files located in the `data` directory in the root of your Hugo project.
Hugo supports loading data from YAML, JSON, XML, and TOML files located in the `data` directory in the root of your Hugo project.
{{< youtube FyPgSuwIMWQ >}}
@@ -28,7 +28,7 @@ Hugo supports loading data from YAML, JSON, and TOML files located in the `data`
The `data` folder is where you can store additional data for Hugo to use when generating your site. Data files aren't used to generate standalone pages; rather, they're meant to be supplemental to content files. This feature can extend the content in case your front matter fields grow out of control. Or perhaps you want to show a larger dataset in a template (see example below). In both cases, it's a good idea to outsource the data in their own files.
These files must be YAML, JSON, or TOML files (using the `.yml`, `.yaml`, `.json`, or `.toml` extension). The data will be accessible as a `map` in the `.Site.Data` variable.
These files must be YAML, JSON, XML, or TOML files (using the `.yml`, `.yaml`, `.json`, `.xml`, or `.toml` extension). The data will be accessible as a `map` in the `.Site.Data` variable.
## Data Files in Themes
@@ -95,7 +95,7 @@ Discover a new favorite bass player? Just add another `.toml` file in the same d
## Example: Accessing Named Values in a Data File
Assume you have the following data structure in your `User0123.[yml|toml|json]` data file located directly in `data/`:
Assume you have the following data structure in your `User0123.[yml|toml|xml|json]` data file located directly in `data/`:
{{< code-toggle file="User0123" >}}
Name: User0123
@@ -232,6 +232,7 @@ If you change any local file and the LiveReload is triggered, Hugo will read the
* [YAML Spec][yaml]
* [JSON Spec][json]
* [CSV Spec][csv]
* [XML Spec][xml]
[config]: /getting-started/configuration/
[csv]: https://tools.ietf.org/html/rfc4180
@@ -247,3 +248,4 @@ If you change any local file and the LiveReload is triggered, Hugo will read the
[variadic]: https://en.wikipedia.org/wiki/Variadic_function
[vars]: /variables/
[yaml]: https://yaml.org/spec/
[xml]: https://www.w3.org/XML/
+1 -2
View File
@@ -69,7 +69,7 @@ Hugo also ships with an internal template for [Disqus comments][disqus], a popul
To use Hugo's Disqus template, you first need to set a single configuration value:
{{< code-toggle file="config" >}}
disqusShortname = "yourdiscussshortname"
disqusShortname = "your-disqus-shortname"
{{</ code-toggle >}}
You also have the option to set the following in the front matter for a given piece of content:
@@ -209,7 +209,6 @@ To add Twitter card metadata, include the following line between the `<head>` ta
## The Internal Templates
* `_internal/disqus.html`
* `_internal/google_news.html`
* `_internal/google_analytics.html`
* `_internal/google_analytics_async.html`
* `_internal/opengraph.html`
+60 -39
View File
@@ -151,7 +151,7 @@ Go Templates only ship with a few basic functions but also provide a mechanism f
<!-- prints true (i.e., since 1 is less than 2) -->
```
Note that both examples make use of Go Template's [math functions][].
Note that both examples make use of Go Template's [math]][] functions.
{{% note "Additional Boolean Operators" %}}
There are more boolean operators than those listed in the Hugo docs in the [Go Template documentation](https://golang.org/pkg/text/template/#hdr-Functions).
@@ -184,7 +184,7 @@ Example of including a `layouts/partials/header.html` partial:
The `template` function was used to include *partial* templates
in much older Hugo versions. Now it's useful only for calling
[*internal* templates][internal_templates]. The syntax is `{{ template
[*internal* templates][internal templates]. The syntax is `{{ template
"_internal/<TEMPLATE>.<EXTENSION>" . }}`.
{{% note %}}
@@ -630,48 +630,69 @@ Finally, you can pull "magic constants" out of your layouts as well. The followi
</nav>
```
## Example: Show Only Upcoming Events
## Example: Show Future Events
Go allows you to do more than what's shown here. Using Hugo's [`where` function][where] and Go built-ins, we can list only the items from `content/events/` whose date (set in a content file's [front matter][]) is in the future. The following is an example [partial template][partials]:
Given the following content structure and [front matter]:
{{< code file="layouts/partials/upcoming-events.html" download="upcoming-events.html" >}}
<h4>Upcoming Events</h4>
<ul class="upcoming-events">
{{ range where .Pages.ByDate "Section" "events" }}
{{ if ge .Date.Unix now.Unix }}
<li>
<!-- add span for event type -->
<span>{{ .Type | title }} —</span>
{{ .Title }} on
<!-- add span for event date -->
<span>{{ .Date.Format "2 January at 3:04pm" }}</span>
at {{ .Params.place }}
</li>
```text
content/
└── events/
├── event-1.md
├── event-2.md
└── event-3.md
```
{{< code-toggle file="content/events/event-1.md" copy="false" >}}
title = 'Event 1'
date = 2021-12-06T10:37:16-08:00
draft = false
start_date = 2021-12-05T09:00:00-08:00
end_date = 2021-12-05T11:00:00-08:00
{{< /code-toggle >}}
This [partial template][partials] renders future events:
{{< code file="layouts/partials/future-events.html" >}}
<h2>Future Events</h2>
<ul>
{{ range where site.RegularPages "Type" "events" }}
{{ if gt (.Params.start_date | time.AsTime) now }}
{{ $startDate := .Params.start_date | time.Format ":date_medium" }}
<li>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> - {{ $startDate }}
</li>
{{ end }}
{{ end }}
{{ end }}
</ul>
{{< /code >}}
If you restrict front matter to the TOML format, and omit quotation marks surrounding date fields, you can perform date comparisons without casting.
[`where` function]: /functions/where/
[config]: /getting-started/configuration/
{{< code file="layouts/partials/future-events.html" >}}
<h2>Future Events</h2>
<ul>
{{ range where (where site.RegularPages "Type" "events") "Params.start_date" "gt" now }}
{{ $startDate := .Params.start_date | time.Format ":date_medium" }}
<li>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> - {{ $startDate }}
</li>
{{ end }}
</ul>
{{< /code >}}
[config]: {{< relref "getting-started/configuration" >}}
[dotdoc]: https://golang.org/pkg/text/template/#hdr-Variables
[first]: /functions/first/
[front matter]: /content-management/front-matter/
[functions]: /functions/ "See the full list of Hugo's templating functions with a quick start reference guide and basic and advanced examples."
[Go html/template]: https://golang.org/pkg/html/template/ "Godocs references for Go's html templating"
[gohtmltemplate]: https://golang.org/pkg/html/template/ "Godocs references for Go's html templating"
[index]: /functions/index-function/
[math functions]: /functions/math/
[partials]: /templates/partials/ "Link to the partial templates page inside of the templating section of the Hugo docs"
[internal_templates]: /templates/internal/
[relpermalink]: /variables/page/
[safehtml]: /functions/safehtml/
[sitevars]: /variables/site/
[pagevars]: /variables/page/
[variables]: /variables/ "See the full extent of page-, site-, and other variables that Hugo make available to you in your templates."
[where]: /functions/where/
[with]: /functions/with/
[godocsindex]: https://golang.org/pkg/text/template/ "Godocs page for index function"
[param]: /functions/param/
[isset]: /functions/isset/
[first]: {{< relref "functions/first" >}}
[front matter]: {{< relref "content-management/front-matter" >}}
[functions]: {{< relref "functions" >}}
[internal templates]: {{< relref "templates/internal" >}}
[isset]: {{< relref "functions/isset" >}}
[math]: {{< relref "functions/math" >}}
[pagevars]: {{< relref "variables/page" >}}
[param]: {{< relref "functions/param" >}}
[partials]: {{< relref "templates/partials" >}}
[relpermalink]: {{< relref "variables/page#page-variables" >}}
[safehtml]: {{< relref "functions/safehtml" >}}
[sitevars]: {{< relref "variables/site" >}}
[variables]: {{< relref "variables" >}}
[with]: {{< relref "functions/with" >}}
+1 -1
View File
@@ -72,7 +72,7 @@ All the methods below, e.g. `.Site.RegularPages` can also be reached via the glo
: indicates the language currently being used to render the website. This object's attributes are set in site configurations' language definition.
.Site.LanguageCode
: a string representing the language as defined in the site configuration. This is mostly used to populate the RSS feeds with the right language code.
: a string representing the language tag as defined in the site configuration.
.Site.LanguagePrefix
: this can be used to prefix URLs to point to the correct language. It will even work when only one defined language. See also the functions [absLangURL](/functions/abslangurl/) and [relLangURL](/functions/rellangurl).
+10 -3
View File
@@ -1893,7 +1893,8 @@
"type": "application/rss+xml",
"string": "application/rss+xml",
"suffixes": [
"xml"
"xml",
"rss"
]
},
{
@@ -3880,6 +3881,12 @@
"Aliases": null,
"Examples": null
},
"Text": {
"Description": "",
"Args": null,
"Aliases": null,
"Examples": null
},
"UnsharpMask": {
"Description": "",
"Args": null,
@@ -4517,9 +4524,9 @@
"Examples": null
},
"Get": {
"Description": "Get locates the filename given in Hugo's assets filesystem\nand creates a Resource object that can be used for further transformations.",
"Description": "Get locates the filename given in Hugo's assets filesystem or downloads\na file from an URL and creates a Resource object that can be used for\nfurther transformations.\n\nFor URLs an additional argument with options can be provided.",
"Args": [
"filename"
"args"
],
"Aliases": null,
"Examples": []
+2 -2
View File
@@ -29,7 +29,7 @@
<div class="tab-content">
{{ range $langs }}
<div data-pane="{{ . }}" class="code-copy-content nt3 tab-pane {{ cond (eq . "yaml") "active" ""}}">
{{ highlight ($code | transform.Remarshal . | safeHTML) . ""}}
{{ highlight ($code | transform.Remarshal . | replaceRE `\n+` "\n" | safeHTML) . "" }}
</div>
{{ if ne ($.Get "copy") "false" }}
<button class="needs-js copy copy-toggle bg-accent-color-dark f6 absolute top-0 right-0 lh-solid hover-bg-primary-color-dark bn white ph3 pv2" title="Copy this code to your clipboard." data-clipboard-action="copy" aria-label="copy button"></button>
@@ -37,5 +37,5 @@
{{end}}
{{ end }}
</div>
</div>
+3 -2
View File
@@ -4,8 +4,9 @@
{{ range $k, $v := $funcs }}
{{ if $v.Description }}
{{ $func := printf "%s.%s" $pkg $k }}
<h2>
<a class="header-link" href="#{{ $func | anchorize | safeURL }}">
{{ $id := $func | anchorize | safeURL }}
<h2 id="{{ $id }}">
<a class="header-link" href="#{{ $id }}">
<svg class="fill-current o-60 hover-accent-color-light" height="22px" viewBox="0 0 24 24" width="22px" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/>
+4 -4
View File
@@ -3,7 +3,7 @@ publish = "public"
command = "hugo --gc --minify"
[context.production.environment]
HUGO_VERSION = "0.88.1"
HUGO_VERSION = "0.89.4"
HUGO_ENV = "production"
HUGO_ENABLEGITINFO = "true"
@@ -11,20 +11,20 @@ HUGO_ENABLEGITINFO = "true"
command = "hugo --gc --minify --enableGitInfo"
[context.split1.environment]
HUGO_VERSION = "0.88.1"
HUGO_VERSION = "0.89.4"
HUGO_ENV = "production"
[context.deploy-preview]
command = "hugo --gc --minify --buildFuture -b $DEPLOY_PRIME_URL"
[context.deploy-preview.environment]
HUGO_VERSION = "0.88.1"
HUGO_VERSION = "0.89.4"
[context.branch-deploy]
command = "hugo --gc --minify -b $DEPLOY_PRIME_URL"
[context.branch-deploy.environment]
HUGO_VERSION = "0.88.1"
HUGO_VERSION = "0.89.4"
[context.next.environment]
HUGO_ENABLEGITINFO = "true"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 145 KiB

+6 -5
View File
@@ -13,14 +13,15 @@ require (
github.com/bep/golibsass v1.0.0
github.com/bep/gowebp v0.1.0
github.com/bep/tmc v0.5.1
github.com/clbanning/mxj/v2 v2.5.5
github.com/cli/safeexec v1.0.0
github.com/disintegration/gift v1.2.1
github.com/dustin/go-humanize v1.0.0
github.com/evanw/esbuild v0.13.12
github.com/evanw/esbuild v0.14.2
github.com/fortytw2/leaktest v1.3.0
github.com/frankban/quicktest v1.14.0
github.com/fsnotify/fsnotify v1.5.1
github.com/getkin/kin-openapi v0.80.0
github.com/getkin/kin-openapi v0.85.0
github.com/ghodss/yaml v1.0.0
github.com/gobuffalo/flect v0.2.3
github.com/gobwas/glob v0.2.3
@@ -37,7 +38,7 @@ require (
github.com/mattn/go-isatty v0.0.14
github.com/miekg/mmark v1.3.6
github.com/mitchellh/hashstructure v1.1.0
github.com/mitchellh/mapstructure v1.4.2
github.com/mitchellh/mapstructure v1.4.3
github.com/muesli/smartcrop v0.3.0
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
github.com/niklasfasching/go-org v1.5.0
@@ -59,11 +60,11 @@ require (
github.com/yuin/goldmark v1.4.4
github.com/yuin/goldmark-highlighting v0.0.0-20200307114337-60d527fdb691
gocloud.dev v0.20.0
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb
golang.org/x/image v0.0.0-20211028202545-6944b10bf410
golang.org/x/net v0.0.0-20210614182718-04defd469f4e
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
golang.org/x/text v0.3.7
google.golang.org/api v0.51.0
google.golang.org/api v0.61.0
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
gopkg.in/yaml.v2 v2.4.0
)
+58 -16
View File
@@ -25,8 +25,12 @@ cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb
cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0=
cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY=
cloud.google.com/go v0.84.0/go.mod h1:RazrYuxIK6Kb7YrzzhPoLmCVzl7Sup4NrbKPg8KHSUM=
cloud.google.com/go v0.87.0 h1:8ZtzmY4a2JIO2sljMbpqkDYxA8aJQveYr3AMa+X40oc=
cloud.google.com/go v0.87.0/go.mod h1:TpDYlFy7vuLzZMMZ+B6iRiELaY7z/gJPaqbMx6mlWcY=
cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aDQ=
cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI=
cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW4=
cloud.google.com/go v0.97.0 h1:3DXvAyifywvq64LfkKaMOmkWPS1CikIQdMe2lY9vxU8=
cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE=
cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc=
@@ -95,6 +99,8 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym
github.com/GeertJohan/go.incremental v1.0.0/go.mod h1:6fAjUhbVuX1KcMD3c8TEgVUqmo4seqhv0i0kdATSkM0=
github.com/GeertJohan/go.rice v1.0.0/go.mod h1:eH6gbSOAUv07dQuZVnBmoDP8mgsM1rtixis4Tib9if0=
github.com/GoogleCloudPlatform/cloudsql-proxy v0.0.0-20191009163259-e802c2cb94ae/go.mod h1:mjwGPas4yKduTyubHvD1Atl9r1rUq8DfVy+gkVvZ+oo=
github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
@@ -139,17 +145,24 @@ github.com/bep/workers v1.0.0/go.mod h1:7kIESOB86HfR2379pwoMWNy8B50D7r99fRLUyPSN
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM=
github.com/census-instrumentation/opencensus-proto v0.2.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/census-instrumentation/opencensus-proto v0.2.1 h1:glEXhBS5PSLLv4IXzLA5yPRVX4bilULVyxxbrfOtDAk=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cheekybits/is v0.0.0-20150225183255-68e9c0620927/go.mod h1:h/aW8ynjgkuj+NQRlZcDbAbM1ORAbXjXX77sX7T289U=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/clbanning/mxj/v2 v2.5.5 h1:oT81vUeEiQQ/DcHbzSytRngP6Ky9O+L+0Bw0zSJag9E=
github.com/clbanning/mxj/v2 v2.5.5/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s=
github.com/cli/safeexec v1.0.0 h1:0VngyaIyqACHdcMNWfo6+KdUYnqEr2Sg+bSP1pdF+dI=
github.com/cli/safeexec v1.0.0/go.mod h1:Z/D4tTN8Vs5gXYHDCbaM1S/anmEDnJb1iW0+EJ5zx3Q=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403 h1:cqQfy1jclcSy/FwLjemeg3SR1yaINm74aQyupQ0Bl8M=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed h1:OZmjad4L3H8ncOIR8rnb5MREYqG8ixi5+WbeUsquF0c=
github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
@@ -182,10 +195,14 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po=
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0 h1:dulLQAYQFYtG5MTplgNGHWuV2D+OBD+Z8lmDBmbLg+s=
github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ=
github.com/envoyproxy/protoc-gen-validate v0.1.0 h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/evanw/esbuild v0.13.12 h1:q8fmywXq1vIKlbA6XSxdU9LCLzMdrsD3wfM2gz2d8JU=
github.com/evanw/esbuild v0.13.12/go.mod h1:GG+zjdi59yh3ehDn4ZWfPcATxjPDUH53iU4ZJbp7dkY=
github.com/evanw/esbuild v0.14.2 h1:vAvIfHk0SxXE6OV+LzZHnlvUk6RigWOFAl7GyS7J9tY=
github.com/evanw/esbuild v0.14.2/go.mod h1:GG+zjdi59yh3ehDn4ZWfPcATxjPDUH53iU4ZJbp7dkY=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
@@ -199,8 +216,8 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI=
github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU=
github.com/getkin/kin-openapi v0.80.0 h1:W/s5/DNnDCR8P+pYyafEWlGk4S7/AfQUWXgrRSSAzf8=
github.com/getkin/kin-openapi v0.80.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg=
github.com/getkin/kin-openapi v0.85.0 h1:vjP2gh+CpIYbgMaFYp2XUBTVDtiYAZ5f+Hxy2Yes1+A=
github.com/getkin/kin-openapi v0.85.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg=
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
@@ -300,6 +317,7 @@ github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLe
github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/subcommands v1.0.1/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
@@ -310,8 +328,10 @@ github.com/google/wire v0.4.0/go.mod h1:ngWDr9Qvq3yZA10YrxfyGELY/AFWGVpy9c1LTRi1
github.com/googleapis/gax-go v2.0.2+incompatible h1:silFMLAnr330+NRuag/VjIGF7TLp/LBrV2CJKFLWEww=
github.com/googleapis/gax-go v2.0.2+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0=
github.com/googleapis/gax-go/v2 v2.1.1 h1:dp3bWCh+PPO1zjRRiCSczJav13sBvG4UhNyVTa1KqdU=
github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/csrf v1.6.0/go.mod h1:7tSf8kmjNYr7IWDCYhd3U8Ck34iQ/Yw5CJu7bAkHEGI=
@@ -360,7 +380,6 @@ github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfC
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jstemmer/go-junit-report v0.9.1 h1:6QPYqodiu3GuPL+7mfx+NwDdp2eTkp9IfEUpgAwUN0o=
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
@@ -416,8 +435,8 @@ github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0Qu
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mitchellh/mapstructure v1.4.2 h1:6h7AQ0yhTcIsmFmnAwQls75jp2Gzs4iB8W7pjMO+rqo=
github.com/mitchellh/mapstructure v1.4.2/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mitchellh/mapstructure v1.4.3 h1:OVowDSCllw/YjdLkam3/sm7wEtOy59d8ndGgCcyj8cs=
github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
@@ -471,6 +490,8 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykE
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY=
github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
@@ -556,8 +577,9 @@ golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EH
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb h1:fqpd0EBDzlHRCjiphRR5Zo/RSWWQlWv34418dnEixWk=
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ=
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -569,7 +591,6 @@ golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRu
golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug=
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
@@ -581,7 +602,6 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -641,8 +661,11 @@ golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ
golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914 h1:3B43BWw0xEBsLZ/NO1VALz6fppU3481pik+2Ksv45z8=
golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 h1:RerP+noqYHUQ8CMRcPlC2nvTa4dcBIjegkuWdcUDuqg=
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -707,8 +730,11 @@ golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365 h1:6wSTsvPddg9gc/mVEEyk9oOAoxn+bT4Z9q1zx+4RwA4=
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881 h1:TyHqChC80pFkXWraUUf6RuB5IqFdQieMLwwCJokV2pc=
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -783,7 +809,6 @@ golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.5 h1:ouewzE6p+/VEB31YYnTbEJdi8pFqKp4P4n85vwo3DHA=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -817,8 +842,13 @@ google.golang.org/api v0.44.0/go.mod h1:EBOGZqzyhtvMDoxwS97ctnh0zUmYY6CxqXsc1Avk
google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo=
google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4=
google.golang.org/api v0.50.0/go.mod h1:4bNT5pAuq5ji4SRZm+5QIkjny9JAyVD/3gaSihNefaw=
google.golang.org/api v0.51.0 h1:SQaA2Cx57B+iPw2MBgyjEkoeMkRK2IenSGoia0U3lCk=
google.golang.org/api v0.51.0/go.mod h1:t4HdrdoNgyN5cbEfm7Lum0lcLDLiise1F8qDKX00sOU=
google.golang.org/api v0.54.0/go.mod h1:7C4bFFOvVDGXjfDTAsgGwDgAxRDeQ4X8NvUedIt6z3k=
google.golang.org/api v0.55.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE=
google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE=
google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdrMgI=
google.golang.org/api v0.61.0 h1:TXXKS1slM3b2bZNJwD5DV/Tp6/M2cLzLOLh9PjDhrw8=
google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
@@ -879,8 +909,18 @@ google.golang.org/genproto v0.0.0-20210604141403-392c879c8b08/go.mod h1:UODoCrxH
google.golang.org/genproto v0.0.0-20210608205507-b6d2f5bf0d7d/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0=
google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24=
google.golang.org/genproto v0.0.0-20210713002101-d411969a0d9a/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k=
google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea h1:8ZyCcgugUqamxp/vZSEJw9CMy7VZlSWYJLLJPi/dSDA=
google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k=
google.golang.org/genproto v0.0.0-20210728212813-7823e685a01f/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48=
google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48=
google.golang.org/genproto v0.0.0-20210813162853-db860fec028c/go.mod h1:cFeNkxwySK631ADgubI+/XFU/xp8FD5KIVV4rj8UC5w=
google.golang.org/genproto v0.0.0-20210821163610-241b8fcbd6c8/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/genproto v0.0.0-20210831024726-fe130286e0e2/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/genproto v0.0.0-20210903162649-d08c68adba83/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/genproto v0.0.0-20210909211513-a8c4777a87af/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/genproto v0.0.0-20210924002016-3dee208752a0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc=
google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1 h1:b9mVrqYfq3P4bCdaLg1qtBnPzUYgglsIdjZkL/fQVOE=
google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
@@ -904,8 +944,10 @@ google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAG
google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM=
google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM=
google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM=
google.golang.org/grpc v1.39.0 h1:Klz8I9kdtkIN6EpHHUOMLCYhTn/2WAe5a0s1hcBkdTI=
google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE=
google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE=
google.golang.org/grpc v1.40.0 h1:AGJ0Ih4mHjSeibYkFGh1dD9KJ/eOtZ93I6hoHhukQ5Q=
google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34=
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
+20 -8
View File
@@ -85,11 +85,16 @@ func FirstUpper(s string) string {
// UniqueStrings returns a new slice with any duplicates removed.
func UniqueStrings(s []string) []string {
unique := make([]string, 0, len(s))
set := map[string]interface{}{}
for _, val := range s {
if _, ok := set[val]; !ok {
for i, val := range s {
var seen bool
for j := 0; j < i; j++ {
if s[j] == val {
seen = true
break
}
}
if !seen {
unique = append(unique, val)
set[val] = val
}
}
return unique
@@ -98,12 +103,19 @@ func UniqueStrings(s []string) []string {
// UniqueStringsReuse returns a slice with any duplicates removed.
// It will modify the input slice.
func UniqueStringsReuse(s []string) []string {
set := map[string]interface{}{}
result := s[:0]
for _, val := range s {
if _, ok := set[val]; !ok {
for i, val := range s {
var seen bool
for j := 0; j < i; j++ {
if s[j] == val {
seen = true
break
}
}
if !seen {
result = append(result, val)
set[val] = val
}
}
return result
+1
View File
@@ -64,6 +64,7 @@ type FileMeta struct {
IsOrdered bool
IsSymlink bool
IsRootFile bool
IsProject bool
Watch bool
Classifier files.ContentClass
+2
View File
@@ -62,6 +62,7 @@ func NewRootMappingFs(fs afero.Fs, rms ...RootMapping) (*RootMappingFs, error) {
rm.Meta.BaseDir = rm.ToBasedir
rm.Meta.MountRoot = rm.path
rm.Meta.Module = rm.Module
rm.Meta.IsProject = rm.IsProject
meta := rm.Meta.Copy()
@@ -118,6 +119,7 @@ type RootMapping struct {
To string // The source directory or file.
ToBasedir string // The base of To. May be empty if an absolute path was provided.
Module string // The module path/ID.
IsProject bool // Whether this is a mount in the main project.
Meta *FileMeta // File metadata (lang etc.)
fi FileMetaInfo
+2 -2
View File
@@ -152,8 +152,8 @@ func TestEmbeddedPaginationTemplate(t *testing.T) {
b.AssertFileContent("public/index.html", expectedOutput)
}
expectedOutputDefaultFormat := "Pager 1\n <ul class=\"pagination pagination-default\">\n <li class=\"page-item disabled\">\n <a href=\"#\" aria-disabled=\"true\" aria-label=\"First\" class=\"page-link\" role=\"button\" tabindex=\"-1\"><span aria-hidden=\"true\">&laquo;&laquo;</span></a>\n </li>\n <li class=\"page-item disabled\">\n <a href=\"#\" aria-disabled=\"true\" aria-label=\"Previous\" class=\"page-link\" role=\"button\" tabindex=\"-1\"><span aria-hidden=\"true\">&laquo;</span></a>\n </li>\n <li class=\"page-item active\">\n <a href=\"#\" aria-current=\"page\" aria-label=\"Page 1\" class=\"page-link\" role=\"button\">1</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Page 2\" class=\"page-link\" role=\"button\">2</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/3/\" aria-label=\"Page 3\" class=\"page-link\" role=\"button\">3</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/4/\" aria-label=\"Page 4\" class=\"page-link\" role=\"button\">4</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/5/\" aria-label=\"Page 5\" class=\"page-link\" role=\"button\">5</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Next\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;</span></a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/10/\" aria-label=\"Last\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;&raquo;</span></a>\n </li>\n </ul>"
expectedOutputTerseFormat := "Pager 1\n <ul class=\"pagination pagination-terse\">\n <li class=\"page-item active\">\n <a href=\"#\" aria-current=\"page\" aria-label=\"Page 1\" class=\"page-link\" role=\"button\">1</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Page 2\" class=\"page-link\" role=\"button\">2</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/3/\" aria-label=\"Page 3\" class=\"page-link\" role=\"button\">3</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Next\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;</span></a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/10/\" aria-label=\"Last\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;&raquo;</span></a>\n </li>\n </ul>"
expectedOutputDefaultFormat := "Pager 1\n <ul class=\"pagination pagination-default\">\n <li class=\"page-item disabled\">\n <a aria-disabled=\"true\" aria-label=\"First\" class=\"page-link\" role=\"button\" tabindex=\"-1\"><span aria-hidden=\"true\">&laquo;&laquo;</span></a>\n </li>\n <li class=\"page-item disabled\">\n <a aria-disabled=\"true\" aria-label=\"Previous\" class=\"page-link\" role=\"button\" tabindex=\"-1\"><span aria-hidden=\"true\">&laquo;</span></a>\n </li>\n <li class=\"page-item active\">\n <a aria-current=\"page\" aria-label=\"Page 1\" class=\"page-link\" role=\"button\">1</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Page 2\" class=\"page-link\" role=\"button\">2</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/3/\" aria-label=\"Page 3\" class=\"page-link\" role=\"button\">3</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/4/\" aria-label=\"Page 4\" class=\"page-link\" role=\"button\">4</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/5/\" aria-label=\"Page 5\" class=\"page-link\" role=\"button\">5</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Next\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;</span></a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/10/\" aria-label=\"Last\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;&raquo;</span></a>\n </li>\n </ul>"
expectedOutputTerseFormat := "Pager 1\n <ul class=\"pagination pagination-terse\">\n <li class=\"page-item active\">\n <a aria-current=\"page\" aria-label=\"Page 1\" class=\"page-link\" role=\"button\">1</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Page 2\" class=\"page-link\" role=\"button\">2</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/3/\" aria-label=\"Page 3\" class=\"page-link\" role=\"button\">3</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Next\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;</span></a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/10/\" aria-label=\"Last\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;&raquo;</span></a>\n </li>\n </ul>"
variant := `{{ template "_internal/pagination.html" . }}`
test(variant, expectedOutputDefaultFormat)
+3 -2
View File
@@ -136,7 +136,7 @@ func (b *BaseFs) AbsProjectContentDir(filename string) (string, string, error) {
isAbs := filepath.IsAbs(filename)
for _, dir := range b.SourceFilesystems.Content.Dirs {
meta := dir.Meta()
if meta.Module != "project" {
if !meta.IsProject {
continue
}
if isAbs {
@@ -161,7 +161,7 @@ func (b *BaseFs) AbsProjectContentDir(filename string) (string, string, error) {
contentDirs := b.SourceFilesystems.Content.Dirs
for i := len(contentDirs) - 1; i >= 0; i-- {
meta := contentDirs[i].Meta()
if meta.Module == "project" {
if meta.IsProject {
return filename, filepath.Join(meta.Filename, filename), nil
}
}
@@ -645,6 +645,7 @@ func (b *sourceFilesystemsBuilder) createModFs(
To: filename,
ToBasedir: base,
Module: md.Module.Path(),
IsProject: md.isMainProject,
Meta: &hugofs.FileMeta{
Watch: md.Watch(),
Weight: mountWeight,
+7 -4
View File
@@ -701,10 +701,13 @@ Data: {{ .Site.Data }}
createSymlinks := func(baseDir, id string) {
for _, dir := range files.ComponentFolders {
c.Assert(os.Chdir(filepath.Join(baseDir, dir)), qt.IsNil)
c.Assert(os.Symlink("real", fmt.Sprintf("realsym%s", id)), qt.IsNil)
c.Assert(os.Chdir(filepath.Join(baseDir, dir, "real")), qt.IsNil)
c.Assert(os.Symlink("data.toml", fmt.Sprintf(filepath.FromSlash("datasym%s.toml"), id)), qt.IsNil)
// Issue #9119: private use language tags cannot exceed 8 characters.
if dir != "i18n" {
c.Assert(os.Chdir(filepath.Join(baseDir, dir)), qt.IsNil)
c.Assert(os.Symlink("real", fmt.Sprintf("realsym%s", id)), qt.IsNil)
c.Assert(os.Chdir(filepath.Join(baseDir, dir, "real")), qt.IsNil)
c.Assert(os.Symlink("data.toml", fmt.Sprintf(filepath.FromSlash("datasym%s.toml"), id)), qt.IsNil)
}
}
}
+142 -8
View File
@@ -17,7 +17,10 @@ import (
"bytes"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httptest"
"os"
"github.com/gohugoio/hugo/config"
@@ -35,6 +38,7 @@ import (
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/htesting"
qt "github.com/frankban/quicktest"
@@ -385,8 +389,13 @@ T1: {{ $r.Content }}
func TestResourceChainBasic(t *testing.T) {
t.Parallel()
ts := httptest.NewServer(http.FileServer(http.Dir("testdata/")))
t.Cleanup(func() {
ts.Close()
})
b := newTestSitesBuilder(t)
b.WithTemplatesAdded("index.html", `
b.WithTemplatesAdded("index.html", fmt.Sprintf(`
{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }}
{{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }}
{{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }}
@@ -403,7 +412,14 @@ FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }}
CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }}
CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }}
`)
{{ $rimg := resources.Get "%[1]s/sunset.jpg" }}
{{ $rfit := $rimg.Fit "200x200" }}
{{ $rfit2 := $rfit.Fit "100x200" }}
{{ $rimg = $rimg | fingerprint }}
SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }}
FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }}
`, ts.URL))
fs := b.Fs.Source
@@ -424,12 +440,16 @@ CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerpri
b.Build(BuildCfg{})
b.AssertFileContent("public/index.html",
`
fmt.Sprintf(`
SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587
FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200
CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css
CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o=
`)
SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587
FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200
`, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{})))
b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}")
b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}")
@@ -537,6 +557,89 @@ func TestResourceChains(t *testing.T) {
c := qt.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/css/styles1.css":
w.Header().Set("Content-Type", "text/css")
w.Write([]byte(`h1 {
font-style: bold;
}`))
return
case "/js/script1.js":
w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`))
return
case "/mydata/json1.json":
w.Write([]byte(`{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}`))
return
case "/mydata/xml1.xml":
w.Write([]byte(`
<hello>
<world>Hugo Rocks!</<world>
</hello>`))
return
case "/mydata/svg1.svg":
w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`)
w.Write([]byte(`
<svg height="100" width="100">
<path d="M1e2 1e2H3e2 2e2z"/>
</svg>`))
return
case "/mydata/html1.html":
w.Write([]byte(`
<html>
<a href=#>Cool</a>
</html>`))
return
case "/authenticated/":
if r.Header.Get("Authorization") == "Bearer abcd" {
w.Write([]byte(`Welcome`))
return
}
http.Error(w, "Forbidden", http.StatusForbidden)
return
case "/post":
if r.Method == http.MethodPost {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Write(body)
return
}
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
http.Error(w, "Not found", http.StatusNotFound)
return
}))
t.Cleanup(func() {
ts.Close()
})
tests := []struct {
name string
shouldRun func() bool
@@ -578,25 +681,53 @@ T6: {{ $bundle1.Permalink }}
[minify.tdewolff.html]
keepWhitespace = false
`)
b.WithTemplates("home.html", `
b.WithTemplates("home.html", fmt.Sprintf(`
Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }}
Min CSS Remote: {{ ( resources.Get "%[1]s/css/styles1.css" | minify ).Content }}
Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }}
Min JS Remote: {{ ( resources.Get "%[1]s/js/script1.js" | minify ).Content }}
Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }}
Min JSON Remote: {{ ( resources.Get "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }}
Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }}
Min XML Remote: {{ ( resources.Get "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }}
Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }}
Min SVG Remote: {{ ( resources.Get "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }}
Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }}
Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }}
`)
Min HTML Remote: {{ ( resources.Get "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }}
`, ts.URL))
}, func(b *sitesBuilder) {
b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`)
b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`)
b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`)
b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`)
b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`)
b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`)
b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`)
b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`)
b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`)
b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`)
b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`)
b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`)
b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`)
}},
{"remote", func() bool { return true }, func(b *sitesBuilder) {
b.WithTemplates("home.html", fmt.Sprintf(`
{{$js := resources.Get "%[1]s/js/script1.js" }}
Remote Filename: {{ $js.RelPermalink }}
{{$svg := resources.Get "%[1]s/mydata/svg1.svg" }}
Remote Content-Disposition: {{ $svg.RelPermalink }}
{{$auth := resources.Get "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }}
Remote Authorization: {{ $auth.Content }}
{{$post := resources.Get "%[1]s/post" (dict "method" "post" "body" "Request body") }}
Remote POST: {{ $post.Content }}
`, ts.URL))
}, func(b *sitesBuilder) {
b.AssertFileContent("public/index.html", `Remote Filename: /script1_`)
b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`)
b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`)
b.AssertFileContent("public/index.html", `Remote POST: Request body`)
}},
{"concat", func() bool { return true }, func(b *sitesBuilder) {
@@ -741,16 +872,19 @@ Publish 2: {{ $cssPublish2.Permalink }}
{{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }}
{{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }}
{{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }}
{{ $xml := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>You</to><from>Me</from><heading>Reminder</heading><body>Do not forget XML</body></note>" | transform.Unmarshal }}
Slogan: {{ $toml.slogan }}
CSV1: {{ $csv1 }} {{ len (index $csv1 0) }}
CSV2: {{ $csv2 }}
XML: {{ $xml.body }}
`)
}, func(b *sitesBuilder) {
b.AssertFileContent("public/index.html",
`Slogan: Hugo Rocks!`,
`[[Hugo Rocks Hugo is Fast!]] 2`,
`CSV2: [[a b c]]`,
`XML: Do not forget XML`,
)
}},
{"resources.Get", func() bool { return true }, func(b *sitesBuilder) {
+5
View File
@@ -93,6 +93,11 @@ func addTranslationFile(bundle *i18n.Bundle, r source.File) error {
lang := paths.Filename(name)
tag := language.Make(lang)
if tag == language.Und {
try := artificialLangTagPrefix + lang
_, err = language.Parse(try)
if err != nil {
return _errors.Errorf("%q %s.", try, err)
}
name = artificialLangTagPrefix + name
}
+1
View File
@@ -136,6 +136,7 @@ func (ini *Init) shouldInitialize() bool {
// Reset resets the current and all its dependencies.
func (ini *Init) Reset() {
mu := ini.init.ResetWithLock()
ini.err = nil
defer mu.Unlock()
for _, d := range ini.children {
d.Reset()
+19
View File
@@ -220,3 +220,22 @@ func TestInitBranchOrder(t *testing.T) {
c.Assert(state.V2, qt.Equals, "ABAB")
}
// See issue 7043
func TestResetError(t *testing.T) {
c := qt.New(t)
r := false
i := New().Add(func() (interface{}, error) {
if r {
return nil, nil
}
return nil, errors.New("r is false")
})
_, err := i.Do()
c.Assert(err, qt.IsNotNil)
i.Reset()
r = true
_, err = i.Do()
c.Assert(err, qt.IsNil)
}
+1 -1
View File
@@ -168,7 +168,7 @@ var (
JSONType = newMediaType("application", "json", []string{"json"})
WebAppManifestType = newMediaTypeWithMimeSuffix("application", "manifest", "json", []string{"webmanifest"})
RSSType = newMediaTypeWithMimeSuffix("application", "rss", "xml", []string{"xml"})
RSSType = newMediaTypeWithMimeSuffix("application", "rss", "xml", []string{"xml", "rss"})
XMLType = newMediaType("application", "xml", []string{"xml"})
SVGType = newMediaTypeWithMimeSuffix("image", "svg", "xml", []string{"svg"})
TextType = newMediaType("text", "plain", []string{"txt"})
+9
View File
@@ -23,6 +23,8 @@ import (
toml "github.com/pelletier/go-toml/v2"
yaml "gopkg.in/yaml.v2"
xml "github.com/clbanning/mxj/v2"
)
const (
@@ -62,7 +64,14 @@ func InterfaceToConfig(in interface{}, format metadecoders.Format, w io.Writer)
_, err = w.Write([]byte{'\n'})
return err
case metadecoders.XML:
b, err := xml.AnyXmlIndent(in, "", "\t", "root")
if err != nil {
return err
}
_, err = w.Write(b)
return err
default:
return errors.New("unsupported Format provided")
}
+20
View File
@@ -24,6 +24,7 @@ import (
"github.com/gohugoio/hugo/common/herrors"
"github.com/niklasfasching/go-org/org"
xml "github.com/clbanning/mxj/v2"
toml "github.com/pelletier/go-toml/v2"
"github.com/pkg/errors"
"github.com/spf13/afero"
@@ -135,6 +136,25 @@ func (d Decoder) UnmarshalTo(data []byte, f Format, v interface{}) error {
err = d.unmarshalORG(data, v)
case JSON:
err = json.Unmarshal(data, v)
case XML:
var xmlRoot xml.Map
xmlRoot, err = xml.NewMapXml(data)
var xmlValue map[string]interface{}
if err == nil {
xmlRootName, err := xmlRoot.Root()
if err != nil {
return toFileError(f, errors.Wrap(err, "failed to unmarshal XML"))
}
xmlValue = xmlRoot[xmlRootName].(map[string]interface{})
}
switch v := v.(type) {
case *map[string]interface{}:
*v = xmlValue
case *interface{}:
*v = xmlValue
}
case TOML:
err = toml.Unmarshal(data, v)
case YAML:
+55
View File
@@ -20,6 +20,59 @@ import (
qt "github.com/frankban/quicktest"
)
func TestUnmarshalXML(t *testing.T) {
c := qt.New(t)
xmlDoc := `<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0"
xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Example feed</title>
<link>https://example.com/</link>
<description>Example feed</description>
<generator>Hugo -- gohugo.io</generator>
<language>en-us</language>
<copyright>Example</copyright>
<lastBuildDate>Fri, 08 Jan 2021 14:44:10 +0000</lastBuildDate>
<atom:link href="https://example.com/feed.xml" rel="self" type="application/rss+xml"/>
<item>
<title>Example title</title>
<link>https://example.com/2021/11/30/example-title/</link>
<pubDate>Tue, 30 Nov 2021 15:00:00 +0000</pubDate>
<guid>https://example.com/2021/11/30/example-title/</guid>
<description>Example description</description>
</item>
</channel>
</rss>`
expect := map[string]interface{}{
"-atom": "http://www.w3.org/2005/Atom", "-version": "2.0",
"channel": map[string]interface{}{
"copyright": "Example",
"description": "Example feed",
"generator": "Hugo -- gohugo.io",
"item": map[string]interface{}{
"description": "Example description",
"guid": "https://example.com/2021/11/30/example-title/",
"link": "https://example.com/2021/11/30/example-title/",
"pubDate": "Tue, 30 Nov 2021 15:00:00 +0000",
"title": "Example title"},
"language": "en-us",
"lastBuildDate": "Fri, 08 Jan 2021 14:44:10 +0000",
"link": []interface{}{"https://example.com/", map[string]interface{}{
"-href": "https://example.com/feed.xml",
"-rel": "self",
"-type": "application/rss+xml"}},
"title": "Example feed",
}}
d := Default
m, err := d.Unmarshal([]byte(xmlDoc), XML)
c.Assert(err, qt.IsNil)
c.Assert(m, qt.DeepEquals, expect)
}
func TestUnmarshalToMap(t *testing.T) {
c := qt.New(t)
@@ -38,6 +91,7 @@ func TestUnmarshalToMap(t *testing.T) {
{"a: Easy!\nb:\n c: 2\n d: [3, 4]", YAML, map[string]interface{}{"a": "Easy!", "b": map[string]interface{}{"c": 2, "d": []interface{}{3, 4}}}},
{"a:\n true: 1\n false: 2", YAML, map[string]interface{}{"a": map[string]interface{}{"true": 1, "false": 2}}},
{`{ "a": "b" }`, JSON, expect},
{`<root><a>b</a></root>`, XML, expect},
{`#+a: b`, ORG, expect},
// errors
{`a = b`, TOML, false},
@@ -72,6 +126,7 @@ func TestUnmarshalToInterface(t *testing.T) {
{`#+DATE: <2020-06-26 Fri>`, ORG, map[string]interface{}{"date": "2020-06-26"}},
{`a = "b"`, TOML, expect},
{`a: "b"`, YAML, expect},
{`<root><a>b</a></root>`, XML, expect},
{`a,b,c`, CSV, [][]string{{"a", "b", "c"}}},
{"a: Easy!\nb:\n c: 2\n d: [3, 4]", YAML, map[string]interface{}{"a": "Easy!", "b": map[string]interface{}{"c": 2, "d": []interface{}{3, 4}}}},
// errors
+12 -4
View File
@@ -30,6 +30,7 @@ const (
TOML Format = "toml"
YAML Format = "yaml"
CSV Format = "csv"
XML Format = "xml"
)
// FormatFromString turns formatStr, typically a file extension without any ".",
@@ -51,6 +52,8 @@ func FormatFromString(formatStr string) Format {
return ORG
case "csv":
return CSV
case "xml":
return XML
}
return ""
@@ -68,27 +71,32 @@ func FormatFromMediaType(m media.Type) Format {
return ""
}
// FormatFromContentString tries to detect the format (JSON, YAML or TOML)
// FormatFromContentString tries to detect the format (JSON, YAML, TOML or XML)
// in the given string.
// It return an empty string if no format could be detected.
func (d Decoder) FormatFromContentString(data string) Format {
csvIdx := strings.IndexRune(data, d.Delimiter)
jsonIdx := strings.Index(data, "{")
yamlIdx := strings.Index(data, ":")
xmlIdx := strings.Index(data, "<")
tomlIdx := strings.Index(data, "=")
if isLowerIndexThan(csvIdx, jsonIdx, yamlIdx, tomlIdx) {
if isLowerIndexThan(csvIdx, jsonIdx, yamlIdx, xmlIdx, tomlIdx) {
return CSV
}
if isLowerIndexThan(jsonIdx, yamlIdx, tomlIdx) {
if isLowerIndexThan(jsonIdx, yamlIdx, xmlIdx, tomlIdx) {
return JSON
}
if isLowerIndexThan(yamlIdx, tomlIdx) {
if isLowerIndexThan(yamlIdx, xmlIdx, tomlIdx) {
return YAML
}
if isLowerIndexThan(xmlIdx, tomlIdx) {
return XML
}
if tomlIdx != -1 {
return TOML
}
+4
View File
@@ -30,6 +30,7 @@ func TestFormatFromString(t *testing.T) {
{"json", JSON},
{"yaml", YAML},
{"yml", YAML},
{"xml", XML},
{"toml", TOML},
{"config.toml", TOML},
{"tOMl", TOML},
@@ -48,6 +49,8 @@ func TestFormatFromMediaType(t *testing.T) {
}{
{media.JSONType, JSON},
{media.YAMLType, YAML},
{media.XMLType, XML},
{media.RSSType, XML},
{media.TOMLType, TOML},
{media.CalendarType, ""},
} {
@@ -70,6 +73,7 @@ func TestFormatFromContentString(t *testing.T) {
{`foo:"bar"`, YAML},
{`{ "foo": "bar"`, JSON},
{`a,b,c"`, CSV},
{`<foo>bar</foo>"`, XML},
{`asdfasdf`, Format("")},
{``, Format("")},
} {
+10 -67
View File
@@ -25,21 +25,11 @@ import (
var issueRe = regexp.MustCompile(`(?i)(?:Updates?|Closes?|Fix.*|See) #(\d+)`)
const (
notesChanges = "notesChanges"
templateChanges = "templateChanges"
coreChanges = "coreChanges"
outChanges = "outChanges"
otherChanges = "otherChanges"
)
type changeLog struct {
Version string
Enhancements map[string]gitInfos
Fixes map[string]gitInfos
Notes gitInfos
All gitInfos
Docs gitInfos
Version string
Notes gitInfos
All gitInfos
Docs gitInfos
// Overall stats
Repo *gitHubRepo
@@ -48,66 +38,19 @@ type changeLog struct {
}
func newChangeLog(infos, docInfos gitInfos) *changeLog {
return &changeLog{
Enhancements: make(map[string]gitInfos),
Fixes: make(map[string]gitInfos),
All: infos,
Docs: docInfos,
}
}
func (l *changeLog) addGitInfo(isFix bool, info gitInfo, category string) {
var (
infos gitInfos
found bool
segment map[string]gitInfos
)
if category == notesChanges {
l.Notes = append(l.Notes, info)
return
} else if isFix {
segment = l.Fixes
} else {
segment = l.Enhancements
log := &changeLog{
Docs: docInfos,
}
infos, found = segment[category]
if !found {
infos = gitInfos{}
}
infos = append(infos, info)
segment[category] = infos
}
func gitInfosToChangeLog(infos, docInfos gitInfos) *changeLog {
log := newChangeLog(infos, docInfos)
for _, info := range infos {
los := strings.ToLower(info.Subject)
isFix := strings.Contains(los, "fix")
category := otherChanges
// TODO(bep) improve
if regexp.MustCompile("(?i)deprecate").MatchString(los) {
category = notesChanges
} else if regexp.MustCompile("(?i)tpl|tplimpl:|layout").MatchString(los) {
category = templateChanges
} else if regexp.MustCompile("(?i)hugolib:").MatchString(los) {
category = coreChanges
} else if regexp.MustCompile("(?i)out(put)?:|media:|Output|Media").MatchString(los) {
category = outChanges
}
// Trim package prefix.
colonIdx := strings.Index(info.Subject, ":")
if colonIdx != -1 && colonIdx < (len(info.Subject)/2) {
info.Subject = info.Subject[colonIdx+1:]
if regexp.MustCompile("(?i)deprecate|note").MatchString(info.Subject) {
log.Notes = append(log.Notes, info)
}
log.All = append(log.All, info)
info.Subject = strings.TrimSpace(info.Subject)
log.addGitInfo(isFix, info, category)
}
return log
@@ -255,7 +198,7 @@ func getGitInfosBefore(ref, tag, repo, repoPath string, remote bool) (gitInfos,
}
// Ignore autogenerated commits etc. in change log. This is a regexp.
const ignoredCommits = "releaser?:|snapcraft:|Merge commit|Squashed"
const ignoredCommits = "snapcraft:|Merge commit|Squashed"
func gitLogBefore(ref, tag, repoPath string) (string, error) {
var prevTag string
+14 -140
View File
@@ -25,11 +25,10 @@ import (
"path/filepath"
"strings"
"text/template"
"time"
)
const (
issueLinkTemplate = "[#%d](https://github.com/gohugoio/hugo/issues/%d)"
issueLinkTemplate = "#%d"
linkTemplate = "[%s](%s)"
releaseNotesMarkdownTemplatePatchRelease = `
{{ if eq (len .All) 1 }}
@@ -39,9 +38,9 @@ This is a bug-fix release with a couple of important fixes.
{{ end }}
{{ range .All }}
{{- if .GitHubCommit -}}
* {{ .Subject }} {{ . | commitURL }} {{ . | authorURL }} {{ range .Issues }}{{ . | issue }}{{ end }}
* {{ .Subject }} {{ .Hash }} {{ . | authorURL }} {{ range .Issues }}{{ . | issue }} {{ end }}
{{ else -}}
* {{ .Subject }} {{ range .Issues }}{{ . | issue }}{{ end }}
* {{ .Subject }} {{ range .Issues }}{{ . | issue }} {{ end }}
{{ end -}}
{{- end }}
@@ -83,41 +82,17 @@ Hugo now has:
## Notes
{{ template "change-section" . }}
{{- end -}}
## Enhancements
{{ template "change-headers" .Enhancements -}}
## Fixes
{{ template "change-headers" .Fixes -}}
{{ define "change-headers" }}
{{ $tmplChanges := index . "templateChanges" -}}
{{- $outChanges := index . "outChanges" -}}
{{- $coreChanges := index . "coreChanges" -}}
{{- $otherChanges := index . "otherChanges" -}}
{{- with $tmplChanges -}}
### Templates
{{ with .All }}
## Changes
{{ template "change-section" . }}
{{- end -}}
{{- with $outChanges -}}
### Output
{{ template "change-section" . }}
{{- end -}}
{{- with $coreChanges -}}
### Core
{{ template "change-section" . }}
{{- end -}}
{{- with $otherChanges -}}
### Other
{{ template "change-section" . }}
{{- end -}}
{{ end }}
{{ define "change-section" }}
{{ range . }}
{{- if .GitHubCommit -}}
* {{ .Subject }} {{ . | commitURL }} {{ . | authorURL }} {{ range .Issues }}{{ . | issue }}{{ end }}
* {{ .Subject }} {{ .Hash }} {{ . | authorURL }} {{ range .Issues }}{{ . | issue }} {{ end }}
{{ else -}}
* {{ .Subject }} {{ range .Issues }}{{ . | issue }}{{ end }}
* {{ .Subject }} {{ range .Issues }}{{ . | issue }} {{ end }}
{{ end -}}
{{- end }}
{{ end }}
@@ -129,7 +104,7 @@ var templateFuncs = template.FuncMap{
return !strings.HasSuffix(c.Version, "0")
},
"issue": func(id int) string {
return fmt.Sprintf(issueLinkTemplate, id, id)
return fmt.Sprintf(issueLinkTemplate, id)
},
"commitURL": func(info gitInfo) string {
if info.GitHubCommit.HTMLURL == "" {
@@ -147,7 +122,7 @@ var templateFuncs = template.FuncMap{
func writeReleaseNotes(version string, infosMain, infosDocs gitInfos, to io.Writer) error {
client := newGitHubAPI("hugo")
changes := gitInfosToChangeLog(infosMain, infosDocs)
changes := newChangeLog(infosMain, infosDocs)
changes.Version = version
repo, err := client.fetchRepo()
if err == nil {
@@ -188,69 +163,22 @@ func fetchThemeCount() (int, error) {
return bytes.Count(b, []byte("\n")) - bytes.Count(b, []byte("#")), nil
}
func writeReleaseNotesToTmpFile(version string, infosMain, infosDocs gitInfos) (string, error) {
f, err := ioutil.TempFile("", "hugorelease")
if err != nil {
return "", err
}
func getReleaseNotesFilename(version string) string {
return filepath.FromSlash(fmt.Sprintf("temp/%s-relnotes-ready.md", version))
defer f.Close()
if err := writeReleaseNotes(version, infosMain, infosDocs, f); err != nil {
return "", err
}
return f.Name(), nil
}
func getReleaseNotesDocsTempDirAndName(version string, final bool) (string, string) {
if final {
return hugoFilepath("temp"), fmt.Sprintf("%s-relnotes-ready.md", version)
}
return hugoFilepath("temp"), fmt.Sprintf("%s-relnotes.md", version)
}
func getReleaseNotesDocsTempFilename(version string, final bool) string {
return filepath.Join(getReleaseNotesDocsTempDirAndName(version, final))
}
func (r *ReleaseHandler) releaseNotesState(version string) (releaseNotesState, error) {
docsTempPath, name := getReleaseNotesDocsTempDirAndName(version, false)
_, err := os.Stat(filepath.Join(docsTempPath, name))
if err == nil {
return releaseNotesCreated, nil
}
docsTempPath, name = getReleaseNotesDocsTempDirAndName(version, true)
_, err = os.Stat(filepath.Join(docsTempPath, name))
if err == nil {
return releaseNotesReady, nil
}
if !os.IsNotExist(err) {
return releaseNotesNone, err
}
return releaseNotesNone, nil
}
func (r *ReleaseHandler) writeReleaseNotesToTemp(version string, isPatch bool, infosMain, infosDocs gitInfos) (string, error) {
docsTempPath, name := getReleaseNotesDocsTempDirAndName(version, isPatch)
filename := getReleaseNotesFilename(version)
var w io.WriteCloser
if !r.try {
os.Mkdir(docsTempPath, os.ModePerm)
f, err := os.Create(filepath.Join(docsTempPath, name))
f, err := os.Create(filename)
if err != nil {
return "", err
}
name = f.Name()
defer f.Close()
w = f
@@ -263,59 +191,5 @@ func (r *ReleaseHandler) writeReleaseNotesToTemp(version string, isPatch bool, i
return "", err
}
return name, nil
}
func (r *ReleaseHandler) writeReleaseNotesToDocs(title, description, sourceFilename string) (string, error) {
targetFilename := "index.md"
bundleDir := strings.TrimSuffix(filepath.Base(sourceFilename), "-ready.md")
contentDir := hugoFilepath("docs/content/en/news/" + bundleDir)
targetFullFilename := filepath.Join(contentDir, targetFilename)
if r.try {
fmt.Printf("Write release notes to /docs: Bundle %q Dir: %q\n", bundleDir, contentDir)
return targetFullFilename, nil
}
if err := os.MkdirAll(contentDir, os.ModePerm); err != nil {
return "", nil
}
b, err := ioutil.ReadFile(sourceFilename)
if err != nil {
return "", err
}
f, err := os.Create(targetFullFilename)
if err != nil {
return "", err
}
defer f.Close()
fmTail := ""
if !strings.HasSuffix(title, ".0") {
// Bug fix release
fmTail = `
images:
- images/blog/hugo-bug-poster.png
`
}
if _, err := f.WriteString(fmt.Sprintf(`
---
date: %s
title: %q
description: %q
categories: ["Releases"]%s
---
`, time.Now().Format("2006-01-02"), title, description, fmTail)); err != nil {
return "", err
}
if _, err := f.Write(b); err != nil {
return "", err
}
return targetFullFilename, nil
return filename, nil
}
+6 -4
View File
@@ -26,19 +26,21 @@ import (
)
func _TestReleaseNotesWriter(t *testing.T) {
skipIfNoToken(t)
if os.Getenv("CI") != "" {
// Travis has an ancient git with no --invert-grep: https://github.com/travis-ci/travis-ci/issues/6328
t.Skip("Skip git test on CI to make Travis happy.")
t.Skip("Skip git test on CI to make Travis happy..")
}
c := qt.New(t)
var b bytes.Buffer
// TODO(bep) consider to query GitHub directly for the gitlog with author info, probably faster.
infos, err := getGitInfosBefore("HEAD", "v0.20", "hugo", "", false)
// TODO(bep) consider to query GitHub directly for the gitlog with author info, probably faster.
infos, err := getGitInfosBefore("HEAD", "v0.89.0", "hugo", "", false)
c.Assert(err, qt.IsNil)
c.Assert(writeReleaseNotes("0.21", infos, infos, &b), qt.IsNil)
c.Assert(writeReleaseNotes("0.89.0", infos, infos, &b), qt.IsNil)
fmt.Println(b.String())
}
+36 -90
View File
@@ -32,15 +32,10 @@ import (
const commitPrefix = "releaser:"
type releaseNotesState int
const (
releaseNotesNone = iota
releaseNotesCreated
releaseNotesReady
)
// ReleaseHandler provides functionality to release a new version of Hugo.
// Test this locally without doing an actual release:
// go run -tags release main.go release --skip-publish --try -r 0.90.0
// Or a variation of the above -- the skip-publish flag makes sure that any changes are performed to the local Git only.
type ReleaseHandler struct {
cliVersion string
@@ -91,6 +86,8 @@ func (r *ReleaseHandler) Run() error {
return errors.New("GITHUB_TOKEN not set, create one here with the repo scope selected: https://github.com/settings/tokens/new")
}
fmt.Printf("Start release from %q\n", wd())
newVersion, finalVersion := r.calculateVersions()
version := newVersion.String()
@@ -124,67 +121,36 @@ func (r *ReleaseHandler) Run() error {
var (
gitCommits gitInfos
gitCommitsDocs gitInfos
relNotesState releaseNotesState
)
relNotesState, err = r.releaseNotesState(version)
defer r.gitPush() // TODO(bep)
gitCommits, err = getGitInfos(changeLogFromTag, "hugo", "", !r.try)
if err != nil {
return err
}
prepareReleaseNotes := isPatch || relNotesState == releaseNotesNone
shouldRelease := isPatch || relNotesState == releaseNotesReady
defer r.gitPush() // TODO(bep)
if prepareReleaseNotes || shouldRelease {
gitCommits, err = getGitInfos(changeLogFromTag, "hugo", "", !r.try)
if err != nil {
return err
}
// TODO(bep) explicit tag?
gitCommitsDocs, err = getGitInfos("", "hugoDocs", "../hugoDocs", !r.try)
if err != nil {
return err
}
// TODO(bep) explicit tag?
gitCommitsDocs, err = getGitInfos("", "hugoDocs", "../hugoDocs", !r.try)
if err != nil {
return err
}
if relNotesState == releaseNotesCreated {
fmt.Println("Release notes created, but not ready. Rename to *-ready.md to continue ...")
return nil
releaseNotesFile, err := r.writeReleaseNotesToTemp(version, isPatch, gitCommits, gitCommitsDocs)
if err != nil {
return err
}
if prepareReleaseNotes {
releaseNotesFile, err := r.writeReleaseNotesToTemp(version, isPatch, gitCommits, gitCommitsDocs)
if err != nil {
return err
}
if _, err := r.git("add", releaseNotesFile); err != nil {
return err
}
commitMsg := fmt.Sprintf("%s Add release notes for %s", commitPrefix, newVersion)
if !isPatch {
commitMsg += "\n\nRename to *-ready.md to continue."
}
commitMsg += "\n[ci skip]"
if _, err := r.git("commit", "-m", commitMsg); err != nil {
return err
}
if _, err := r.git("add", releaseNotesFile); err != nil {
return err
}
if !shouldRelease {
fmt.Printf("Skip release ... ")
return nil
}
commitMsg := fmt.Sprintf("%s Add release notes for %s", commitPrefix, newVersion)
commitMsg += "\n[ci skip]"
// For docs, for now we assume that:
// The /docs subtree is up to date and ready to go.
// The hugoDocs/dev and hugoDocs/master must be merged manually after release.
// TODO(bep) improve this when we see how it works.
if _, err := r.git("commit", "-m", commitMsg); err != nil {
return err
}
if err := r.bumpVersions(newVersion); err != nil {
return err
@@ -194,28 +160,7 @@ func (r *ReleaseHandler) Run() error {
return err
}
releaseNotesFile := getReleaseNotesDocsTempFilename(version, true)
title, description := version, version
if isPatch {
title = "Hugo " + version + ": A couple of Bug Fixes"
description = "This version fixes a couple of bugs introduced in " + mainVersion.String() + "."
}
// Write the release notes to the docs site as well.
docFile, err := r.writeReleaseNotesToDocs(title, description, releaseNotesFile)
if err != nil {
return err
}
if _, err := r.git("add", docFile); err != nil {
return err
}
if _, err := r.git("commit", "-m", fmt.Sprintf("%s Add release notes to /docs for release of %s\n\n[ci skip]", commitPrefix, newVersion)); err != nil {
return err
}
if _, err := r.git("tag", "-a", tag, "-m", fmt.Sprintf("%s %s [ci skip]", commitPrefix, newVersion)); err != nil {
if _, err := r.git("tag", "-a", tag, "-m", fmt.Sprintf("%s %s\n\n[ci skip]", commitPrefix, newVersion)); err != nil {
return err
}
@@ -319,8 +264,8 @@ func (r *ReleaseHandler) bumpVersions(ver hugo.Version) error {
}
func (r *ReleaseHandler) replaceInFile(filename string, oldNew ...string) error {
fullFilename := hugoFilepath(filename)
fi, err := os.Stat(fullFilename)
filename = filepath.FromSlash(filename)
fi, err := os.Stat(filename)
if err != nil {
return err
}
@@ -330,7 +275,7 @@ func (r *ReleaseHandler) replaceInFile(filename string, oldNew ...string) error
return nil
}
b, err := ioutil.ReadFile(fullFilename)
b, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
@@ -341,17 +286,18 @@ func (r *ReleaseHandler) replaceInFile(filename string, oldNew ...string) error
newContent = re.ReplaceAllString(newContent, oldNew[i+1])
}
return ioutil.WriteFile(fullFilename, []byte(newContent), fi.Mode())
}
func hugoFilepath(filename string) string {
pwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
return filepath.Join(pwd, filename)
return ioutil.WriteFile(filename, []byte(newContent), fi.Mode())
}
func isCI() bool {
return os.Getenv("CI") != ""
}
func wd() string {
p, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
return p
}
+5
View File
@@ -597,6 +597,8 @@ func TestImageOperationsGolden(t *testing.T) {
c := qt.New(t)
c.Parallel()
// Note, if you're enabling this on a MacOS M1 (ARM) you need to run the test with GOARCH=amd64.
// GOARCH=amd64 go test -timeout 30s -run "^TestImageOperationsGolden$" ./resources -v
devMode := false
testImages := []string{"sunset.jpg", "gohugoio8.png", "gohugoio24.png"}
@@ -674,6 +676,9 @@ func TestImageOperationsGolden(t *testing.T) {
f.Hue(22),
f.Contrast(32.5),
f.Overlay(gopher.(images.ImageSource), 20, 30),
f.Text("No options"),
f.Text("This long text is to test line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."),
f.Text("Hugo rocks!", map[string]interface{}{"x": 3, "y": 3, "size": 20, "color": "#fc03b1"}),
}
resized, err := orig.Fill("400x200 center")
+57
View File
@@ -15,6 +15,12 @@
package images
import (
"fmt"
"github.com/gohugoio/hugo/common/hugio"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/resources/resource"
"github.com/disintegration/gift"
"github.com/spf13/cast"
)
@@ -33,6 +39,57 @@ func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter {
}
}
// Text creates a filter that draws text with the given options.
func (*Filters) Text(text string, options ...interface{}) gift.Filter {
tf := textFilter{
text: text,
color: "#ffffff",
size: 20,
x: 10,
y: 10,
linespacing: 2,
}
var opt maps.Params
if len(options) > 0 {
opt = maps.MustToParamsAndPrepare(options[0])
for option, v := range opt {
switch option {
case "color":
tf.color = cast.ToString(v)
case "size":
tf.size = cast.ToFloat64(v)
case "x":
tf.x = cast.ToInt(v)
case "y":
tf.y = cast.ToInt(v)
case "linespacing":
tf.linespacing = cast.ToInt(v)
case "font":
fontSource, ok1 := v.(hugio.ReadSeekCloserProvider)
identifier, ok2 := v.(resource.Identifier)
if !(ok1 && ok2) {
panic(fmt.Sprintf("invalid text font source: %T", v))
}
tf.fontSource = fontSource
// The input value isn't hashable and will not make a stable key.
// Replace it with a string in the map used as basis for the
// hash string.
opt["font"] = identifier.Key()
}
}
}
return filter{
Options: newFilterOpts(text, opt),
Filter: tf,
}
}
// Brightness creates a filter that changes the brightness of an image.
// The percentage parameter must be in range (-100, 100).
func (*Filters) Brightness(percentage interface{}) gift.Filter {
+108
View File
@@ -0,0 +1,108 @@
// 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 images
import (
"image"
"image/draw"
"io"
"strings"
"github.com/disintegration/gift"
"github.com/gohugoio/hugo/common/hugio"
"golang.org/x/image/font"
"golang.org/x/image/font/gofont/goregular"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
)
var _ gift.Filter = (*textFilter)(nil)
type textFilter struct {
text, color string
x, y int
size float64
linespacing int
fontSource hugio.ReadSeekCloserProvider
}
func (f textFilter) Draw(dst draw.Image, src image.Image, options *gift.Options) {
color, err := hexStringToColor(f.color)
if err != nil {
panic(err)
}
// Load and parse font
ttf := goregular.TTF
if f.fontSource != nil {
rs, err := f.fontSource.ReadSeekCloser()
if err != nil {
panic(err)
}
defer rs.Close()
ttf, err = io.ReadAll(rs)
if err != nil {
panic(err)
}
}
otf, err := opentype.Parse(ttf)
if err != nil {
panic(err)
}
// Set font options
face, err := opentype.NewFace(otf, &opentype.FaceOptions{
Size: f.size,
DPI: 72,
Hinting: font.HintingNone,
})
if err != nil {
panic(err)
}
d := font.Drawer{
Dst: dst,
Src: image.NewUniform(color),
Face: face,
}
gift.New().Draw(dst, src)
// Draw text, consider and include linebreaks
maxWidth := dst.Bounds().Dx() - 20
fontHeight := face.Metrics().Ascent.Ceil()
// Correct y position based on font and size
f.y = f.y + fontHeight
// Start position
y := f.y
d.Dot = fixed.P(f.x, f.y)
// Draw text and break line at max width
parts := strings.Fields(f.text)
for _, str := range parts {
strWith := font.MeasureString(face, str)
if (d.Dot.X.Ceil() + strWith.Ceil()) >= maxWidth {
y = y + fontHeight + f.linespacing
d.Dot = fixed.P(f.x, y)
}
d.DrawString(str + " ")
}
}
func (f textFilter) Bounds(srcBounds image.Rectangle) image.Rectangle {
return image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
}
+1 -5
View File
@@ -155,11 +155,7 @@ type OpenReadSeekCloser func() (hugio.ReadSeekCloser, error)
// ReadSeekCloserResource is a Resource that supports loading its content.
type ReadSeekCloserResource interface {
MediaType() media.Type
ReadSeekCloserProvider
}
type ReadSeekCloserProvider interface {
ReadSeekCloser() (hugio.ReadSeekCloser, error)
hugio.ReadSeekCloserProvider
}
// LengthProvider is a Resource that provides a length
+209 -2
View File
@@ -16,28 +16,53 @@
package create
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"net/http/httputil"
"net/url"
"path"
"path/filepath"
"strings"
"time"
"github.com/gohugoio/hugo/hugofs/glob"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/cache/filecache"
"github.com/gohugoio/hugo/common/hugio"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/resources"
"github.com/gohugoio/hugo/resources/resource"
"github.com/pkg/errors"
)
// Client contains methods to create Resource objects.
// tasks to Resource objects.
type Client struct {
rs *resources.Spec
rs *resources.Spec
httpClient *http.Client
cacheGetResource *filecache.Cache
}
// New creates a new Client with the given specification.
func New(rs *resources.Spec) *Client {
return &Client{rs: rs}
return &Client{
rs: rs,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
cacheGetResource: rs.FileCaches.GetResourceCache(),
}
}
// Get creates a new Resource by opening the given filename in the assets filesystem.
@@ -126,3 +151,185 @@ func (c *Client) FromString(targetPath, content string) (resource.Resource, erro
})
})
}
// FromRemote expects one or n-parts of a URL to a resource
// If you provide multiple parts they will be joined together to the final URL.
func (c *Client) FromRemote(uri string, options map[string]interface{}) (resource.Resource, error) {
rURL, err := url.Parse(uri)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri)
}
resourceID := helpers.HashString(uri, options)
_, httpResponse, err := c.cacheGetResource.GetOrCreate(resourceID, func() (io.ReadCloser, error) {
method, reqBody, err := getMethodAndBody(options)
if err != nil {
return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri)
}
req, err := http.NewRequest(method, uri, reqBody)
if err != nil {
return nil, errors.Wrapf(err, "failed to create request for resource %s", uri)
}
addDefaultHeaders(req)
if _, ok := options["headers"]; ok {
headers, err := maps.ToStringMapE(options["headers"])
if err != nil {
return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri)
}
addUserProvidedHeaders(headers, req)
}
// Workaround for https://github.com/golang/go/issues/49366
// This is the entire lifetime of the request.
ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)
defer cancel()
req = req.WithContext(ctx)
res, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode < 200 || res.StatusCode > 299 {
return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode))
}
httpResponse, err := httputil.DumpResponse(res, true)
if err != nil {
return nil, err
}
return hugio.ToReadCloser(bytes.NewReader(httpResponse)), nil
})
if err != nil {
return nil, err
}
defer httpResponse.Close()
res, err := http.ReadResponse(bufio.NewReader(httpResponse), nil)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, errors.Wrapf(err, "failed to read remote resource %s", uri)
}
filename := path.Base(rURL.Path)
if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil {
if _, ok := params["filename"]; ok {
filename = params["filename"]
}
}
var contentType string
if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 {
contentType = arr[0]
}
// If content type was not determined by header, look for a file extention
if contentType == "" {
if ext := path.Ext(filename); ext != "" {
contentType = ext
}
}
// If content type was not determined by header or file extention, try using content itself
if contentType == "" {
if ct := http.DetectContentType(body); ct != "application/octet-stream" {
if arr, _ := mime.ExtensionsByType(ct); arr != nil {
contentType = arr[0]
}
}
}
resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType
return c.rs.New(
resources.ResourceSourceDescriptor{
LazyPublish: true,
OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {
return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil
},
RelTargetFilename: filepath.Clean(resourceID),
})
}
func addDefaultHeaders(req *http.Request, accepts ...string) {
for _, accept := range accepts {
if !hasHeaderValue(req.Header, "Accept", accept) {
req.Header.Add("Accept", accept)
}
}
if !hasHeaderKey(req.Header, "User-Agent") {
req.Header.Add("User-Agent", "Hugo Static Site Generator")
}
}
func addUserProvidedHeaders(headers map[string]interface{}, req *http.Request) {
if headers == nil {
return
}
for key, val := range headers {
vals := types.ToStringSlicePreserveString(val)
for _, s := range vals {
req.Header.Add(key, s)
}
}
}
func hasHeaderValue(m http.Header, key, value string) bool {
var s []string
var ok bool
if s, ok = m[key]; !ok {
return false
}
for _, v := range s {
if v == value {
return true
}
}
return false
}
func hasHeaderKey(m http.Header, key string) bool {
_, ok := m[key]
return ok
}
func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) {
if options == nil {
return "GET", nil, nil
}
if method, ok := options["method"].(string); ok {
method = strings.ToUpper(method)
switch method {
case "GET", "DELETE", "HEAD", "OPTIONS":
return method, nil, nil
case "POST", "PUT", "PATCH":
var body []byte
if _, ok := options["body"]; ok {
switch b := options["body"].(type) {
case string:
body = []byte(b)
case []byte:
body = b
}
}
return method, bytes.NewBuffer(body), nil
}
return "", nil, fmt.Errorf("invalid HTTP method %q", method)
}
return "GET", nil, nil
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

-15
View File
@@ -1,15 +0,0 @@
This is a bug-fix release with a couple of important fixes.
* Improve error when we cannot determine content directory in "hugo new" [b8155452](https://github.com/gohugoio/hugo/commit/b8155452ac699473b6b2a34f53988dee01b4da34) [@bep](https://github.com/bep) [#9166](https://github.com/gohugoio/hugo/issues/9166)
* deps: Upgrade github.com/yuin/goldmark v1.4.3 => v1.4.4 [08552a7a](https://github.com/gohugoio/hugo/commit/08552a7a4cd1fe64efdd2f1b95142fa4295cb298) [@jmooring](https://github.com/jmooring) [#9159](https://github.com/gohugoio/hugo/issues/9159)
* commands: Make sure pollInterval is always set [fdad91fd](https://github.com/gohugoio/hugo/commit/fdad91fd96bc4636bf3a957cdddce18b66473124) [@bep](https://github.com/bep) [#9165](https://github.com/gohugoio/hugo/issues/9165)
* create: Improve archetype directory discovery and tests [5f3f6089](https://github.com/gohugoio/hugo/commit/5f3f60898cfe1c087841ec1fbd5ddc2916d0a2c6) [@bep](https://github.com/bep) [#9146](https://github.com/gohugoio/hugo/issues/9146)
* create: Add a log statement when archetype is a directory [057d02de](https://github.com/gohugoio/hugo/commit/057d02de256a3866b7044abaa4d03c69d9fedef0) [@bep](https://github.com/bep) [#9157](https://github.com/gohugoio/hugo/issues/9157)
* create: Always print "Content ... created" [43ac59da](https://github.com/gohugoio/hugo/commit/43ac59da850901cc848b35129ca7223f9f9a9b19) [@bep](https://github.com/bep) [#9157](https://github.com/gohugoio/hugo/issues/9157)
* commands: Fix missing file locking in server partial render [ab5c6990](https://github.com/gohugoio/hugo/commit/ab5c6990a55cbb11d97f857b4619b83fddda3d18) [@bep](https://github.com/bep) [#9162](https://github.com/gohugoio/hugo/issues/9162)
* modules: Improve error message [9369d13e](https://github.com/gohugoio/hugo/commit/9369d13e59ffac262944477fad3dcd2742d66288) [@davidsneighbour](https://github.com/davidsneighbour)

Some files were not shown because too many files have changed in this diff Show More