repo_name
stringclasses 2
values | pr_number
int64 2.62k
123k
| pr_title
stringlengths 8
193
| pr_description
stringlengths 0
27.9k
| author
stringlengths 3
23
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 21
28k
| filepath
stringlengths 7
174
| before_content
stringlengths 0
554M
| after_content
stringlengths 0
554M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./hugolib/page__per_output.go | // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"bytes"
"context"
"fmt"
"html/template"
"runtime/debug"
"strings"
"sync"
"unicode/utf8"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/markup/converter/hooks"
"github.com/gohugoio/hugo/markup/converter"
"github.com/gohugoio/hugo/lazy"
bp "github.com/gohugoio/hugo/bufferpool"
"github.com/gohugoio/hugo/tpl"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/resource"
)
var (
nopTargetPath = targetPathsHolder{}
nopPagePerOutput = struct {
resource.ResourceLinksProvider
page.ContentProvider
page.PageRenderProvider
page.PaginatorProvider
page.TableOfContentsProvider
page.AlternativeOutputFormatsProvider
targetPather
}{
page.NopPage,
page.NopPage,
page.NopPage,
page.NopPage,
page.NopPage,
page.NopPage,
nopTargetPath,
}
)
var pageContentOutputDependenciesID = identity.KeyValueIdentity{Key: "pageOutput", Value: "dependencies"}
func newPageContentOutput(p *pageState, po *pageOutput) (*pageContentOutput, error) {
parent := p.init
var dependencyTracker identity.Manager
if p.s.running() {
dependencyTracker = identity.NewManager(pageContentOutputDependenciesID)
}
cp := &pageContentOutput{
dependencyTracker: dependencyTracker,
p: p,
f: po.f,
renderHooks: &renderHooks{},
}
initContent := func() (err error) {
p.s.h.IncrContentRender()
if p.cmap == nil {
// Nothing to do.
return nil
}
defer func() {
// See https://github.com/gohugoio/hugo/issues/6210
if r := recover(); r != nil {
err = fmt.Errorf("%s", r)
p.s.Log.Errorf("[BUG] Got panic:\n%s\n%s", r, string(debug.Stack()))
}
}()
if err := po.initRenderHooks(); err != nil {
return err
}
var hasShortcodeVariants bool
f := po.f
cp.contentPlaceholders, hasShortcodeVariants, err = p.shortcodeState.renderShortcodesForPage(p, f)
if err != nil {
return err
}
enableReuse := !(hasShortcodeVariants || cp.renderHooksHaveVariants)
if enableReuse {
// Reuse this for the other output formats.
// We may improve on this, but we really want to avoid re-rendering the content
// to all output formats.
// The current rule is that if you need output format-aware shortcodes or
// content rendering hooks, create a output format-specific template, e.g.
// myshortcode.amp.html.
cp.enableReuse()
}
cp.workContent = p.contentToRender(cp.contentPlaceholders)
isHTML := cp.p.m.markup == "html"
if !isHTML {
r, err := cp.renderContent(cp.workContent, true)
if err != nil {
return err
}
cp.workContent = r.Bytes()
if tocProvider, ok := r.(converter.TableOfContentsProvider); ok {
cfg := p.s.ContentSpec.Converters.GetMarkupConfig()
cp.tableOfContents = template.HTML(
tocProvider.TableOfContents().ToHTML(
cfg.TableOfContents.StartLevel,
cfg.TableOfContents.EndLevel,
cfg.TableOfContents.Ordered,
),
)
} else {
tmpContent, tmpTableOfContents := helpers.ExtractTOC(cp.workContent)
cp.tableOfContents = helpers.BytesToHTML(tmpTableOfContents)
cp.workContent = tmpContent
}
}
if cp.placeholdersEnabled {
// ToC was accessed via .Page.TableOfContents in the shortcode,
// at a time when the ToC wasn't ready.
cp.contentPlaceholders[tocShortcodePlaceholder] = string(cp.tableOfContents)
}
if p.cmap.hasNonMarkdownShortcode || cp.placeholdersEnabled {
// There are one or more replacement tokens to be replaced.
cp.workContent, err = replaceShortcodeTokens(cp.workContent, cp.contentPlaceholders)
if err != nil {
return err
}
}
if cp.p.source.hasSummaryDivider {
if isHTML {
src := p.source.parsed.Input()
// Use the summary sections as they are provided by the user.
if p.source.posSummaryEnd != -1 {
cp.summary = helpers.BytesToHTML(src[p.source.posMainContent:p.source.posSummaryEnd])
}
if cp.p.source.posBodyStart != -1 {
cp.workContent = src[cp.p.source.posBodyStart:]
}
} else {
summary, content, err := splitUserDefinedSummaryAndContent(cp.p.m.markup, cp.workContent)
if err != nil {
cp.p.s.Log.Errorf("Failed to set user defined summary for page %q: %s", cp.p.pathOrTitle(), err)
} else {
cp.workContent = content
cp.summary = helpers.BytesToHTML(summary)
}
}
} else if cp.p.m.summary != "" {
b, err := cp.renderContent([]byte(cp.p.m.summary), false)
if err != nil {
return err
}
html := cp.p.s.ContentSpec.TrimShortHTML(b.Bytes())
cp.summary = helpers.BytesToHTML(html)
}
cp.content = helpers.BytesToHTML(cp.workContent)
return nil
}
// Recursive loops can only happen in content files with template code (shortcodes etc.)
// Avoid creating new goroutines if we don't have to.
needTimeout := p.shortcodeState.hasShortcodes() || cp.renderHooks != nil
if needTimeout {
cp.initMain = parent.BranchWithTimeout(p.s.siteCfg.timeout, func(ctx context.Context) (interface{}, error) {
return nil, initContent()
})
} else {
cp.initMain = parent.Branch(func() (interface{}, error) {
return nil, initContent()
})
}
cp.initPlain = cp.initMain.Branch(func() (interface{}, error) {
cp.plain = helpers.StripHTML(string(cp.content))
cp.plainWords = strings.Fields(cp.plain)
cp.setWordCounts(p.m.isCJKLanguage)
if err := cp.setAutoSummary(); err != nil {
return err, nil
}
return nil, nil
})
return cp, nil
}
type renderHooks struct {
hooks *hooks.Renderers
init sync.Once
}
// pageContentOutput represents the Page content for a given output format.
type pageContentOutput struct {
f output.Format
// If we can reuse this for other output formats.
reuse bool
reuseInit sync.Once
p *pageState
// Lazy load dependencies
initMain *lazy.Init
initPlain *lazy.Init
placeholdersEnabled bool
placeholdersEnabledInit sync.Once
renderHooks *renderHooks
// Set if there are more than one output format variant
renderHooksHaveVariants bool // TODO(bep) reimplement this in another way, consolidate with shortcodes
// Content state
workContent []byte
dependencyTracker identity.Manager // Set in server mode.
// Temporary storage of placeholders mapped to their content.
// These are shortcodes etc. Some of these will need to be replaced
// after any markup is rendered, so they share a common prefix.
contentPlaceholders map[string]string
// Content sections
content template.HTML
summary template.HTML
tableOfContents template.HTML
truncated bool
plainWords []string
plain string
fuzzyWordCount int
wordCount int
readingTime int
}
func (p *pageContentOutput) trackDependency(id identity.Provider) {
if p.dependencyTracker != nil {
p.dependencyTracker.Add(id)
}
}
func (p *pageContentOutput) Reset() {
if p.dependencyTracker != nil {
p.dependencyTracker.Reset()
}
p.initMain.Reset()
p.initPlain.Reset()
p.renderHooks = &renderHooks{}
}
func (p *pageContentOutput) Content() (interface{}, error) {
if p.p.s.initInit(p.initMain, p.p) {
return p.content, nil
}
return nil, nil
}
func (p *pageContentOutput) FuzzyWordCount() int {
p.p.s.initInit(p.initPlain, p.p)
return p.fuzzyWordCount
}
func (p *pageContentOutput) Len() int {
p.p.s.initInit(p.initMain, p.p)
return len(p.content)
}
func (p *pageContentOutput) Plain() string {
p.p.s.initInit(p.initPlain, p.p)
return p.plain
}
func (p *pageContentOutput) PlainWords() []string {
p.p.s.initInit(p.initPlain, p.p)
return p.plainWords
}
func (p *pageContentOutput) ReadingTime() int {
p.p.s.initInit(p.initPlain, p.p)
return p.readingTime
}
func (p *pageContentOutput) Summary() template.HTML {
p.p.s.initInit(p.initMain, p.p)
if !p.p.source.hasSummaryDivider {
p.p.s.initInit(p.initPlain, p.p)
}
return p.summary
}
func (p *pageContentOutput) TableOfContents() template.HTML {
p.p.s.initInit(p.initMain, p.p)
return p.tableOfContents
}
func (p *pageContentOutput) Truncated() bool {
if p.p.truncated {
return true
}
p.p.s.initInit(p.initPlain, p.p)
return p.truncated
}
func (p *pageContentOutput) WordCount() int {
p.p.s.initInit(p.initPlain, p.p)
return p.wordCount
}
func (p *pageContentOutput) setAutoSummary() error {
if p.p.source.hasSummaryDivider || p.p.m.summary != "" {
return nil
}
var summary string
var truncated bool
if p.p.m.isCJKLanguage {
summary, truncated = p.p.s.ContentSpec.TruncateWordsByRune(p.plainWords)
} else {
summary, truncated = p.p.s.ContentSpec.TruncateWordsToWholeSentence(p.plain)
}
p.summary = template.HTML(summary)
p.truncated = truncated
return nil
}
func (cp *pageContentOutput) renderContent(content []byte, renderTOC bool) (converter.Result, error) {
c := cp.p.getContentConverter()
return cp.renderContentWithConverter(c, content, renderTOC)
}
func (cp *pageContentOutput) renderContentWithConverter(c converter.Converter, content []byte, renderTOC bool) (converter.Result, error) {
r, err := c.Convert(
converter.RenderContext{
Src: content,
RenderTOC: renderTOC,
RenderHooks: cp.renderHooks.hooks,
})
if err == nil {
if ids, ok := r.(identity.IdentitiesProvider); ok {
for _, v := range ids.GetIdentities() {
cp.trackDependency(v)
}
}
}
return r, err
}
func (p *pageContentOutput) setWordCounts(isCJKLanguage bool) {
if isCJKLanguage {
p.wordCount = 0
for _, word := range p.plainWords {
runeCount := utf8.RuneCountInString(word)
if len(word) == runeCount {
p.wordCount++
} else {
p.wordCount += runeCount
}
}
} else {
p.wordCount = helpers.TotalWords(p.plain)
}
// TODO(bep) is set in a test. Fix that.
if p.fuzzyWordCount == 0 {
p.fuzzyWordCount = (p.wordCount + 100) / 100 * 100
}
if isCJKLanguage {
p.readingTime = (p.wordCount + 500) / 501
} else {
p.readingTime = (p.wordCount + 212) / 213
}
}
// A callback to signal that we have inserted a placeholder into the rendered
// content. This avoids doing extra replacement work.
func (p *pageContentOutput) enablePlaceholders() {
p.placeholdersEnabledInit.Do(func() {
p.placeholdersEnabled = true
})
}
func (p *pageContentOutput) enableReuse() {
p.reuseInit.Do(func() {
p.reuse = true
})
}
// these will be shifted out when rendering a given output format.
type pagePerOutputProviders interface {
targetPather
page.PaginatorProvider
resource.ResourceLinksProvider
}
type targetPather interface {
targetPaths() page.TargetPaths
}
type targetPathsHolder struct {
paths page.TargetPaths
page.OutputFormat
}
func (t targetPathsHolder) targetPaths() page.TargetPaths {
return t.paths
}
func executeToString(h tpl.TemplateHandler, templ tpl.Template, data interface{}) (string, error) {
b := bp.GetBuffer()
defer bp.PutBuffer(b)
if err := h.Execute(templ, b, data); err != nil {
return "", err
}
return b.String(), nil
}
func splitUserDefinedSummaryAndContent(markup string, c []byte) (summary []byte, content []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("summary split failed: %s", r)
}
}()
startDivider := bytes.Index(c, internalSummaryDividerBaseBytes)
if startDivider == -1 {
return
}
startTag := "p"
switch markup {
case "asciidocext":
startTag = "div"
}
// Walk back and forward to the surrounding tags.
start := bytes.LastIndex(c[:startDivider], []byte("<"+startTag))
end := bytes.Index(c[startDivider:], []byte("</"+startTag))
if start == -1 {
start = startDivider
} else {
start = startDivider - (startDivider - start)
}
if end == -1 {
end = startDivider + len(internalSummaryDividerBase)
} else {
end = startDivider + end + len(startTag) + 3
}
var addDiv bool
switch markup {
case "rst":
addDiv = true
}
withoutDivider := append(c[:start], bytes.Trim(c[end:], "\n")...)
if len(withoutDivider) > 0 {
summary = bytes.TrimSpace(withoutDivider[:start])
}
if addDiv {
// For the rst
summary = append(append([]byte(nil), summary...), []byte("</div>")...)
}
if err != nil {
return
}
content = bytes.TrimSpace(withoutDivider)
return
}
| // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"bytes"
"context"
"fmt"
"html/template"
"runtime/debug"
"strings"
"sync"
"unicode/utf8"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/markup/converter/hooks"
"github.com/gohugoio/hugo/markup/converter"
"github.com/gohugoio/hugo/lazy"
bp "github.com/gohugoio/hugo/bufferpool"
"github.com/gohugoio/hugo/tpl"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/resource"
)
var (
nopTargetPath = targetPathsHolder{}
nopPagePerOutput = struct {
resource.ResourceLinksProvider
page.ContentProvider
page.PageRenderProvider
page.PaginatorProvider
page.TableOfContentsProvider
page.AlternativeOutputFormatsProvider
targetPather
}{
page.NopPage,
page.NopPage,
page.NopPage,
page.NopPage,
page.NopPage,
page.NopPage,
nopTargetPath,
}
)
var pageContentOutputDependenciesID = identity.KeyValueIdentity{Key: "pageOutput", Value: "dependencies"}
func newPageContentOutput(p *pageState, po *pageOutput) (*pageContentOutput, error) {
parent := p.init
var dependencyTracker identity.Manager
if p.s.running() {
dependencyTracker = identity.NewManager(pageContentOutputDependenciesID)
}
cp := &pageContentOutput{
dependencyTracker: dependencyTracker,
p: p,
f: po.f,
renderHooks: &renderHooks{},
}
initContent := func() (err error) {
p.s.h.IncrContentRender()
if p.cmap == nil {
// Nothing to do.
return nil
}
defer func() {
// See https://github.com/gohugoio/hugo/issues/6210
if r := recover(); r != nil {
err = fmt.Errorf("%s", r)
p.s.Log.Errorf("[BUG] Got panic:\n%s\n%s", r, string(debug.Stack()))
}
}()
if err := po.initRenderHooks(); err != nil {
return err
}
var hasShortcodeVariants bool
f := po.f
cp.contentPlaceholders, hasShortcodeVariants, err = p.shortcodeState.renderShortcodesForPage(p, f)
if err != nil {
return err
}
enableReuse := !(hasShortcodeVariants || cp.renderHooksHaveVariants)
if enableReuse {
// Reuse this for the other output formats.
// We may improve on this, but we really want to avoid re-rendering the content
// to all output formats.
// The current rule is that if you need output format-aware shortcodes or
// content rendering hooks, create a output format-specific template, e.g.
// myshortcode.amp.html.
cp.enableReuse()
}
cp.workContent = p.contentToRender(cp.contentPlaceholders)
isHTML := cp.p.m.markup == "html"
if !isHTML {
r, err := cp.renderContent(cp.workContent, true)
if err != nil {
return err
}
cp.workContent = r.Bytes()
if tocProvider, ok := r.(converter.TableOfContentsProvider); ok {
cfg := p.s.ContentSpec.Converters.GetMarkupConfig()
cp.tableOfContents = template.HTML(
tocProvider.TableOfContents().ToHTML(
cfg.TableOfContents.StartLevel,
cfg.TableOfContents.EndLevel,
cfg.TableOfContents.Ordered,
),
)
} else {
tmpContent, tmpTableOfContents := helpers.ExtractTOC(cp.workContent)
cp.tableOfContents = helpers.BytesToHTML(tmpTableOfContents)
cp.workContent = tmpContent
}
}
if cp.placeholdersEnabled {
// ToC was accessed via .Page.TableOfContents in the shortcode,
// at a time when the ToC wasn't ready.
cp.contentPlaceholders[tocShortcodePlaceholder] = string(cp.tableOfContents)
}
if p.cmap.hasNonMarkdownShortcode || cp.placeholdersEnabled {
// There are one or more replacement tokens to be replaced.
cp.workContent, err = replaceShortcodeTokens(cp.workContent, cp.contentPlaceholders)
if err != nil {
return err
}
}
if cp.p.source.hasSummaryDivider {
if isHTML {
src := p.source.parsed.Input()
// Use the summary sections as they are provided by the user.
if p.source.posSummaryEnd != -1 {
cp.summary = helpers.BytesToHTML(src[p.source.posMainContent:p.source.posSummaryEnd])
}
if cp.p.source.posBodyStart != -1 {
cp.workContent = src[cp.p.source.posBodyStart:]
}
} else {
summary, content, err := splitUserDefinedSummaryAndContent(cp.p.m.markup, cp.workContent)
if err != nil {
cp.p.s.Log.Errorf("Failed to set user defined summary for page %q: %s", cp.p.pathOrTitle(), err)
} else {
cp.workContent = content
cp.summary = helpers.BytesToHTML(summary)
}
}
} else if cp.p.m.summary != "" {
b, err := cp.renderContent([]byte(cp.p.m.summary), false)
if err != nil {
return err
}
html := cp.p.s.ContentSpec.TrimShortHTML(b.Bytes())
cp.summary = helpers.BytesToHTML(html)
}
cp.content = helpers.BytesToHTML(cp.workContent)
return nil
}
// Recursive loops can only happen in content files with template code (shortcodes etc.)
// Avoid creating new goroutines if we don't have to.
needTimeout := p.shortcodeState.hasShortcodes() || cp.renderHooks != nil
if needTimeout {
cp.initMain = parent.BranchWithTimeout(p.s.siteCfg.timeout, func(ctx context.Context) (interface{}, error) {
return nil, initContent()
})
} else {
cp.initMain = parent.Branch(func() (interface{}, error) {
return nil, initContent()
})
}
cp.initPlain = cp.initMain.Branch(func() (interface{}, error) {
cp.plain = helpers.StripHTML(string(cp.content))
cp.plainWords = strings.Fields(cp.plain)
cp.setWordCounts(p.m.isCJKLanguage)
if err := cp.setAutoSummary(); err != nil {
return err, nil
}
return nil, nil
})
return cp, nil
}
type renderHooks struct {
hooks *hooks.Renderers
init sync.Once
}
// pageContentOutput represents the Page content for a given output format.
type pageContentOutput struct {
f output.Format
// If we can reuse this for other output formats.
reuse bool
reuseInit sync.Once
p *pageState
// Lazy load dependencies
initMain *lazy.Init
initPlain *lazy.Init
placeholdersEnabled bool
placeholdersEnabledInit sync.Once
renderHooks *renderHooks
// Set if there are more than one output format variant
renderHooksHaveVariants bool // TODO(bep) reimplement this in another way, consolidate with shortcodes
// Content state
workContent []byte
dependencyTracker identity.Manager // Set in server mode.
// Temporary storage of placeholders mapped to their content.
// These are shortcodes etc. Some of these will need to be replaced
// after any markup is rendered, so they share a common prefix.
contentPlaceholders map[string]string
// Content sections
content template.HTML
summary template.HTML
tableOfContents template.HTML
truncated bool
plainWords []string
plain string
fuzzyWordCount int
wordCount int
readingTime int
}
func (p *pageContentOutput) trackDependency(id identity.Provider) {
if p.dependencyTracker != nil {
p.dependencyTracker.Add(id)
}
}
func (p *pageContentOutput) Reset() {
if p.dependencyTracker != nil {
p.dependencyTracker.Reset()
}
p.initMain.Reset()
p.initPlain.Reset()
p.renderHooks = &renderHooks{}
}
func (p *pageContentOutput) Content() (interface{}, error) {
if p.p.s.initInit(p.initMain, p.p) {
return p.content, nil
}
return nil, nil
}
func (p *pageContentOutput) FuzzyWordCount() int {
p.p.s.initInit(p.initPlain, p.p)
return p.fuzzyWordCount
}
func (p *pageContentOutput) Len() int {
p.p.s.initInit(p.initMain, p.p)
return len(p.content)
}
func (p *pageContentOutput) Plain() string {
p.p.s.initInit(p.initPlain, p.p)
return p.plain
}
func (p *pageContentOutput) PlainWords() []string {
p.p.s.initInit(p.initPlain, p.p)
return p.plainWords
}
func (p *pageContentOutput) ReadingTime() int {
p.p.s.initInit(p.initPlain, p.p)
return p.readingTime
}
func (p *pageContentOutput) Summary() template.HTML {
p.p.s.initInit(p.initMain, p.p)
if !p.p.source.hasSummaryDivider {
p.p.s.initInit(p.initPlain, p.p)
}
return p.summary
}
func (p *pageContentOutput) TableOfContents() template.HTML {
p.p.s.initInit(p.initMain, p.p)
return p.tableOfContents
}
func (p *pageContentOutput) Truncated() bool {
if p.p.truncated {
return true
}
p.p.s.initInit(p.initPlain, p.p)
return p.truncated
}
func (p *pageContentOutput) WordCount() int {
p.p.s.initInit(p.initPlain, p.p)
return p.wordCount
}
func (p *pageContentOutput) setAutoSummary() error {
if p.p.source.hasSummaryDivider || p.p.m.summary != "" {
return nil
}
var summary string
var truncated bool
if p.p.m.isCJKLanguage {
summary, truncated = p.p.s.ContentSpec.TruncateWordsByRune(p.plainWords)
} else {
summary, truncated = p.p.s.ContentSpec.TruncateWordsToWholeSentence(p.plain)
}
p.summary = template.HTML(summary)
p.truncated = truncated
return nil
}
func (cp *pageContentOutput) renderContent(content []byte, renderTOC bool) (converter.Result, error) {
c := cp.p.getContentConverter()
return cp.renderContentWithConverter(c, content, renderTOC)
}
func (cp *pageContentOutput) renderContentWithConverter(c converter.Converter, content []byte, renderTOC bool) (converter.Result, error) {
r, err := c.Convert(
converter.RenderContext{
Src: content,
RenderTOC: renderTOC,
RenderHooks: cp.renderHooks.hooks,
})
if err == nil {
if ids, ok := r.(identity.IdentitiesProvider); ok {
for _, v := range ids.GetIdentities() {
cp.trackDependency(v)
}
}
}
return r, err
}
func (p *pageContentOutput) setWordCounts(isCJKLanguage bool) {
if isCJKLanguage {
p.wordCount = 0
for _, word := range p.plainWords {
runeCount := utf8.RuneCountInString(word)
if len(word) == runeCount {
p.wordCount++
} else {
p.wordCount += runeCount
}
}
} else {
p.wordCount = helpers.TotalWords(p.plain)
}
// TODO(bep) is set in a test. Fix that.
if p.fuzzyWordCount == 0 {
p.fuzzyWordCount = (p.wordCount + 100) / 100 * 100
}
if isCJKLanguage {
p.readingTime = (p.wordCount + 500) / 501
} else {
p.readingTime = (p.wordCount + 212) / 213
}
}
// A callback to signal that we have inserted a placeholder into the rendered
// content. This avoids doing extra replacement work.
func (p *pageContentOutput) enablePlaceholders() {
p.placeholdersEnabledInit.Do(func() {
p.placeholdersEnabled = true
})
}
func (p *pageContentOutput) enableReuse() {
p.reuseInit.Do(func() {
p.reuse = true
})
}
// these will be shifted out when rendering a given output format.
type pagePerOutputProviders interface {
targetPather
page.PaginatorProvider
resource.ResourceLinksProvider
}
type targetPather interface {
targetPaths() page.TargetPaths
}
type targetPathsHolder struct {
paths page.TargetPaths
page.OutputFormat
}
func (t targetPathsHolder) targetPaths() page.TargetPaths {
return t.paths
}
func executeToString(h tpl.TemplateHandler, templ tpl.Template, data interface{}) (string, error) {
b := bp.GetBuffer()
defer bp.PutBuffer(b)
if err := h.Execute(templ, b, data); err != nil {
return "", err
}
return b.String(), nil
}
func splitUserDefinedSummaryAndContent(markup string, c []byte) (summary []byte, content []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("summary split failed: %s", r)
}
}()
startDivider := bytes.Index(c, internalSummaryDividerBaseBytes)
if startDivider == -1 {
return
}
startTag := "p"
switch markup {
case "asciidocext":
startTag = "div"
}
// Walk back and forward to the surrounding tags.
start := bytes.LastIndex(c[:startDivider], []byte("<"+startTag))
end := bytes.Index(c[startDivider:], []byte("</"+startTag))
if start == -1 {
start = startDivider
} else {
start = startDivider - (startDivider - start)
}
if end == -1 {
end = startDivider + len(internalSummaryDividerBase)
} else {
end = startDivider + end + len(startTag) + 3
}
var addDiv bool
switch markup {
case "rst":
addDiv = true
}
withoutDivider := append(c[:start], bytes.Trim(c[end:], "\n")...)
if len(withoutDivider) > 0 {
summary = bytes.TrimSpace(withoutDivider[:start])
}
if addDiv {
// For the rst
summary = append(append([]byte(nil), summary...), []byte("</div>")...)
}
if err != nil {
return
}
content = bytes.TrimSpace(withoutDivider)
return
}
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./docs/content/en/functions/path.Base.md | ---
title: path.Base
description: Base returns the last element of a path.
godocref:
date: 2018-11-28
publishdate: 2018-11-28
lastmod: 2018-11-28
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [path, base]
signature: ["path.Base PATH"]
workson: []
hugoversion: "0.40"
relatedfuncs: [path.Dir, path.Ext, path.Split]
deprecated: false
---
`path.Base` returns the last element of `PATH`.
If `PATH` is empty, `.` is returned.
**Note:** On Windows, `PATH` is converted to slash (`/`) separators.
```
{{ path.Base "a/news.html" }} → "news.html"
{{ path.Base "news.html" }} → "news.html"
{{ path.Base "a/b/c" }} → "c"
{{ path.Base "/x/y/z/" }} → "z"
```
| ---
title: path.Base
description: Base returns the last element of a path.
godocref:
date: 2018-11-28
publishdate: 2018-11-28
lastmod: 2018-11-28
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [path, base]
signature: ["path.Base PATH"]
workson: []
hugoversion: "0.40"
relatedfuncs: [path.Dir, path.Ext, path.Split]
deprecated: false
---
`path.Base` returns the last element of `PATH`.
If `PATH` is empty, `.` is returned.
**Note:** On Windows, `PATH` is converted to slash (`/`) separators.
```
{{ path.Base "a/news.html" }} → "news.html"
{{ path.Base "news.html" }} → "news.html"
{{ path.Base "a/b/c" }} → "c"
{{ path.Base "/x/y/z/" }} → "z"
```
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./hugolib/page_permalink_test.go | // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"fmt"
"html/template"
"path/filepath"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps"
)
func TestPermalink(t *testing.T) {
t.Parallel()
tests := []struct {
file string
base template.URL
slug string
url string
uglyURLs bool
canonifyURLs bool
expectedAbs string
expectedRel string
}{
{"x/y/z/boofar.md", "", "", "", false, false, "/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "", "", "", false, false, "/x/y/z/boofar/", "/x/y/z/boofar/"},
// Issue #1174
{"x/y/z/boofar.md", "http://gopher.com/", "", "", false, true, "http://gopher.com/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "http://gopher.com/", "", "", true, true, "http://gopher.com/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "", "boofar", "", false, false, "/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "http://barnew/", "", "", false, false, "http://barnew/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "http://barnew/", "boofar", "", false, false, "http://barnew/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "", "", "", true, false, "/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "", "", "", true, false, "/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "", "boofar", "", true, false, "/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "http://barnew/", "", "", true, false, "http://barnew/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "http://barnew/", "boofar", "", true, false, "http://barnew/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", true, false, "http://barnew/boo/x/y/z/booslug.html", "/boo/x/y/z/booslug.html"},
{"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", false, true, "http://barnew/boo/x/y/z/booslug/", "/x/y/z/booslug/"},
{"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", false, false, "http://barnew/boo/x/y/z/booslug/", "/boo/x/y/z/booslug/"},
{"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", true, true, "http://barnew/boo/x/y/z/booslug.html", "/x/y/z/booslug.html"},
{"x/y/z/boofar.md", "http://barnew/boo", "booslug", "", true, true, "http://barnew/boo/x/y/z/booslug.html", "/x/y/z/booslug.html"},
// Issue #4666
{"x/y/z/boo-makeindex.md", "http://barnew/boo", "", "", true, true, "http://barnew/boo/x/y/z/boo-makeindex.html", "/x/y/z/boo-makeindex.html"},
// test URL overrides
{"x/y/z/boofar.md", "", "", "/z/y/q/", false, false, "/z/y/q/", "/z/y/q/"},
}
for i, test := range tests {
test := test
t.Run(fmt.Sprintf("%s-%d", test.file, i), func(t *testing.T) {
t.Parallel()
c := qt.New(t)
cfg, fs := newTestCfg()
cfg.Set("uglyURLs", test.uglyURLs)
cfg.Set("canonifyURLs", test.canonifyURLs)
cfg.Set("baseURL", test.base)
pageContent := fmt.Sprintf(`---
title: Page
slug: %q
url: %q
output: ["HTML"]
---
Content
`, test.slug, test.url)
writeSource(t, fs, filepath.Join("content", filepath.FromSlash(test.file)), pageContent)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0]
u := p.Permalink()
expected := test.expectedAbs
if u != expected {
t.Fatalf("[%d] Expected abs url: %s, got: %s", i, expected, u)
}
u = p.RelPermalink()
expected = test.expectedRel
if u != expected {
t.Errorf("[%d] Expected rel url: %s, got: %s", i, expected, u)
}
})
}
}
func TestRelativeURLInFrontMatter(t *testing.T) {
config := `
baseURL = "https://example.com"
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = false
[Languages]
[Languages.en]
weight = 10
contentDir = "content/en"
[Languages.nn]
weight = 20
contentDir = "content/nn"
`
pageTempl := `---
title: "A page"
url: %q
---
Some content.
`
b := newTestSitesBuilder(t).WithConfigFile("toml", config)
b.WithContent("content/en/blog/page1.md", fmt.Sprintf(pageTempl, "myblog/p1/"))
b.WithContent("content/en/blog/page2.md", fmt.Sprintf(pageTempl, "../../../../../myblog/p2/"))
b.WithContent("content/en/blog/page3.md", fmt.Sprintf(pageTempl, "../myblog/../myblog/p3/"))
b.WithContent("content/en/blog/_index.md", fmt.Sprintf(pageTempl, "this-is-my-english-blog"))
b.WithContent("content/nn/blog/page1.md", fmt.Sprintf(pageTempl, "myblog/p1/"))
b.WithContent("content/nn/blog/_index.md", fmt.Sprintf(pageTempl, "this-is-my-blog"))
b.Build(BuildCfg{})
b.AssertFileContent("public/nn/myblog/p1/index.html", "Single: A page|Hello|nn|RelPermalink: /nn/myblog/p1/|")
b.AssertFileContent("public/nn/this-is-my-blog/index.html", "List Page 1|A page|Hello|https://example.com/nn/this-is-my-blog/|")
b.AssertFileContent("public/this-is-my-english-blog/index.html", "List Page 1|A page|Hello|https://example.com/this-is-my-english-blog/|")
b.AssertFileContent("public/myblog/p1/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p1/|Permalink: https://example.com/myblog/p1/|")
b.AssertFileContent("public/myblog/p2/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p2/|Permalink: https://example.com/myblog/p2/|")
b.AssertFileContent("public/myblog/p3/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p3/|Permalink: https://example.com/myblog/p3/|")
}
| // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"fmt"
"html/template"
"path/filepath"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps"
)
func TestPermalink(t *testing.T) {
t.Parallel()
tests := []struct {
file string
base template.URL
slug string
url string
uglyURLs bool
canonifyURLs bool
expectedAbs string
expectedRel string
}{
{"x/y/z/boofar.md", "", "", "", false, false, "/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "", "", "", false, false, "/x/y/z/boofar/", "/x/y/z/boofar/"},
// Issue #1174
{"x/y/z/boofar.md", "http://gopher.com/", "", "", false, true, "http://gopher.com/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "http://gopher.com/", "", "", true, true, "http://gopher.com/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "", "boofar", "", false, false, "/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "http://barnew/", "", "", false, false, "http://barnew/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "http://barnew/", "boofar", "", false, false, "http://barnew/x/y/z/boofar/", "/x/y/z/boofar/"},
{"x/y/z/boofar.md", "", "", "", true, false, "/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "", "", "", true, false, "/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "", "boofar", "", true, false, "/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "http://barnew/", "", "", true, false, "http://barnew/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "http://barnew/", "boofar", "", true, false, "http://barnew/x/y/z/boofar.html", "/x/y/z/boofar.html"},
{"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", true, false, "http://barnew/boo/x/y/z/booslug.html", "/boo/x/y/z/booslug.html"},
{"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", false, true, "http://barnew/boo/x/y/z/booslug/", "/x/y/z/booslug/"},
{"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", false, false, "http://barnew/boo/x/y/z/booslug/", "/boo/x/y/z/booslug/"},
{"x/y/z/boofar.md", "http://barnew/boo/", "booslug", "", true, true, "http://barnew/boo/x/y/z/booslug.html", "/x/y/z/booslug.html"},
{"x/y/z/boofar.md", "http://barnew/boo", "booslug", "", true, true, "http://barnew/boo/x/y/z/booslug.html", "/x/y/z/booslug.html"},
// Issue #4666
{"x/y/z/boo-makeindex.md", "http://barnew/boo", "", "", true, true, "http://barnew/boo/x/y/z/boo-makeindex.html", "/x/y/z/boo-makeindex.html"},
// test URL overrides
{"x/y/z/boofar.md", "", "", "/z/y/q/", false, false, "/z/y/q/", "/z/y/q/"},
}
for i, test := range tests {
test := test
t.Run(fmt.Sprintf("%s-%d", test.file, i), func(t *testing.T) {
t.Parallel()
c := qt.New(t)
cfg, fs := newTestCfg()
cfg.Set("uglyURLs", test.uglyURLs)
cfg.Set("canonifyURLs", test.canonifyURLs)
cfg.Set("baseURL", test.base)
pageContent := fmt.Sprintf(`---
title: Page
slug: %q
url: %q
output: ["HTML"]
---
Content
`, test.slug, test.url)
writeSource(t, fs, filepath.Join("content", filepath.FromSlash(test.file)), pageContent)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0]
u := p.Permalink()
expected := test.expectedAbs
if u != expected {
t.Fatalf("[%d] Expected abs url: %s, got: %s", i, expected, u)
}
u = p.RelPermalink()
expected = test.expectedRel
if u != expected {
t.Errorf("[%d] Expected rel url: %s, got: %s", i, expected, u)
}
})
}
}
func TestRelativeURLInFrontMatter(t *testing.T) {
config := `
baseURL = "https://example.com"
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = false
[Languages]
[Languages.en]
weight = 10
contentDir = "content/en"
[Languages.nn]
weight = 20
contentDir = "content/nn"
`
pageTempl := `---
title: "A page"
url: %q
---
Some content.
`
b := newTestSitesBuilder(t).WithConfigFile("toml", config)
b.WithContent("content/en/blog/page1.md", fmt.Sprintf(pageTempl, "myblog/p1/"))
b.WithContent("content/en/blog/page2.md", fmt.Sprintf(pageTempl, "../../../../../myblog/p2/"))
b.WithContent("content/en/blog/page3.md", fmt.Sprintf(pageTempl, "../myblog/../myblog/p3/"))
b.WithContent("content/en/blog/_index.md", fmt.Sprintf(pageTempl, "this-is-my-english-blog"))
b.WithContent("content/nn/blog/page1.md", fmt.Sprintf(pageTempl, "myblog/p1/"))
b.WithContent("content/nn/blog/_index.md", fmt.Sprintf(pageTempl, "this-is-my-blog"))
b.Build(BuildCfg{})
b.AssertFileContent("public/nn/myblog/p1/index.html", "Single: A page|Hello|nn|RelPermalink: /nn/myblog/p1/|")
b.AssertFileContent("public/nn/this-is-my-blog/index.html", "List Page 1|A page|Hello|https://example.com/nn/this-is-my-blog/|")
b.AssertFileContent("public/this-is-my-english-blog/index.html", "List Page 1|A page|Hello|https://example.com/this-is-my-english-blog/|")
b.AssertFileContent("public/myblog/p1/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p1/|Permalink: https://example.com/myblog/p1/|")
b.AssertFileContent("public/myblog/p2/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p2/|Permalink: https://example.com/myblog/p2/|")
b.AssertFileContent("public/myblog/p3/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p3/|Permalink: https://example.com/myblog/p3/|")
}
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./parser/metadecoders/format_test.go | // Copyright 2018 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metadecoders
import (
"testing"
"github.com/gohugoio/hugo/media"
qt "github.com/frankban/quicktest"
)
func TestFormatFromString(t *testing.T) {
c := qt.New(t)
for _, test := range []struct {
s string
expect Format
}{
{"json", JSON},
{"yaml", YAML},
{"yml", YAML},
{"toml", TOML},
{"config.toml", TOML},
{"tOMl", TOML},
{"org", ORG},
{"foo", ""},
} {
c.Assert(FormatFromString(test.s), qt.Equals, test.expect)
}
}
func TestFormatFromMediaType(t *testing.T) {
c := qt.New(t)
for _, test := range []struct {
m media.Type
expect Format
}{
{media.JSONType, JSON},
{media.YAMLType, YAML},
{media.TOMLType, TOML},
{media.CalendarType, ""},
} {
c.Assert(FormatFromMediaType(test.m), qt.Equals, test.expect)
}
}
func TestFormatFromContentString(t *testing.T) {
t.Parallel()
c := qt.New(t)
for i, test := range []struct {
data string
expect interface{}
}{
{`foo = "bar"`, TOML},
{` foo = "bar"`, TOML},
{`foo="bar"`, TOML},
{`foo: "bar"`, YAML},
{`foo:"bar"`, YAML},
{`{ "foo": "bar"`, JSON},
{`a,b,c"`, CSV},
{`asdfasdf`, Format("")},
{``, Format("")},
} {
errMsg := qt.Commentf("[%d] %s", i, test.data)
result := Default.FormatFromContentString(test.data)
c.Assert(result, qt.Equals, test.expect, errMsg)
}
}
| // Copyright 2018 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metadecoders
import (
"testing"
"github.com/gohugoio/hugo/media"
qt "github.com/frankban/quicktest"
)
func TestFormatFromString(t *testing.T) {
c := qt.New(t)
for _, test := range []struct {
s string
expect Format
}{
{"json", JSON},
{"yaml", YAML},
{"yml", YAML},
{"toml", TOML},
{"config.toml", TOML},
{"tOMl", TOML},
{"org", ORG},
{"foo", ""},
} {
c.Assert(FormatFromString(test.s), qt.Equals, test.expect)
}
}
func TestFormatFromMediaType(t *testing.T) {
c := qt.New(t)
for _, test := range []struct {
m media.Type
expect Format
}{
{media.JSONType, JSON},
{media.YAMLType, YAML},
{media.TOMLType, TOML},
{media.CalendarType, ""},
} {
c.Assert(FormatFromMediaType(test.m), qt.Equals, test.expect)
}
}
func TestFormatFromContentString(t *testing.T) {
t.Parallel()
c := qt.New(t)
for i, test := range []struct {
data string
expect interface{}
}{
{`foo = "bar"`, TOML},
{` foo = "bar"`, TOML},
{`foo="bar"`, TOML},
{`foo: "bar"`, YAML},
{`foo:"bar"`, YAML},
{`{ "foo": "bar"`, JSON},
{`a,b,c"`, CSV},
{`asdfasdf`, Format("")},
{``, Format("")},
} {
errMsg := qt.Commentf("[%d] %s", i, test.data)
result := Default.FormatFromContentString(test.data)
c.Assert(result, qt.Equals, test.expect, errMsg)
}
}
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./hugolib/pages_process.go | // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"context"
"fmt"
"path/filepath"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/source"
"github.com/gohugoio/hugo/hugofs/files"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/hugofs"
)
func newPagesProcessor(h *HugoSites, sp *source.SourceSpec) *pagesProcessor {
procs := make(map[string]pagesCollectorProcessorProvider)
for _, s := range h.Sites {
procs[s.Lang()] = &sitePagesProcessor{
m: s.pageMap,
errorSender: s.h,
itemChan: make(chan interface{}, config.GetNumWorkerMultiplier()*2),
}
}
return &pagesProcessor{
procs: procs,
}
}
type pagesCollectorProcessorProvider interface {
Process(item interface{}) error
Start(ctx context.Context) context.Context
Wait() error
}
type pagesProcessor struct {
// Per language/Site
procs map[string]pagesCollectorProcessorProvider
}
func (proc *pagesProcessor) Process(item interface{}) error {
switch v := item.(type) {
// Page bundles mapped to their language.
case pageBundles:
for _, vv := range v {
proc.getProcFromFi(vv.header).Process(vv)
}
case hugofs.FileMetaInfo:
proc.getProcFromFi(v).Process(v)
default:
panic(fmt.Sprintf("unrecognized item type in Process: %T", item))
}
return nil
}
func (proc *pagesProcessor) Start(ctx context.Context) context.Context {
for _, p := range proc.procs {
ctx = p.Start(ctx)
}
return ctx
}
func (proc *pagesProcessor) Wait() error {
var err error
for _, p := range proc.procs {
if e := p.Wait(); e != nil {
err = e
}
}
return err
}
func (proc *pagesProcessor) getProcFromFi(fi hugofs.FileMetaInfo) pagesCollectorProcessorProvider {
if p, found := proc.procs[fi.Meta().Lang()]; found {
return p
}
return defaultPageProcessor
}
type nopPageProcessor int
func (nopPageProcessor) Process(item interface{}) error {
return nil
}
func (nopPageProcessor) Start(ctx context.Context) context.Context {
return context.Background()
}
func (nopPageProcessor) Wait() error {
return nil
}
var defaultPageProcessor = new(nopPageProcessor)
type sitePagesProcessor struct {
m *pageMap
errorSender herrors.ErrorSender
itemChan chan interface{}
itemGroup *errgroup.Group
}
func (p *sitePagesProcessor) Process(item interface{}) error {
p.itemChan <- item
return nil
}
func (p *sitePagesProcessor) Start(ctx context.Context) context.Context {
p.itemGroup, ctx = errgroup.WithContext(ctx)
p.itemGroup.Go(func() error {
for item := range p.itemChan {
if err := p.doProcess(item); err != nil {
return err
}
}
return nil
})
return ctx
}
func (p *sitePagesProcessor) Wait() error {
close(p.itemChan)
return p.itemGroup.Wait()
}
func (p *sitePagesProcessor) copyFile(fim hugofs.FileMetaInfo) error {
meta := fim.Meta()
f, err := meta.Open()
if err != nil {
return errors.Wrap(err, "copyFile: failed to open")
}
s := p.m.s
target := filepath.Join(s.PathSpec.GetTargetLanguageBasePath(), meta.Path())
defer f.Close()
return s.publish(&s.PathSpec.ProcessingStats.Files, target, f)
}
func (p *sitePagesProcessor) doProcess(item interface{}) error {
m := p.m
switch v := item.(type) {
case *fileinfoBundle:
if err := m.AddFilesBundle(v.header, v.resources...); err != nil {
return err
}
case hugofs.FileMetaInfo:
if p.shouldSkip(v) {
return nil
}
meta := v.Meta()
classifier := meta.Classifier()
switch classifier {
case files.ContentClassContent:
if err := m.AddFilesBundle(v); err != nil {
return err
}
case files.ContentClassFile:
if err := p.copyFile(v); err != nil {
return err
}
default:
panic(fmt.Sprintf("invalid classifier: %q", classifier))
}
default:
panic(fmt.Sprintf("unrecognized item type in Process: %T", item))
}
return nil
}
func (p *sitePagesProcessor) shouldSkip(fim hugofs.FileMetaInfo) bool {
// TODO(ep) unify
return p.m.s.SourceSpec.DisabledLanguages[fim.Meta().Lang()]
}
| // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"context"
"fmt"
"path/filepath"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/source"
"github.com/gohugoio/hugo/hugofs/files"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/hugofs"
)
func newPagesProcessor(h *HugoSites, sp *source.SourceSpec) *pagesProcessor {
procs := make(map[string]pagesCollectorProcessorProvider)
for _, s := range h.Sites {
procs[s.Lang()] = &sitePagesProcessor{
m: s.pageMap,
errorSender: s.h,
itemChan: make(chan interface{}, config.GetNumWorkerMultiplier()*2),
}
}
return &pagesProcessor{
procs: procs,
}
}
type pagesCollectorProcessorProvider interface {
Process(item interface{}) error
Start(ctx context.Context) context.Context
Wait() error
}
type pagesProcessor struct {
// Per language/Site
procs map[string]pagesCollectorProcessorProvider
}
func (proc *pagesProcessor) Process(item interface{}) error {
switch v := item.(type) {
// Page bundles mapped to their language.
case pageBundles:
for _, vv := range v {
proc.getProcFromFi(vv.header).Process(vv)
}
case hugofs.FileMetaInfo:
proc.getProcFromFi(v).Process(v)
default:
panic(fmt.Sprintf("unrecognized item type in Process: %T", item))
}
return nil
}
func (proc *pagesProcessor) Start(ctx context.Context) context.Context {
for _, p := range proc.procs {
ctx = p.Start(ctx)
}
return ctx
}
func (proc *pagesProcessor) Wait() error {
var err error
for _, p := range proc.procs {
if e := p.Wait(); e != nil {
err = e
}
}
return err
}
func (proc *pagesProcessor) getProcFromFi(fi hugofs.FileMetaInfo) pagesCollectorProcessorProvider {
if p, found := proc.procs[fi.Meta().Lang()]; found {
return p
}
return defaultPageProcessor
}
type nopPageProcessor int
func (nopPageProcessor) Process(item interface{}) error {
return nil
}
func (nopPageProcessor) Start(ctx context.Context) context.Context {
return context.Background()
}
func (nopPageProcessor) Wait() error {
return nil
}
var defaultPageProcessor = new(nopPageProcessor)
type sitePagesProcessor struct {
m *pageMap
errorSender herrors.ErrorSender
itemChan chan interface{}
itemGroup *errgroup.Group
}
func (p *sitePagesProcessor) Process(item interface{}) error {
p.itemChan <- item
return nil
}
func (p *sitePagesProcessor) Start(ctx context.Context) context.Context {
p.itemGroup, ctx = errgroup.WithContext(ctx)
p.itemGroup.Go(func() error {
for item := range p.itemChan {
if err := p.doProcess(item); err != nil {
return err
}
}
return nil
})
return ctx
}
func (p *sitePagesProcessor) Wait() error {
close(p.itemChan)
return p.itemGroup.Wait()
}
func (p *sitePagesProcessor) copyFile(fim hugofs.FileMetaInfo) error {
meta := fim.Meta()
f, err := meta.Open()
if err != nil {
return errors.Wrap(err, "copyFile: failed to open")
}
s := p.m.s
target := filepath.Join(s.PathSpec.GetTargetLanguageBasePath(), meta.Path())
defer f.Close()
return s.publish(&s.PathSpec.ProcessingStats.Files, target, f)
}
func (p *sitePagesProcessor) doProcess(item interface{}) error {
m := p.m
switch v := item.(type) {
case *fileinfoBundle:
if err := m.AddFilesBundle(v.header, v.resources...); err != nil {
return err
}
case hugofs.FileMetaInfo:
if p.shouldSkip(v) {
return nil
}
meta := v.Meta()
classifier := meta.Classifier()
switch classifier {
case files.ContentClassContent:
if err := m.AddFilesBundle(v); err != nil {
return err
}
case files.ContentClassFile:
if err := p.copyFile(v); err != nil {
return err
}
default:
panic(fmt.Sprintf("invalid classifier: %q", classifier))
}
default:
panic(fmt.Sprintf("unrecognized item type in Process: %T", item))
}
return nil
}
func (p *sitePagesProcessor) shouldSkip(fim hugofs.FileMetaInfo) bool {
// TODO(ep) unify
return p.m.s.SourceSpec.DisabledLanguages[fim.Meta().Lang()]
}
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./examples/blog/content/post/another-post.md | +++
title = "Another Hugo Post"
description = "Nothing special, but one post is boring."
date = "2014-09-02"
categories = [ "example", "configuration" ]
tags = [
"example",
"hugo",
"toml"
]
+++
TOML, YAML, JSON --- Oh my!
-------------------------
One of the nifty Hugo features we should cover: flexible configuration and front matter formats! This entry has front
matter in `toml`, unlike the last one which used `yaml`, and `json` is also available if that's your preference.
<!--more-->
The `toml` front matter used on this entry:
```
+++
title = "Another Hugo Post"
description = "Nothing special, but one post is boring."
date = "2014-09-02"
categories = [ "example", "configuration" ]
tags = [
"example",
"hugo",
"toml"
]
+++
```
This flexibility also extends to your site's global configuration file. You're free to use any format you prefer::simply
name the file `config.yaml`, `config.toml` or `config.json`, and go on your merry way.
JSON Example
------------
How would this entry's front matter look in `json`? That's easy enough to demonstrate:
```
{
"title": "Another Hugo Post",
"description": "Nothing special, but one post is boring.",
"date": "2014-09-02",
"categories": [ "example", "configuration" ],
"tags": [
"example",
"hugo",
"toml"
],
}
```
| +++
title = "Another Hugo Post"
description = "Nothing special, but one post is boring."
date = "2014-09-02"
categories = [ "example", "configuration" ]
tags = [
"example",
"hugo",
"toml"
]
+++
TOML, YAML, JSON --- Oh my!
-------------------------
One of the nifty Hugo features we should cover: flexible configuration and front matter formats! This entry has front
matter in `toml`, unlike the last one which used `yaml`, and `json` is also available if that's your preference.
<!--more-->
The `toml` front matter used on this entry:
```
+++
title = "Another Hugo Post"
description = "Nothing special, but one post is boring."
date = "2014-09-02"
categories = [ "example", "configuration" ]
tags = [
"example",
"hugo",
"toml"
]
+++
```
This flexibility also extends to your site's global configuration file. You're free to use any format you prefer::simply
name the file `config.yaml`, `config.toml` or `config.json`, and go on your merry way.
JSON Example
------------
How would this entry's front matter look in `json`? That's easy enough to demonstrate:
```
{
"title": "Another Hugo Post",
"description": "Nothing special, but one post is boring.",
"date": "2014-09-02",
"categories": [ "example", "configuration" ],
"tags": [
"example",
"hugo",
"toml"
],
}
```
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./docs/content/en/templates/template-debugging.md | ---
title: Template Debugging
# linktitle: Template Debugging
description: You can use Go templates' `printf` function to debug your Hugo templates. These snippets provide a quick and easy visualization of the variables available to you in different contexts.
godocref: https://golang.org/pkg/fmt/
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [templates]
keywords: [debugging,troubleshooting]
menu:
docs:
parent: "templates"
weight: 180
weight: 180
sections_weight: 180
draft: false
aliases: []
toc: false
---
Here are some snippets you can add to your template to answer some common questions.
These snippets use the `printf` function available in all Go templates. This function is an alias to the Go function, [fmt.Printf](https://golang.org/pkg/fmt/).
## What Variables are Available in this Context?
You can use the template syntax, `$.`, to get the top-level template context from anywhere in your template. This will print out all the values under, `.Site`.
```
{{ printf "%#v" $.Site }}
```
This will print out the value of `.Permalink`:
```
{{ printf "%#v" .Permalink }}
```
This will print out a list of all the variables scoped to the current context
(`.`, aka ["the dot"][tempintro]).
```
{{ printf "%#v" . }}
```
When developing a [homepage][], what does one of the pages you're looping through look like?
```
{{ range .Pages }}
{{/* The context, ".", is now each one of the pages as it goes through the loop */}}
{{ printf "%#v" . }}
{{ end }}
```
## Why Am I Showing No Defined Variables?
Check that you are passing variables in the `partial` function:
```
{{ partial "header" }}
```
This example will render the header partial, but the header partial will not have access to any contextual variables. You need to pass variables explicitly. For example, note the addition of ["the dot"][tempintro].
```
{{ partial "header" . }}
```
The dot (`.`) is considered fundamental to understanding Hugo templating. For more information, see [Introduction to Hugo Templating][tempintro].
[homepage]: /templates/homepage/
[tempintro]: /templates/introduction/
| ---
title: Template Debugging
# linktitle: Template Debugging
description: You can use Go templates' `printf` function to debug your Hugo templates. These snippets provide a quick and easy visualization of the variables available to you in different contexts.
godocref: https://golang.org/pkg/fmt/
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [templates]
keywords: [debugging,troubleshooting]
menu:
docs:
parent: "templates"
weight: 180
weight: 180
sections_weight: 180
draft: false
aliases: []
toc: false
---
Here are some snippets you can add to your template to answer some common questions.
These snippets use the `printf` function available in all Go templates. This function is an alias to the Go function, [fmt.Printf](https://golang.org/pkg/fmt/).
## What Variables are Available in this Context?
You can use the template syntax, `$.`, to get the top-level template context from anywhere in your template. This will print out all the values under, `.Site`.
```
{{ printf "%#v" $.Site }}
```
This will print out the value of `.Permalink`:
```
{{ printf "%#v" .Permalink }}
```
This will print out a list of all the variables scoped to the current context
(`.`, aka ["the dot"][tempintro]).
```
{{ printf "%#v" . }}
```
When developing a [homepage][], what does one of the pages you're looping through look like?
```
{{ range .Pages }}
{{/* The context, ".", is now each one of the pages as it goes through the loop */}}
{{ printf "%#v" . }}
{{ end }}
```
## Why Am I Showing No Defined Variables?
Check that you are passing variables in the `partial` function:
```
{{ partial "header" }}
```
This example will render the header partial, but the header partial will not have access to any contextual variables. You need to pass variables explicitly. For example, note the addition of ["the dot"][tempintro].
```
{{ partial "header" . }}
```
The dot (`.`) is considered fundamental to understanding Hugo templating. For more information, see [Introduction to Hugo Templating][tempintro].
[homepage]: /templates/homepage/
[tempintro]: /templates/introduction/
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./tpl/tplimpl/template.go | // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tplimpl
import (
"io"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/afero"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugofs/files"
"github.com/pkg/errors"
"github.com/gohugoio/hugo/tpl/tplimpl/embedded"
htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"
texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/tpl"
)
const (
textTmplNamePrefix = "_text/"
shortcodesPathPrefix = "shortcodes/"
internalPathPrefix = "_internal/"
baseFileBase = "baseof"
)
// The identifiers may be truncated in the log, e.g.
// "executing "main" at <$scaled.SRelPermalin...>: can't evaluate field SRelPermalink in type *resource.Image"
var identifiersRe = regexp.MustCompile(`at \<(.*?)(\.{3})?\>:`)
var embeddedTemplatesAliases = map[string][]string{
"shortcodes/twitter.html": {"shortcodes/tweet.html"},
}
var (
_ tpl.TemplateManager = (*templateExec)(nil)
_ tpl.TemplateHandler = (*templateExec)(nil)
_ tpl.TemplateFuncGetter = (*templateExec)(nil)
_ tpl.TemplateFinder = (*templateExec)(nil)
_ tpl.Template = (*templateState)(nil)
_ tpl.Info = (*templateState)(nil)
)
var baseTemplateDefineRe = regexp.MustCompile(`^{{-?\s*define`)
// needsBaseTemplate returns true if the first non-comment template block is a
// define block.
// If a base template does not exist, we will handle that when it's used.
func needsBaseTemplate(templ string) bool {
idx := -1
inComment := false
for i := 0; i < len(templ); {
if !inComment && strings.HasPrefix(templ[i:], "{{/*") {
inComment = true
i += 4
} else if inComment && strings.HasPrefix(templ[i:], "*/}}") {
inComment = false
i += 4
} else {
r, size := utf8.DecodeRuneInString(templ[i:])
if !inComment {
if strings.HasPrefix(templ[i:], "{{") {
idx = i
break
} else if !unicode.IsSpace(r) {
break
}
}
i += size
}
}
if idx == -1 {
return false
}
return baseTemplateDefineRe.MatchString(templ[idx:])
}
func newIdentity(name string) identity.Manager {
return identity.NewManager(identity.NewPathIdentity(files.ComponentFolderLayouts, name))
}
func newStandaloneTextTemplate(funcs map[string]interface{}) tpl.TemplateParseFinder {
return &textTemplateWrapperWithLock{
RWMutex: &sync.RWMutex{},
Template: texttemplate.New("").Funcs(funcs),
}
}
func newTemplateExec(d *deps.Deps) (*templateExec, error) {
exec, funcs := newTemplateExecuter(d)
funcMap := make(map[string]interface{})
for k, v := range funcs {
funcMap[k] = v.Interface()
}
h := &templateHandler{
nameBaseTemplateName: make(map[string]string),
transformNotFound: make(map[string]*templateState),
identityNotFound: make(map[string][]identity.Manager),
shortcodes: make(map[string]*shortcodeTemplates),
templateInfo: make(map[string]tpl.Info),
baseof: make(map[string]templateInfo),
needsBaseof: make(map[string]templateInfo),
main: newTemplateNamespace(funcMap),
Deps: d,
layoutHandler: output.NewLayoutHandler(),
layoutsFs: d.BaseFs.Layouts.Fs,
layoutTemplateCache: make(map[layoutCacheKey]tpl.Template),
}
if err := h.loadEmbedded(); err != nil {
return nil, err
}
if err := h.loadTemplates(); err != nil {
return nil, err
}
e := &templateExec{
d: d,
executor: exec,
funcs: funcs,
templateHandler: h,
}
d.SetTmpl(e)
d.SetTextTmpl(newStandaloneTextTemplate(funcMap))
if d.WithTemplate != nil {
if err := d.WithTemplate(e); err != nil {
return nil, err
}
}
return e, nil
}
func newTemplateNamespace(funcs map[string]interface{}) *templateNamespace {
return &templateNamespace{
prototypeHTML: htmltemplate.New("").Funcs(funcs),
prototypeText: texttemplate.New("").Funcs(funcs),
templateStateMap: &templateStateMap{
templates: make(map[string]*templateState),
},
}
}
func newTemplateState(templ tpl.Template, info templateInfo) *templateState {
return &templateState{
info: info,
typ: info.resolveType(),
Template: templ,
Manager: newIdentity(info.name),
parseInfo: tpl.DefaultParseInfo,
}
}
type layoutCacheKey struct {
d output.LayoutDescriptor
f string
}
type templateExec struct {
d *deps.Deps
executor texttemplate.Executer
funcs map[string]reflect.Value
*templateHandler
}
func (t templateExec) Clone(d *deps.Deps) *templateExec {
exec, funcs := newTemplateExecuter(d)
t.executor = exec
t.funcs = funcs
t.d = d
return &t
}
func (t *templateExec) Execute(templ tpl.Template, wr io.Writer, data interface{}) error {
if rlocker, ok := templ.(types.RLocker); ok {
rlocker.RLock()
defer rlocker.RUnlock()
}
if t.Metrics != nil {
defer t.Metrics.MeasureSince(templ.Name(), time.Now())
}
execErr := t.executor.Execute(templ, wr, data)
if execErr != nil {
execErr = t.addFileContext(templ, execErr)
}
return execErr
}
func (t *templateExec) GetFunc(name string) (reflect.Value, bool) {
v, found := t.funcs[name]
return v, found
}
func (t *templateExec) MarkReady() error {
var err error
t.readyInit.Do(func() {
// We only need the clones if base templates are in use.
if len(t.needsBaseof) > 0 {
err = t.main.createPrototypes()
}
})
return err
}
type templateHandler struct {
main *templateNamespace
needsBaseof map[string]templateInfo
baseof map[string]templateInfo
readyInit sync.Once
// This is the filesystem to load the templates from. All the templates are
// stored in the root of this filesystem.
layoutsFs afero.Fs
layoutHandler *output.LayoutHandler
layoutTemplateCache map[layoutCacheKey]tpl.Template
layoutTemplateCacheMu sync.RWMutex
*deps.Deps
// Used to get proper filenames in errors
nameBaseTemplateName map[string]string
// Holds name and source of template definitions not found during the first
// AST transformation pass.
transformNotFound map[string]*templateState
// Holds identities of templates not found during first pass.
identityNotFound map[string][]identity.Manager
// shortcodes maps shortcode name to template variants
// (language, output format etc.) of that shortcode.
shortcodes map[string]*shortcodeTemplates
// templateInfo maps template name to some additional information about that template.
// Note that for shortcodes that same information is embedded in the
// shortcodeTemplates type.
templateInfo map[string]tpl.Info
}
// AddTemplate parses and adds a template to the collection.
// Templates with name prefixed with "_text" will be handled as plain
// text templates.
func (t *templateHandler) AddTemplate(name, tpl string) error {
templ, err := t.addTemplateTo(t.newTemplateInfo(name, tpl), t.main)
if err == nil {
t.applyTemplateTransformers(t.main, templ)
}
return err
}
func (t *templateHandler) Lookup(name string) (tpl.Template, bool) {
templ, found := t.main.Lookup(name)
if found {
return templ, true
}
return nil, false
}
func (t *templateHandler) LookupLayout(d output.LayoutDescriptor, f output.Format) (tpl.Template, bool, error) {
key := layoutCacheKey{d, f.Name}
t.layoutTemplateCacheMu.RLock()
if cacheVal, found := t.layoutTemplateCache[key]; found {
t.layoutTemplateCacheMu.RUnlock()
return cacheVal, true, nil
}
t.layoutTemplateCacheMu.RUnlock()
t.layoutTemplateCacheMu.Lock()
defer t.layoutTemplateCacheMu.Unlock()
templ, found, err := t.findLayout(d, f)
if err == nil && found {
t.layoutTemplateCache[key] = templ
return templ, true, nil
}
return nil, false, err
}
// This currently only applies to shortcodes and what we get here is the
// shortcode name.
func (t *templateHandler) LookupVariant(name string, variants tpl.TemplateVariants) (tpl.Template, bool, bool) {
name = templateBaseName(templateShortcode, name)
s, found := t.shortcodes[name]
if !found {
return nil, false, false
}
sv, found := s.fromVariants(variants)
if !found {
return nil, false, false
}
more := len(s.variants) > 1
return sv.ts, true, more
}
// LookupVariants returns all variants of name, nil if none found.
func (t *templateHandler) LookupVariants(name string) []tpl.Template {
name = templateBaseName(templateShortcode, name)
s, found := t.shortcodes[name]
if !found {
return nil
}
variants := make([]tpl.Template, len(s.variants))
for i := 0; i < len(variants); i++ {
variants[i] = s.variants[i].ts
}
return variants
}
func (t *templateHandler) HasTemplate(name string) bool {
if _, found := t.baseof[name]; found {
return true
}
if _, found := t.needsBaseof[name]; found {
return true
}
_, found := t.Lookup(name)
return found
}
func (t *templateHandler) findLayout(d output.LayoutDescriptor, f output.Format) (tpl.Template, bool, error) {
layouts, _ := t.layoutHandler.For(d, f)
for _, name := range layouts {
templ, found := t.main.Lookup(name)
if found {
return templ, true, nil
}
overlay, found := t.needsBaseof[name]
if !found {
continue
}
d.Baseof = true
baseLayouts, _ := t.layoutHandler.For(d, f)
var base templateInfo
found = false
for _, l := range baseLayouts {
base, found = t.baseof[l]
if found {
break
}
}
templ, err := t.applyBaseTemplate(overlay, base)
if err != nil {
return nil, false, err
}
ts := newTemplateState(templ, overlay)
if found {
ts.baseInfo = base
// Add the base identity to detect changes
ts.Add(identity.NewPathIdentity(files.ComponentFolderLayouts, base.name))
}
t.applyTemplateTransformers(t.main, ts)
if err := t.extractPartials(ts.Template); err != nil {
return nil, false, err
}
return ts, true, nil
}
return nil, false, nil
}
func (t *templateHandler) findTemplate(name string) *templateState {
if templ, found := t.Lookup(name); found {
return templ.(*templateState)
}
return nil
}
func (t *templateHandler) newTemplateInfo(name, tpl string) templateInfo {
var isText bool
name, isText = t.nameIsText(name)
return templateInfo{
name: name,
isText: isText,
template: tpl,
}
}
func (t *templateHandler) addFileContext(templ tpl.Template, inerr error) error {
if strings.HasPrefix(templ.Name(), "_internal") {
return inerr
}
ts, ok := templ.(*templateState)
if !ok {
return inerr
}
//lint:ignore ST1008 the error is the main result
checkFilename := func(info templateInfo, inErr error) (error, bool) {
if info.filename == "" {
return inErr, false
}
lineMatcher := func(m herrors.LineMatcher) bool {
if m.Position.LineNumber != m.LineNumber {
return false
}
identifiers := t.extractIdentifiers(m.Error.Error())
for _, id := range identifiers {
if strings.Contains(m.Line, id) {
return true
}
}
return false
}
f, err := t.layoutsFs.Open(info.filename)
if err != nil {
return inErr, false
}
defer f.Close()
fe, ok := herrors.WithFileContext(inErr, info.realFilename, f, lineMatcher)
if ok {
return fe, true
}
return inErr, false
}
inerr = errors.Wrap(inerr, "execute of template failed")
if err, ok := checkFilename(ts.info, inerr); ok {
return err
}
err, _ := checkFilename(ts.baseInfo, inerr)
return err
}
func (t *templateHandler) addShortcodeVariant(ts *templateState) {
name := ts.Name()
base := templateBaseName(templateShortcode, name)
shortcodename, variants := templateNameAndVariants(base)
templs, found := t.shortcodes[shortcodename]
if !found {
templs = &shortcodeTemplates{}
t.shortcodes[shortcodename] = templs
}
sv := shortcodeVariant{variants: variants, ts: ts}
i := templs.indexOf(variants)
if i != -1 {
// Only replace if it's an override of an internal template.
if !isInternal(name) {
templs.variants[i] = sv
}
} else {
templs.variants = append(templs.variants, sv)
}
}
func (t *templateHandler) addTemplateFile(name, path string) error {
getTemplate := func(filename string) (templateInfo, error) {
fs := t.Layouts.Fs
b, err := afero.ReadFile(fs, filename)
if err != nil {
return templateInfo{filename: filename, fs: fs}, err
}
s := removeLeadingBOM(string(b))
realFilename := filename
if fi, err := fs.Stat(filename); err == nil {
if fim, ok := fi.(hugofs.FileMetaInfo); ok {
realFilename = fim.Meta().Filename()
}
}
var isText bool
name, isText = t.nameIsText(name)
return templateInfo{
name: name,
isText: isText,
template: s,
filename: filename,
realFilename: realFilename,
fs: fs,
}, nil
}
tinfo, err := getTemplate(path)
if err != nil {
return err
}
if isBaseTemplatePath(name) {
// Store it for later.
t.baseof[name] = tinfo
return nil
}
needsBaseof := !t.noBaseNeeded(name) && needsBaseTemplate(tinfo.template)
if needsBaseof {
t.needsBaseof[name] = tinfo
return nil
}
templ, err := t.addTemplateTo(tinfo, t.main)
if err != nil {
return tinfo.errWithFileContext("parse failed", err)
}
t.applyTemplateTransformers(t.main, templ)
return nil
}
func (t *templateHandler) addTemplateTo(info templateInfo, to *templateNamespace) (*templateState, error) {
return to.parse(info)
}
func (t *templateHandler) applyBaseTemplate(overlay, base templateInfo) (tpl.Template, error) {
if overlay.isText {
var (
templ = t.main.prototypeTextClone.New(overlay.name)
err error
)
if !base.IsZero() {
templ, err = templ.Parse(base.template)
if err != nil {
return nil, base.errWithFileContext("parse failed", err)
}
}
templ, err = texttemplate.Must(templ.Clone()).Parse(overlay.template)
if err != nil {
return nil, overlay.errWithFileContext("parse failed", err)
}
// The extra lookup is a workaround, see
// * https://github.com/golang/go/issues/16101
// * https://github.com/gohugoio/hugo/issues/2549
// templ = templ.Lookup(templ.Name())
return templ, nil
}
var (
templ = t.main.prototypeHTMLClone.New(overlay.name)
err error
)
if !base.IsZero() {
templ, err = templ.Parse(base.template)
if err != nil {
return nil, base.errWithFileContext("parse failed", err)
}
}
templ, err = htmltemplate.Must(templ.Clone()).Parse(overlay.template)
if err != nil {
return nil, overlay.errWithFileContext("parse failed", err)
}
// The extra lookup is a workaround, see
// * https://github.com/golang/go/issues/16101
// * https://github.com/gohugoio/hugo/issues/2549
templ = templ.Lookup(templ.Name())
return templ, err
}
func (t *templateHandler) applyTemplateTransformers(ns *templateNamespace, ts *templateState) (*templateContext, error) {
c, err := applyTemplateTransformers(ts, ns.newTemplateLookup(ts))
if err != nil {
return nil, err
}
for k := range c.templateNotFound {
t.transformNotFound[k] = ts
t.identityNotFound[k] = append(t.identityNotFound[k], c.t)
}
for k := range c.identityNotFound {
t.identityNotFound[k] = append(t.identityNotFound[k], c.t)
}
return c, err
}
func (t *templateHandler) extractIdentifiers(line string) []string {
m := identifiersRe.FindAllStringSubmatch(line, -1)
identifiers := make([]string, len(m))
for i := 0; i < len(m); i++ {
identifiers[i] = m[i][1]
}
return identifiers
}
func (t *templateHandler) loadEmbedded() error {
for _, kv := range embedded.EmbeddedTemplates {
name, templ := kv[0], kv[1]
if err := t.AddTemplate(internalPathPrefix+name, templ); err != nil {
return err
}
if aliases, found := embeddedTemplatesAliases[name]; found {
// TODO(bep) avoid reparsing these aliases
for _, alias := range aliases {
alias = internalPathPrefix + alias
if err := t.AddTemplate(alias, templ); err != nil {
return err
}
}
}
}
return nil
}
func (t *templateHandler) loadTemplates() error {
walker := func(path string, fi hugofs.FileMetaInfo, err error) error {
if err != nil || fi.IsDir() {
return err
}
if isDotFile(path) || isBackupFile(path) {
return nil
}
name := strings.TrimPrefix(filepath.ToSlash(path), "/")
filename := filepath.Base(path)
outputFormat, found := t.OutputFormatsConfig.FromFilename(filename)
if found && outputFormat.IsPlainText {
name = textTmplNamePrefix + name
}
if err := t.addTemplateFile(name, path); err != nil {
return err
}
return nil
}
if err := helpers.SymbolicWalk(t.Layouts.Fs, "", walker); err != nil {
if !os.IsNotExist(err) {
return err
}
return nil
}
return nil
}
func (t *templateHandler) nameIsText(name string) (string, bool) {
isText := strings.HasPrefix(name, textTmplNamePrefix)
if isText {
name = strings.TrimPrefix(name, textTmplNamePrefix)
}
return name, isText
}
func (t *templateHandler) noBaseNeeded(name string) bool {
if strings.HasPrefix(name, "shortcodes/") || strings.HasPrefix(name, "partials/") {
return true
}
return strings.Contains(name, "_markup/")
}
func (t *templateHandler) extractPartials(templ tpl.Template) error {
templs := templates(templ)
for _, templ := range templs {
if templ.Name() == "" || !strings.HasPrefix(templ.Name(), "partials/") {
continue
}
ts := newTemplateState(templ, templateInfo{name: templ.Name()})
ts.typ = templatePartial
t.main.mu.RLock()
_, found := t.main.templates[templ.Name()]
t.main.mu.RUnlock()
if !found {
t.main.mu.Lock()
// This is a template defined inline.
_, err := applyTemplateTransformers(ts, t.main.newTemplateLookup(ts))
if err != nil {
t.main.mu.Unlock()
return err
}
t.main.templates[templ.Name()] = ts
t.main.mu.Unlock()
}
}
return nil
}
func (t *templateHandler) postTransform() error {
defineCheckedHTML := false
defineCheckedText := false
for _, v := range t.main.templates {
if v.typ == templateShortcode {
t.addShortcodeVariant(v)
}
if defineCheckedHTML && defineCheckedText {
continue
}
isText := isText(v.Template)
if isText {
if defineCheckedText {
continue
}
defineCheckedText = true
} else {
if defineCheckedHTML {
continue
}
defineCheckedHTML = true
}
if err := t.extractPartials(v.Template); err != nil {
return err
}
}
for name, source := range t.transformNotFound {
lookup := t.main.newTemplateLookup(source)
templ := lookup(name)
if templ != nil {
_, err := applyTemplateTransformers(templ, lookup)
if err != nil {
return err
}
}
}
for k, v := range t.identityNotFound {
ts := t.findTemplate(k)
if ts != nil {
for _, im := range v {
im.Add(ts)
}
}
}
return nil
}
type templateNamespace struct {
prototypeText *texttemplate.Template
prototypeHTML *htmltemplate.Template
prototypeTextClone *texttemplate.Template
prototypeHTMLClone *htmltemplate.Template
*templateStateMap
}
func (t templateNamespace) Clone() *templateNamespace {
t.mu.Lock()
defer t.mu.Unlock()
t.templateStateMap = &templateStateMap{
templates: make(map[string]*templateState),
}
t.prototypeText = texttemplate.Must(t.prototypeText.Clone())
t.prototypeHTML = htmltemplate.Must(t.prototypeHTML.Clone())
return &t
}
func (t *templateNamespace) Lookup(name string) (tpl.Template, bool) {
t.mu.RLock()
defer t.mu.RUnlock()
templ, found := t.templates[name]
if !found {
return nil, false
}
return templ, found
}
func (t *templateNamespace) createPrototypes() error {
t.prototypeTextClone = texttemplate.Must(t.prototypeText.Clone())
t.prototypeHTMLClone = htmltemplate.Must(t.prototypeHTML.Clone())
return nil
}
func (t *templateNamespace) newTemplateLookup(in *templateState) func(name string) *templateState {
return func(name string) *templateState {
if templ, found := t.templates[name]; found {
if templ.isText() != in.isText() {
return nil
}
return templ
}
if templ, found := findTemplateIn(name, in); found {
return newTemplateState(templ, templateInfo{name: templ.Name()})
}
return nil
}
}
func (t *templateNamespace) parse(info templateInfo) (*templateState, error) {
t.mu.Lock()
defer t.mu.Unlock()
if info.isText {
prototype := t.prototypeText
templ, err := prototype.New(info.name).Parse(info.template)
if err != nil {
return nil, err
}
ts := newTemplateState(templ, info)
t.templates[info.name] = ts
return ts, nil
}
prototype := t.prototypeHTML
templ, err := prototype.New(info.name).Parse(info.template)
if err != nil {
return nil, err
}
ts := newTemplateState(templ, info)
t.templates[info.name] = ts
return ts, nil
}
type templateState struct {
tpl.Template
typ templateType
parseInfo tpl.ParseInfo
identity.Manager
info templateInfo
baseInfo templateInfo // Set when a base template is used.
}
func (t *templateState) ParseInfo() tpl.ParseInfo {
return t.parseInfo
}
func (t *templateState) isText() bool {
return isText(t.Template)
}
func isText(templ tpl.Template) bool {
_, isText := templ.(*texttemplate.Template)
return isText
}
type templateStateMap struct {
mu sync.RWMutex
templates map[string]*templateState
}
type templateWrapperWithLock struct {
*sync.RWMutex
tpl.Template
}
type textTemplateWrapperWithLock struct {
*sync.RWMutex
*texttemplate.Template
}
func (t *textTemplateWrapperWithLock) Lookup(name string) (tpl.Template, bool) {
t.RLock()
templ := t.Template.Lookup(name)
t.RUnlock()
if templ == nil {
return nil, false
}
return &textTemplateWrapperWithLock{
RWMutex: t.RWMutex,
Template: templ,
}, true
}
func (t *textTemplateWrapperWithLock) LookupVariant(name string, variants tpl.TemplateVariants) (tpl.Template, bool, bool) {
panic("not supported")
}
func (t *textTemplateWrapperWithLock) LookupVariants(name string) []tpl.Template {
panic("not supported")
}
func (t *textTemplateWrapperWithLock) Parse(name, tpl string) (tpl.Template, error) {
t.Lock()
defer t.Unlock()
return t.Template.New(name).Parse(tpl)
}
func isBackupFile(path string) bool {
return path[len(path)-1] == '~'
}
func isBaseTemplatePath(path string) bool {
return strings.Contains(filepath.Base(path), baseFileBase)
}
func isDotFile(path string) bool {
return filepath.Base(path)[0] == '.'
}
func removeLeadingBOM(s string) string {
const bom = '\ufeff'
for i, r := range s {
if i == 0 && r != bom {
return s
}
if i > 0 {
return s[i:]
}
}
return s
}
// resolves _internal/shortcodes/param.html => param.html etc.
func templateBaseName(typ templateType, name string) string {
name = strings.TrimPrefix(name, internalPathPrefix)
switch typ {
case templateShortcode:
return strings.TrimPrefix(name, shortcodesPathPrefix)
default:
panic("not implemented")
}
}
func unwrap(templ tpl.Template) tpl.Template {
if ts, ok := templ.(*templateState); ok {
return ts.Template
}
return templ
}
func templates(in tpl.Template) []tpl.Template {
var templs []tpl.Template
in = unwrap(in)
if textt, ok := in.(*texttemplate.Template); ok {
for _, t := range textt.Templates() {
templs = append(templs, t)
}
}
if htmlt, ok := in.(*htmltemplate.Template); ok {
for _, t := range htmlt.Templates() {
templs = append(templs, t)
}
}
return templs
}
| // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tplimpl
import (
"io"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/afero"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugofs/files"
"github.com/pkg/errors"
"github.com/gohugoio/hugo/tpl/tplimpl/embedded"
htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"
texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/tpl"
)
const (
textTmplNamePrefix = "_text/"
shortcodesPathPrefix = "shortcodes/"
internalPathPrefix = "_internal/"
baseFileBase = "baseof"
)
// The identifiers may be truncated in the log, e.g.
// "executing "main" at <$scaled.SRelPermalin...>: can't evaluate field SRelPermalink in type *resource.Image"
var identifiersRe = regexp.MustCompile(`at \<(.*?)(\.{3})?\>:`)
var embeddedTemplatesAliases = map[string][]string{
"shortcodes/twitter.html": {"shortcodes/tweet.html"},
}
var (
_ tpl.TemplateManager = (*templateExec)(nil)
_ tpl.TemplateHandler = (*templateExec)(nil)
_ tpl.TemplateFuncGetter = (*templateExec)(nil)
_ tpl.TemplateFinder = (*templateExec)(nil)
_ tpl.Template = (*templateState)(nil)
_ tpl.Info = (*templateState)(nil)
)
var baseTemplateDefineRe = regexp.MustCompile(`^{{-?\s*define`)
// needsBaseTemplate returns true if the first non-comment template block is a
// define block.
// If a base template does not exist, we will handle that when it's used.
func needsBaseTemplate(templ string) bool {
idx := -1
inComment := false
for i := 0; i < len(templ); {
if !inComment && strings.HasPrefix(templ[i:], "{{/*") {
inComment = true
i += 4
} else if inComment && strings.HasPrefix(templ[i:], "*/}}") {
inComment = false
i += 4
} else {
r, size := utf8.DecodeRuneInString(templ[i:])
if !inComment {
if strings.HasPrefix(templ[i:], "{{") {
idx = i
break
} else if !unicode.IsSpace(r) {
break
}
}
i += size
}
}
if idx == -1 {
return false
}
return baseTemplateDefineRe.MatchString(templ[idx:])
}
func newIdentity(name string) identity.Manager {
return identity.NewManager(identity.NewPathIdentity(files.ComponentFolderLayouts, name))
}
func newStandaloneTextTemplate(funcs map[string]interface{}) tpl.TemplateParseFinder {
return &textTemplateWrapperWithLock{
RWMutex: &sync.RWMutex{},
Template: texttemplate.New("").Funcs(funcs),
}
}
func newTemplateExec(d *deps.Deps) (*templateExec, error) {
exec, funcs := newTemplateExecuter(d)
funcMap := make(map[string]interface{})
for k, v := range funcs {
funcMap[k] = v.Interface()
}
h := &templateHandler{
nameBaseTemplateName: make(map[string]string),
transformNotFound: make(map[string]*templateState),
identityNotFound: make(map[string][]identity.Manager),
shortcodes: make(map[string]*shortcodeTemplates),
templateInfo: make(map[string]tpl.Info),
baseof: make(map[string]templateInfo),
needsBaseof: make(map[string]templateInfo),
main: newTemplateNamespace(funcMap),
Deps: d,
layoutHandler: output.NewLayoutHandler(),
layoutsFs: d.BaseFs.Layouts.Fs,
layoutTemplateCache: make(map[layoutCacheKey]tpl.Template),
}
if err := h.loadEmbedded(); err != nil {
return nil, err
}
if err := h.loadTemplates(); err != nil {
return nil, err
}
e := &templateExec{
d: d,
executor: exec,
funcs: funcs,
templateHandler: h,
}
d.SetTmpl(e)
d.SetTextTmpl(newStandaloneTextTemplate(funcMap))
if d.WithTemplate != nil {
if err := d.WithTemplate(e); err != nil {
return nil, err
}
}
return e, nil
}
func newTemplateNamespace(funcs map[string]interface{}) *templateNamespace {
return &templateNamespace{
prototypeHTML: htmltemplate.New("").Funcs(funcs),
prototypeText: texttemplate.New("").Funcs(funcs),
templateStateMap: &templateStateMap{
templates: make(map[string]*templateState),
},
}
}
func newTemplateState(templ tpl.Template, info templateInfo) *templateState {
return &templateState{
info: info,
typ: info.resolveType(),
Template: templ,
Manager: newIdentity(info.name),
parseInfo: tpl.DefaultParseInfo,
}
}
type layoutCacheKey struct {
d output.LayoutDescriptor
f string
}
type templateExec struct {
d *deps.Deps
executor texttemplate.Executer
funcs map[string]reflect.Value
*templateHandler
}
func (t templateExec) Clone(d *deps.Deps) *templateExec {
exec, funcs := newTemplateExecuter(d)
t.executor = exec
t.funcs = funcs
t.d = d
return &t
}
func (t *templateExec) Execute(templ tpl.Template, wr io.Writer, data interface{}) error {
if rlocker, ok := templ.(types.RLocker); ok {
rlocker.RLock()
defer rlocker.RUnlock()
}
if t.Metrics != nil {
defer t.Metrics.MeasureSince(templ.Name(), time.Now())
}
execErr := t.executor.Execute(templ, wr, data)
if execErr != nil {
execErr = t.addFileContext(templ, execErr)
}
return execErr
}
func (t *templateExec) GetFunc(name string) (reflect.Value, bool) {
v, found := t.funcs[name]
return v, found
}
func (t *templateExec) MarkReady() error {
var err error
t.readyInit.Do(func() {
// We only need the clones if base templates are in use.
if len(t.needsBaseof) > 0 {
err = t.main.createPrototypes()
}
})
return err
}
type templateHandler struct {
main *templateNamespace
needsBaseof map[string]templateInfo
baseof map[string]templateInfo
readyInit sync.Once
// This is the filesystem to load the templates from. All the templates are
// stored in the root of this filesystem.
layoutsFs afero.Fs
layoutHandler *output.LayoutHandler
layoutTemplateCache map[layoutCacheKey]tpl.Template
layoutTemplateCacheMu sync.RWMutex
*deps.Deps
// Used to get proper filenames in errors
nameBaseTemplateName map[string]string
// Holds name and source of template definitions not found during the first
// AST transformation pass.
transformNotFound map[string]*templateState
// Holds identities of templates not found during first pass.
identityNotFound map[string][]identity.Manager
// shortcodes maps shortcode name to template variants
// (language, output format etc.) of that shortcode.
shortcodes map[string]*shortcodeTemplates
// templateInfo maps template name to some additional information about that template.
// Note that for shortcodes that same information is embedded in the
// shortcodeTemplates type.
templateInfo map[string]tpl.Info
}
// AddTemplate parses and adds a template to the collection.
// Templates with name prefixed with "_text" will be handled as plain
// text templates.
func (t *templateHandler) AddTemplate(name, tpl string) error {
templ, err := t.addTemplateTo(t.newTemplateInfo(name, tpl), t.main)
if err == nil {
t.applyTemplateTransformers(t.main, templ)
}
return err
}
func (t *templateHandler) Lookup(name string) (tpl.Template, bool) {
templ, found := t.main.Lookup(name)
if found {
return templ, true
}
return nil, false
}
func (t *templateHandler) LookupLayout(d output.LayoutDescriptor, f output.Format) (tpl.Template, bool, error) {
key := layoutCacheKey{d, f.Name}
t.layoutTemplateCacheMu.RLock()
if cacheVal, found := t.layoutTemplateCache[key]; found {
t.layoutTemplateCacheMu.RUnlock()
return cacheVal, true, nil
}
t.layoutTemplateCacheMu.RUnlock()
t.layoutTemplateCacheMu.Lock()
defer t.layoutTemplateCacheMu.Unlock()
templ, found, err := t.findLayout(d, f)
if err == nil && found {
t.layoutTemplateCache[key] = templ
return templ, true, nil
}
return nil, false, err
}
// This currently only applies to shortcodes and what we get here is the
// shortcode name.
func (t *templateHandler) LookupVariant(name string, variants tpl.TemplateVariants) (tpl.Template, bool, bool) {
name = templateBaseName(templateShortcode, name)
s, found := t.shortcodes[name]
if !found {
return nil, false, false
}
sv, found := s.fromVariants(variants)
if !found {
return nil, false, false
}
more := len(s.variants) > 1
return sv.ts, true, more
}
// LookupVariants returns all variants of name, nil if none found.
func (t *templateHandler) LookupVariants(name string) []tpl.Template {
name = templateBaseName(templateShortcode, name)
s, found := t.shortcodes[name]
if !found {
return nil
}
variants := make([]tpl.Template, len(s.variants))
for i := 0; i < len(variants); i++ {
variants[i] = s.variants[i].ts
}
return variants
}
func (t *templateHandler) HasTemplate(name string) bool {
if _, found := t.baseof[name]; found {
return true
}
if _, found := t.needsBaseof[name]; found {
return true
}
_, found := t.Lookup(name)
return found
}
func (t *templateHandler) findLayout(d output.LayoutDescriptor, f output.Format) (tpl.Template, bool, error) {
layouts, _ := t.layoutHandler.For(d, f)
for _, name := range layouts {
templ, found := t.main.Lookup(name)
if found {
return templ, true, nil
}
overlay, found := t.needsBaseof[name]
if !found {
continue
}
d.Baseof = true
baseLayouts, _ := t.layoutHandler.For(d, f)
var base templateInfo
found = false
for _, l := range baseLayouts {
base, found = t.baseof[l]
if found {
break
}
}
templ, err := t.applyBaseTemplate(overlay, base)
if err != nil {
return nil, false, err
}
ts := newTemplateState(templ, overlay)
if found {
ts.baseInfo = base
// Add the base identity to detect changes
ts.Add(identity.NewPathIdentity(files.ComponentFolderLayouts, base.name))
}
t.applyTemplateTransformers(t.main, ts)
if err := t.extractPartials(ts.Template); err != nil {
return nil, false, err
}
return ts, true, nil
}
return nil, false, nil
}
func (t *templateHandler) findTemplate(name string) *templateState {
if templ, found := t.Lookup(name); found {
return templ.(*templateState)
}
return nil
}
func (t *templateHandler) newTemplateInfo(name, tpl string) templateInfo {
var isText bool
name, isText = t.nameIsText(name)
return templateInfo{
name: name,
isText: isText,
template: tpl,
}
}
func (t *templateHandler) addFileContext(templ tpl.Template, inerr error) error {
if strings.HasPrefix(templ.Name(), "_internal") {
return inerr
}
ts, ok := templ.(*templateState)
if !ok {
return inerr
}
//lint:ignore ST1008 the error is the main result
checkFilename := func(info templateInfo, inErr error) (error, bool) {
if info.filename == "" {
return inErr, false
}
lineMatcher := func(m herrors.LineMatcher) bool {
if m.Position.LineNumber != m.LineNumber {
return false
}
identifiers := t.extractIdentifiers(m.Error.Error())
for _, id := range identifiers {
if strings.Contains(m.Line, id) {
return true
}
}
return false
}
f, err := t.layoutsFs.Open(info.filename)
if err != nil {
return inErr, false
}
defer f.Close()
fe, ok := herrors.WithFileContext(inErr, info.realFilename, f, lineMatcher)
if ok {
return fe, true
}
return inErr, false
}
inerr = errors.Wrap(inerr, "execute of template failed")
if err, ok := checkFilename(ts.info, inerr); ok {
return err
}
err, _ := checkFilename(ts.baseInfo, inerr)
return err
}
func (t *templateHandler) addShortcodeVariant(ts *templateState) {
name := ts.Name()
base := templateBaseName(templateShortcode, name)
shortcodename, variants := templateNameAndVariants(base)
templs, found := t.shortcodes[shortcodename]
if !found {
templs = &shortcodeTemplates{}
t.shortcodes[shortcodename] = templs
}
sv := shortcodeVariant{variants: variants, ts: ts}
i := templs.indexOf(variants)
if i != -1 {
// Only replace if it's an override of an internal template.
if !isInternal(name) {
templs.variants[i] = sv
}
} else {
templs.variants = append(templs.variants, sv)
}
}
func (t *templateHandler) addTemplateFile(name, path string) error {
getTemplate := func(filename string) (templateInfo, error) {
fs := t.Layouts.Fs
b, err := afero.ReadFile(fs, filename)
if err != nil {
return templateInfo{filename: filename, fs: fs}, err
}
s := removeLeadingBOM(string(b))
realFilename := filename
if fi, err := fs.Stat(filename); err == nil {
if fim, ok := fi.(hugofs.FileMetaInfo); ok {
realFilename = fim.Meta().Filename()
}
}
var isText bool
name, isText = t.nameIsText(name)
return templateInfo{
name: name,
isText: isText,
template: s,
filename: filename,
realFilename: realFilename,
fs: fs,
}, nil
}
tinfo, err := getTemplate(path)
if err != nil {
return err
}
if isBaseTemplatePath(name) {
// Store it for later.
t.baseof[name] = tinfo
return nil
}
needsBaseof := !t.noBaseNeeded(name) && needsBaseTemplate(tinfo.template)
if needsBaseof {
t.needsBaseof[name] = tinfo
return nil
}
templ, err := t.addTemplateTo(tinfo, t.main)
if err != nil {
return tinfo.errWithFileContext("parse failed", err)
}
t.applyTemplateTransformers(t.main, templ)
return nil
}
func (t *templateHandler) addTemplateTo(info templateInfo, to *templateNamespace) (*templateState, error) {
return to.parse(info)
}
func (t *templateHandler) applyBaseTemplate(overlay, base templateInfo) (tpl.Template, error) {
if overlay.isText {
var (
templ = t.main.prototypeTextClone.New(overlay.name)
err error
)
if !base.IsZero() {
templ, err = templ.Parse(base.template)
if err != nil {
return nil, base.errWithFileContext("parse failed", err)
}
}
templ, err = texttemplate.Must(templ.Clone()).Parse(overlay.template)
if err != nil {
return nil, overlay.errWithFileContext("parse failed", err)
}
// The extra lookup is a workaround, see
// * https://github.com/golang/go/issues/16101
// * https://github.com/gohugoio/hugo/issues/2549
// templ = templ.Lookup(templ.Name())
return templ, nil
}
var (
templ = t.main.prototypeHTMLClone.New(overlay.name)
err error
)
if !base.IsZero() {
templ, err = templ.Parse(base.template)
if err != nil {
return nil, base.errWithFileContext("parse failed", err)
}
}
templ, err = htmltemplate.Must(templ.Clone()).Parse(overlay.template)
if err != nil {
return nil, overlay.errWithFileContext("parse failed", err)
}
// The extra lookup is a workaround, see
// * https://github.com/golang/go/issues/16101
// * https://github.com/gohugoio/hugo/issues/2549
templ = templ.Lookup(templ.Name())
return templ, err
}
func (t *templateHandler) applyTemplateTransformers(ns *templateNamespace, ts *templateState) (*templateContext, error) {
c, err := applyTemplateTransformers(ts, ns.newTemplateLookup(ts))
if err != nil {
return nil, err
}
for k := range c.templateNotFound {
t.transformNotFound[k] = ts
t.identityNotFound[k] = append(t.identityNotFound[k], c.t)
}
for k := range c.identityNotFound {
t.identityNotFound[k] = append(t.identityNotFound[k], c.t)
}
return c, err
}
func (t *templateHandler) extractIdentifiers(line string) []string {
m := identifiersRe.FindAllStringSubmatch(line, -1)
identifiers := make([]string, len(m))
for i := 0; i < len(m); i++ {
identifiers[i] = m[i][1]
}
return identifiers
}
func (t *templateHandler) loadEmbedded() error {
for _, kv := range embedded.EmbeddedTemplates {
name, templ := kv[0], kv[1]
if err := t.AddTemplate(internalPathPrefix+name, templ); err != nil {
return err
}
if aliases, found := embeddedTemplatesAliases[name]; found {
// TODO(bep) avoid reparsing these aliases
for _, alias := range aliases {
alias = internalPathPrefix + alias
if err := t.AddTemplate(alias, templ); err != nil {
return err
}
}
}
}
return nil
}
func (t *templateHandler) loadTemplates() error {
walker := func(path string, fi hugofs.FileMetaInfo, err error) error {
if err != nil || fi.IsDir() {
return err
}
if isDotFile(path) || isBackupFile(path) {
return nil
}
name := strings.TrimPrefix(filepath.ToSlash(path), "/")
filename := filepath.Base(path)
outputFormat, found := t.OutputFormatsConfig.FromFilename(filename)
if found && outputFormat.IsPlainText {
name = textTmplNamePrefix + name
}
if err := t.addTemplateFile(name, path); err != nil {
return err
}
return nil
}
if err := helpers.SymbolicWalk(t.Layouts.Fs, "", walker); err != nil {
if !os.IsNotExist(err) {
return err
}
return nil
}
return nil
}
func (t *templateHandler) nameIsText(name string) (string, bool) {
isText := strings.HasPrefix(name, textTmplNamePrefix)
if isText {
name = strings.TrimPrefix(name, textTmplNamePrefix)
}
return name, isText
}
func (t *templateHandler) noBaseNeeded(name string) bool {
if strings.HasPrefix(name, "shortcodes/") || strings.HasPrefix(name, "partials/") {
return true
}
return strings.Contains(name, "_markup/")
}
func (t *templateHandler) extractPartials(templ tpl.Template) error {
templs := templates(templ)
for _, templ := range templs {
if templ.Name() == "" || !strings.HasPrefix(templ.Name(), "partials/") {
continue
}
ts := newTemplateState(templ, templateInfo{name: templ.Name()})
ts.typ = templatePartial
t.main.mu.RLock()
_, found := t.main.templates[templ.Name()]
t.main.mu.RUnlock()
if !found {
t.main.mu.Lock()
// This is a template defined inline.
_, err := applyTemplateTransformers(ts, t.main.newTemplateLookup(ts))
if err != nil {
t.main.mu.Unlock()
return err
}
t.main.templates[templ.Name()] = ts
t.main.mu.Unlock()
}
}
return nil
}
func (t *templateHandler) postTransform() error {
defineCheckedHTML := false
defineCheckedText := false
for _, v := range t.main.templates {
if v.typ == templateShortcode {
t.addShortcodeVariant(v)
}
if defineCheckedHTML && defineCheckedText {
continue
}
isText := isText(v.Template)
if isText {
if defineCheckedText {
continue
}
defineCheckedText = true
} else {
if defineCheckedHTML {
continue
}
defineCheckedHTML = true
}
if err := t.extractPartials(v.Template); err != nil {
return err
}
}
for name, source := range t.transformNotFound {
lookup := t.main.newTemplateLookup(source)
templ := lookup(name)
if templ != nil {
_, err := applyTemplateTransformers(templ, lookup)
if err != nil {
return err
}
}
}
for k, v := range t.identityNotFound {
ts := t.findTemplate(k)
if ts != nil {
for _, im := range v {
im.Add(ts)
}
}
}
return nil
}
type templateNamespace struct {
prototypeText *texttemplate.Template
prototypeHTML *htmltemplate.Template
prototypeTextClone *texttemplate.Template
prototypeHTMLClone *htmltemplate.Template
*templateStateMap
}
func (t templateNamespace) Clone() *templateNamespace {
t.mu.Lock()
defer t.mu.Unlock()
t.templateStateMap = &templateStateMap{
templates: make(map[string]*templateState),
}
t.prototypeText = texttemplate.Must(t.prototypeText.Clone())
t.prototypeHTML = htmltemplate.Must(t.prototypeHTML.Clone())
return &t
}
func (t *templateNamespace) Lookup(name string) (tpl.Template, bool) {
t.mu.RLock()
defer t.mu.RUnlock()
templ, found := t.templates[name]
if !found {
return nil, false
}
return templ, found
}
func (t *templateNamespace) createPrototypes() error {
t.prototypeTextClone = texttemplate.Must(t.prototypeText.Clone())
t.prototypeHTMLClone = htmltemplate.Must(t.prototypeHTML.Clone())
return nil
}
func (t *templateNamespace) newTemplateLookup(in *templateState) func(name string) *templateState {
return func(name string) *templateState {
if templ, found := t.templates[name]; found {
if templ.isText() != in.isText() {
return nil
}
return templ
}
if templ, found := findTemplateIn(name, in); found {
return newTemplateState(templ, templateInfo{name: templ.Name()})
}
return nil
}
}
func (t *templateNamespace) parse(info templateInfo) (*templateState, error) {
t.mu.Lock()
defer t.mu.Unlock()
if info.isText {
prototype := t.prototypeText
templ, err := prototype.New(info.name).Parse(info.template)
if err != nil {
return nil, err
}
ts := newTemplateState(templ, info)
t.templates[info.name] = ts
return ts, nil
}
prototype := t.prototypeHTML
templ, err := prototype.New(info.name).Parse(info.template)
if err != nil {
return nil, err
}
ts := newTemplateState(templ, info)
t.templates[info.name] = ts
return ts, nil
}
type templateState struct {
tpl.Template
typ templateType
parseInfo tpl.ParseInfo
identity.Manager
info templateInfo
baseInfo templateInfo // Set when a base template is used.
}
func (t *templateState) ParseInfo() tpl.ParseInfo {
return t.parseInfo
}
func (t *templateState) isText() bool {
return isText(t.Template)
}
func isText(templ tpl.Template) bool {
_, isText := templ.(*texttemplate.Template)
return isText
}
type templateStateMap struct {
mu sync.RWMutex
templates map[string]*templateState
}
type templateWrapperWithLock struct {
*sync.RWMutex
tpl.Template
}
type textTemplateWrapperWithLock struct {
*sync.RWMutex
*texttemplate.Template
}
func (t *textTemplateWrapperWithLock) Lookup(name string) (tpl.Template, bool) {
t.RLock()
templ := t.Template.Lookup(name)
t.RUnlock()
if templ == nil {
return nil, false
}
return &textTemplateWrapperWithLock{
RWMutex: t.RWMutex,
Template: templ,
}, true
}
func (t *textTemplateWrapperWithLock) LookupVariant(name string, variants tpl.TemplateVariants) (tpl.Template, bool, bool) {
panic("not supported")
}
func (t *textTemplateWrapperWithLock) LookupVariants(name string) []tpl.Template {
panic("not supported")
}
func (t *textTemplateWrapperWithLock) Parse(name, tpl string) (tpl.Template, error) {
t.Lock()
defer t.Unlock()
return t.Template.New(name).Parse(tpl)
}
func isBackupFile(path string) bool {
return path[len(path)-1] == '~'
}
func isBaseTemplatePath(path string) bool {
return strings.Contains(filepath.Base(path), baseFileBase)
}
func isDotFile(path string) bool {
return filepath.Base(path)[0] == '.'
}
func removeLeadingBOM(s string) string {
const bom = '\ufeff'
for i, r := range s {
if i == 0 && r != bom {
return s
}
if i > 0 {
return s[i:]
}
}
return s
}
// resolves _internal/shortcodes/param.html => param.html etc.
func templateBaseName(typ templateType, name string) string {
name = strings.TrimPrefix(name, internalPathPrefix)
switch typ {
case templateShortcode:
return strings.TrimPrefix(name, shortcodesPathPrefix)
default:
panic("not implemented")
}
}
func unwrap(templ tpl.Template) tpl.Template {
if ts, ok := templ.(*templateState); ok {
return ts.Template
}
return templ
}
func templates(in tpl.Template) []tpl.Template {
var templs []tpl.Template
in = unwrap(in)
if textt, ok := in.(*texttemplate.Template); ok {
for _, t := range textt.Templates() {
templs = append(templs, t)
}
}
if htmlt, ok := in.(*htmltemplate.Template); ok {
for _, t := range htmlt.Templates() {
templs = append(templs, t)
}
}
return templs
}
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./docs/content/en/functions/float.md | ---
title: float
linktitle: float
description: Creates a `float` from the argument passed into the function.
godocref:
date: 2017-09-28
publishdate: 2017-09-28
lastmod: 2017-09-28
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [strings,floats]
signature: ["float INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
Useful for turning strings into floating point numbers.
```
{{ float "1.23" }} → 1.23
```
| ---
title: float
linktitle: float
description: Creates a `float` from the argument passed into the function.
godocref:
date: 2017-09-28
publishdate: 2017-09-28
lastmod: 2017-09-28
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [strings,floats]
signature: ["float INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
Useful for turning strings into floating point numbers.
```
{{ float "1.23" }} → 1.23
```
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./docs/content/en/functions/plainify.md | ---
title: plainify
linktitle: plainify
description: Strips any HTML and returns the plain text version of the provided string.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-30
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [strings]
signature: ["plainify INPUT"]
workson: []
hugoversion:
relatedfuncs: [jsonify]
deprecated: false
aliases: []
---
```
{{ "<b>BatMan</b>" | plainify }} → "BatMan"
```
See also the `.PlainWords`, `.Plain`, and `.RawContent` [page variables][pagevars].
[pagevars]: /variables/page/
| ---
title: plainify
linktitle: plainify
description: Strips any HTML and returns the plain text version of the provided string.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-30
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [strings]
signature: ["plainify INPUT"]
workson: []
hugoversion:
relatedfuncs: [jsonify]
deprecated: false
aliases: []
---
```
{{ "<b>BatMan</b>" | plainify }} → "BatMan"
```
See also the `.PlainWords`, `.Plain`, and `.RawContent` [page variables][pagevars].
[pagevars]: /variables/page/
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./docs/content/en/commands/hugo_mod.md | ---
date: 2021-02-18
title: "hugo mod"
slug: hugo_mod
url: /commands/hugo_mod/
---
## hugo mod
Various Hugo Modules helpers.
### Synopsis
Various helpers to help manage the modules in your project's dependency graph.
Most operations here requires a Go version installed on your system (>= Go 1.12) and the relevant VCS client (typically Git).
This is not needed if you only operate on modules inside /themes or if you have vendored them via "hugo mod vendor".
Note that Hugo will always start out by resolving the components defined in the site
configuration, provided by a _vendor directory (if no --ignoreVendor flag provided),
Go Modules, or a folder inside the themes directory, in that order.
See https://gohugo.io/hugo-modules/ for more information.
### Options
```
-b, --baseURL string hostname (and path) to the root, e.g. http://spf13.com/
-D, --buildDrafts include content marked as draft
-E, --buildExpired include expired content
-F, --buildFuture include content with publishdate in the future
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
--cleanDestinationDir remove files from destination not found in static directories
-c, --contentDir string filesystem path to content directory
-d, --destination string filesystem path to write files to
--disableKinds strings disable different kind of pages (home, RSS etc.)
--enableGitInfo add Git revision, date and author info to the pages
--forceSyncStatic copy all files when static is changed.
--gc enable to run some cleanup tasks (remove unused cache files) after the build
-h, --help help for mod
--i18n-warnings print missing translations
--ignoreCache ignores the cache directory
-l, --layoutDir string filesystem path to layout directory
--minify minify any supported output format (HTML, XML etc.)
--noChmod don't sync permission mode of files
--noTimes don't sync modification time of files
--path-warnings print warnings on duplicate target paths etc.
--print-mem print memory usage to screen at intervals
--templateMetrics display metrics about template executions
--templateMetricsHints calculate some improvement hints when combined with --templateMetrics
-t, --theme strings themes to use (located in /themes/THEMENAME/)
--trace file write trace to file (not useful in general)
```
### Options inherited from parent commands
```
--config string config file (default is path/config.yaml|json|toml)
--configDir string config dir (default "config")
--debug debug output
-e, --environment string build environment
--ignoreVendor ignores any _vendor directory
--ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern
--log enable Logging
--logFile string log File path (if set, logging enabled automatically)
--quiet build in quiet mode
-s, --source string filesystem path to read files relative from
--themesDir string filesystem path to themes directory
-v, --verbose verbose output
--verboseLog verbose logging
```
### SEE ALSO
* [hugo](/commands/hugo/) - hugo builds your site
* [hugo mod clean](/commands/hugo_mod_clean/) - Delete the Hugo Module cache for the current project.
* [hugo mod get](/commands/hugo_mod_get/) - Resolves dependencies in your current Hugo Project.
* [hugo mod graph](/commands/hugo_mod_graph/) - Print a module dependency graph.
* [hugo mod init](/commands/hugo_mod_init/) - Initialize this project as a Hugo Module.
* [hugo mod npm](/commands/hugo_mod_npm/) - Various npm helpers.
* [hugo mod tidy](/commands/hugo_mod_tidy/) - Remove unused entries in go.mod and go.sum.
* [hugo mod vendor](/commands/hugo_mod_vendor/) - Vendor all module dependencies into the _vendor directory.
* [hugo mod verify](/commands/hugo_mod_verify/) - Verify dependencies.
###### Auto generated by spf13/cobra on 18-Feb-2021
| ---
date: 2021-02-18
title: "hugo mod"
slug: hugo_mod
url: /commands/hugo_mod/
---
## hugo mod
Various Hugo Modules helpers.
### Synopsis
Various helpers to help manage the modules in your project's dependency graph.
Most operations here requires a Go version installed on your system (>= Go 1.12) and the relevant VCS client (typically Git).
This is not needed if you only operate on modules inside /themes or if you have vendored them via "hugo mod vendor".
Note that Hugo will always start out by resolving the components defined in the site
configuration, provided by a _vendor directory (if no --ignoreVendor flag provided),
Go Modules, or a folder inside the themes directory, in that order.
See https://gohugo.io/hugo-modules/ for more information.
### Options
```
-b, --baseURL string hostname (and path) to the root, e.g. http://spf13.com/
-D, --buildDrafts include content marked as draft
-E, --buildExpired include expired content
-F, --buildFuture include content with publishdate in the future
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
--cleanDestinationDir remove files from destination not found in static directories
-c, --contentDir string filesystem path to content directory
-d, --destination string filesystem path to write files to
--disableKinds strings disable different kind of pages (home, RSS etc.)
--enableGitInfo add Git revision, date and author info to the pages
--forceSyncStatic copy all files when static is changed.
--gc enable to run some cleanup tasks (remove unused cache files) after the build
-h, --help help for mod
--i18n-warnings print missing translations
--ignoreCache ignores the cache directory
-l, --layoutDir string filesystem path to layout directory
--minify minify any supported output format (HTML, XML etc.)
--noChmod don't sync permission mode of files
--noTimes don't sync modification time of files
--path-warnings print warnings on duplicate target paths etc.
--print-mem print memory usage to screen at intervals
--templateMetrics display metrics about template executions
--templateMetricsHints calculate some improvement hints when combined with --templateMetrics
-t, --theme strings themes to use (located in /themes/THEMENAME/)
--trace file write trace to file (not useful in general)
```
### Options inherited from parent commands
```
--config string config file (default is path/config.yaml|json|toml)
--configDir string config dir (default "config")
--debug debug output
-e, --environment string build environment
--ignoreVendor ignores any _vendor directory
--ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern
--log enable Logging
--logFile string log File path (if set, logging enabled automatically)
--quiet build in quiet mode
-s, --source string filesystem path to read files relative from
--themesDir string filesystem path to themes directory
-v, --verbose verbose output
--verboseLog verbose logging
```
### SEE ALSO
* [hugo](/commands/hugo/) - hugo builds your site
* [hugo mod clean](/commands/hugo_mod_clean/) - Delete the Hugo Module cache for the current project.
* [hugo mod get](/commands/hugo_mod_get/) - Resolves dependencies in your current Hugo Project.
* [hugo mod graph](/commands/hugo_mod_graph/) - Print a module dependency graph.
* [hugo mod init](/commands/hugo_mod_init/) - Initialize this project as a Hugo Module.
* [hugo mod npm](/commands/hugo_mod_npm/) - Various npm helpers.
* [hugo mod tidy](/commands/hugo_mod_tidy/) - Remove unused entries in go.mod and go.sum.
* [hugo mod vendor](/commands/hugo_mod_vendor/) - Vendor all module dependencies into the _vendor directory.
* [hugo mod verify](/commands/hugo_mod_verify/) - Verify dependencies.
###### Auto generated by spf13/cobra on 18-Feb-2021
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./docs/content/en/news/0.69.0-relnotes/index.md |
---
date: 2020-04-10
title: "Post Build Resource Transformations"
description: "Hugo 0.69.0 allows you to delay resource processing to after the build, the prime use case being removal of unused CSS."
categories: ["Releases"]
---
**It's Eeaster, a time for mysteries and puzzles.** And at first glance, this Hugo release looks a little mysterious. The core of if is a mind-twister:
```go-html-template
{{ $css := resources.Get "css/main.css" }}
{{ $css = $css | resources.PostCSS }}
{{ if hugo.IsProduction }}
{{ $css = $css | minify | fingerprint | resources.PostProcess }}
{{ end }}
<link href="{{ $css.RelPermalink }}" rel="stylesheet" />
```
The above uses the new [resources.PostProcess](https://gohugo.io/hugo-pipes/postprocess/) template function which tells Hugo to postpone the transformation of the Hugo Pipes chain to _after the build_, allowing the build steps to use the build output in `/public` as part of its processing.
The prime current use case for the above is CSS pruning in PostCSS. In simple cases you can use the templates as a base for the content filters, but that has its limitations and can be very hard to setup, especially in themed configurations. So we have added a new [writeStats](https://gohugo.io/getting-started/configuration/#configure-build) configuration that, when enabled, will write a file named `hugo_stats.json` to your project root with some aggregated data about the build, e.g. list of HTML entities published, to be used to do [CSS pruning](https://gohugo.io/hugo-pipes/postprocess/#css-purging-with-postcss).
This release represents **20 contributions by 10 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 [@moorereason](https://github.com/moorereason), [@jaywilliams](https://github.com/jaywilliams), and [@satotake](https://github.com/satotake) for their ongoing contributions.
And a big thanks to [@digitalcraftsman](https://github.com/digitalcraftsman) and [@onedrawingperday](https://github.com/onedrawingperday) for their relentless work on keeping the themes site in pristine condition and to [@davidsneighbour](https://github.com/davidsneighbour) and [@kaushalmodi](https://github.com/kaushalmodi) for all the great work on the documentation site.
Many have also been busy writing and fixing the documentation in [hugoDocs](https://github.com/gohugoio/hugoDocs),
which has received **14 contributions by 7 contributors**. A special thanks to [@bep](https://github.com/bep), [@coliff](https://github.com/coliff), [@dmgawel](https://github.com/dmgawel), and [@jasikpark](https://github.com/jasikpark) for their work on the documentation site.
Hugo now has:
* 43052+ [stars](https://github.com/gohugoio/hugo/stargazers)
* 438+ [contributors](https://github.com/gohugoio/hugo/graphs/contributors)
* 302+ [themes](http://themes.gohugo.io/)
## Enhancements
### Templates
* Extend Jsonify to support options map [8568928a](https://github.com/gohugoio/hugo/commit/8568928aa8e82a6bd7de4555c3703d8835fbd25b) [@moorereason](https://github.com/moorereason)
* Extend Jsonify to support optional indent parameter [1bc93021](https://github.com/gohugoio/hugo/commit/1bc93021e3dca6405628f6fdd2dc32cff9c9836c) [@moorereason](https://github.com/moorereason) [#5040](https://github.com/gohugoio/hugo/issues/5040)
### Other
* Regen docs helper [b7ff4dc2](https://github.com/gohugoio/hugo/commit/b7ff4dc23e6314fd09ee2c1e24cde96fc833164e) [@bep](https://github.com/bep)
* Collect HTML elements during the build to use in PurgeCSS etc. [095bf64c](https://github.com/gohugoio/hugo/commit/095bf64c99f57efe083540a50e658808a0a1c32b) [@bep](https://github.com/bep) [#6999](https://github.com/gohugoio/hugo/issues/6999)
* Update to latest emoji package [7791a804](https://github.com/gohugoio/hugo/commit/7791a804e2179667617b3b145b0fe7eba17627a1) [@QuLogic](https://github.com/QuLogic)
* Update hosting-on-aws-amplify.md [c774b230](https://github.com/gohugoio/hugo/commit/c774b230e941902675af081f118ea206a4f2a04e) [@Helicer](https://github.com/Helicer)
* Add basic "post resource publish support" [2f721f8e](https://github.com/gohugoio/hugo/commit/2f721f8ec69c52202815cd1b543ca4bf535c0901) [@bep](https://github.com/bep) [#7146](https://github.com/gohugoio/hugo/issues/7146)
* Typo correction [7eba37ae](https://github.com/gohugoio/hugo/commit/7eba37ae9b8653be4fc21a0dbbc6f35ca5b9280e) [@fekete-robert](https://github.com/fekete-robert)
* Use semver for min_version per recommendations [efc61d6f](https://github.com/gohugoio/hugo/commit/efc61d6f3b9f5fb294411ac1dc872b8fc5bdbacb) [@jaywilliams](https://github.com/jaywilliams)
* Updateto gitmap v1.1.2 [4de3ecdc](https://github.com/gohugoio/hugo/commit/4de3ecdc2658ffd54d2b5073c5ff303b4bf29383) [@dragtor](https://github.com/dragtor) [#6985](https://github.com/gohugoio/hugo/issues/6985)
* Add data context to the key in ExecuteAsTemplate" [c9dc316a](https://github.com/gohugoio/hugo/commit/c9dc316ad160e78c9dff4e75313db4cac8ea6414) [@bep](https://github.com/bep) [#7064](https://github.com/gohugoio/hugo/issues/7064)
## Fixes
### Other
* Fix hugo mod vendor for regular file mounts [d8d6a25b](https://github.com/gohugoio/hugo/commit/d8d6a25b5755bedaf90261a1539dc37a2f05c3df) [@bep](https://github.com/bep) [#7140](https://github.com/gohugoio/hugo/issues/7140)
* Revert "Revert "common/herrors: Fix typos in comments"" [9f12be54](https://github.com/gohugoio/hugo/commit/9f12be54ee84f24efdf7c58f05867e8d0dea2ccb) [@bep](https://github.com/bep)
* Fix typos in comments" [4437e918](https://github.com/gohugoio/hugo/commit/4437e918cdab1d84f2f184fe71e5dac14aa48897) [@bep](https://github.com/bep)
* Fix typos in comments [1123711b](https://github.com/gohugoio/hugo/commit/1123711b0979b1647d7c486f67af7503afb11abb) [@rnazmo](https://github.com/rnazmo)
* Fix TrimShortHTML [9c998753](https://github.com/gohugoio/hugo/commit/9c9987535f98714c8a4ec98903f54233735ef0e4) [@satotake](https://github.com/satotake) [#7081](https://github.com/gohugoio/hugo/issues/7081)
* Fix IsDescendant/IsAncestor for overlapping section names [4a39564e](https://github.com/gohugoio/hugo/commit/4a39564efe7b02a685598ae9dbae95e2326c0230) [@bep](https://github.com/bep) [#7096](https://github.com/gohugoio/hugo/issues/7096)
* fix typo in getting started [b6e097cf](https://github.com/gohugoio/hugo/commit/b6e097cfe65ecd1d47c805969082e6805563612b) [@matrixise](https://github.com/matrixise)
* Fix _build.list.local logic [523d5194](https://github.com/gohugoio/hugo/commit/523d51948fc20e2afb4721b43203c5ab696ae220) [@bep](https://github.com/bep) [#7089](https://github.com/gohugoio/hugo/issues/7089)
* Fix cache reset for a page's collections on server live reload [cfa73050](https://github.com/gohugoio/hugo/commit/cfa73050a49b2646fe3557cefa0ed31989b0eeeb) [@bep](https://github.com/bep) [#7085](https://github.com/gohugoio/hugo/issues/7085)
|
---
date: 2020-04-10
title: "Post Build Resource Transformations"
description: "Hugo 0.69.0 allows you to delay resource processing to after the build, the prime use case being removal of unused CSS."
categories: ["Releases"]
---
**It's Eeaster, a time for mysteries and puzzles.** And at first glance, this Hugo release looks a little mysterious. The core of if is a mind-twister:
```go-html-template
{{ $css := resources.Get "css/main.css" }}
{{ $css = $css | resources.PostCSS }}
{{ if hugo.IsProduction }}
{{ $css = $css | minify | fingerprint | resources.PostProcess }}
{{ end }}
<link href="{{ $css.RelPermalink }}" rel="stylesheet" />
```
The above uses the new [resources.PostProcess](https://gohugo.io/hugo-pipes/postprocess/) template function which tells Hugo to postpone the transformation of the Hugo Pipes chain to _after the build_, allowing the build steps to use the build output in `/public` as part of its processing.
The prime current use case for the above is CSS pruning in PostCSS. In simple cases you can use the templates as a base for the content filters, but that has its limitations and can be very hard to setup, especially in themed configurations. So we have added a new [writeStats](https://gohugo.io/getting-started/configuration/#configure-build) configuration that, when enabled, will write a file named `hugo_stats.json` to your project root with some aggregated data about the build, e.g. list of HTML entities published, to be used to do [CSS pruning](https://gohugo.io/hugo-pipes/postprocess/#css-purging-with-postcss).
This release represents **20 contributions by 10 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 [@moorereason](https://github.com/moorereason), [@jaywilliams](https://github.com/jaywilliams), and [@satotake](https://github.com/satotake) for their ongoing contributions.
And a big thanks to [@digitalcraftsman](https://github.com/digitalcraftsman) and [@onedrawingperday](https://github.com/onedrawingperday) for their relentless work on keeping the themes site in pristine condition and to [@davidsneighbour](https://github.com/davidsneighbour) and [@kaushalmodi](https://github.com/kaushalmodi) for all the great work on the documentation site.
Many have also been busy writing and fixing the documentation in [hugoDocs](https://github.com/gohugoio/hugoDocs),
which has received **14 contributions by 7 contributors**. A special thanks to [@bep](https://github.com/bep), [@coliff](https://github.com/coliff), [@dmgawel](https://github.com/dmgawel), and [@jasikpark](https://github.com/jasikpark) for their work on the documentation site.
Hugo now has:
* 43052+ [stars](https://github.com/gohugoio/hugo/stargazers)
* 438+ [contributors](https://github.com/gohugoio/hugo/graphs/contributors)
* 302+ [themes](http://themes.gohugo.io/)
## Enhancements
### Templates
* Extend Jsonify to support options map [8568928a](https://github.com/gohugoio/hugo/commit/8568928aa8e82a6bd7de4555c3703d8835fbd25b) [@moorereason](https://github.com/moorereason)
* Extend Jsonify to support optional indent parameter [1bc93021](https://github.com/gohugoio/hugo/commit/1bc93021e3dca6405628f6fdd2dc32cff9c9836c) [@moorereason](https://github.com/moorereason) [#5040](https://github.com/gohugoio/hugo/issues/5040)
### Other
* Regen docs helper [b7ff4dc2](https://github.com/gohugoio/hugo/commit/b7ff4dc23e6314fd09ee2c1e24cde96fc833164e) [@bep](https://github.com/bep)
* Collect HTML elements during the build to use in PurgeCSS etc. [095bf64c](https://github.com/gohugoio/hugo/commit/095bf64c99f57efe083540a50e658808a0a1c32b) [@bep](https://github.com/bep) [#6999](https://github.com/gohugoio/hugo/issues/6999)
* Update to latest emoji package [7791a804](https://github.com/gohugoio/hugo/commit/7791a804e2179667617b3b145b0fe7eba17627a1) [@QuLogic](https://github.com/QuLogic)
* Update hosting-on-aws-amplify.md [c774b230](https://github.com/gohugoio/hugo/commit/c774b230e941902675af081f118ea206a4f2a04e) [@Helicer](https://github.com/Helicer)
* Add basic "post resource publish support" [2f721f8e](https://github.com/gohugoio/hugo/commit/2f721f8ec69c52202815cd1b543ca4bf535c0901) [@bep](https://github.com/bep) [#7146](https://github.com/gohugoio/hugo/issues/7146)
* Typo correction [7eba37ae](https://github.com/gohugoio/hugo/commit/7eba37ae9b8653be4fc21a0dbbc6f35ca5b9280e) [@fekete-robert](https://github.com/fekete-robert)
* Use semver for min_version per recommendations [efc61d6f](https://github.com/gohugoio/hugo/commit/efc61d6f3b9f5fb294411ac1dc872b8fc5bdbacb) [@jaywilliams](https://github.com/jaywilliams)
* Updateto gitmap v1.1.2 [4de3ecdc](https://github.com/gohugoio/hugo/commit/4de3ecdc2658ffd54d2b5073c5ff303b4bf29383) [@dragtor](https://github.com/dragtor) [#6985](https://github.com/gohugoio/hugo/issues/6985)
* Add data context to the key in ExecuteAsTemplate" [c9dc316a](https://github.com/gohugoio/hugo/commit/c9dc316ad160e78c9dff4e75313db4cac8ea6414) [@bep](https://github.com/bep) [#7064](https://github.com/gohugoio/hugo/issues/7064)
## Fixes
### Other
* Fix hugo mod vendor for regular file mounts [d8d6a25b](https://github.com/gohugoio/hugo/commit/d8d6a25b5755bedaf90261a1539dc37a2f05c3df) [@bep](https://github.com/bep) [#7140](https://github.com/gohugoio/hugo/issues/7140)
* Revert "Revert "common/herrors: Fix typos in comments"" [9f12be54](https://github.com/gohugoio/hugo/commit/9f12be54ee84f24efdf7c58f05867e8d0dea2ccb) [@bep](https://github.com/bep)
* Fix typos in comments" [4437e918](https://github.com/gohugoio/hugo/commit/4437e918cdab1d84f2f184fe71e5dac14aa48897) [@bep](https://github.com/bep)
* Fix typos in comments [1123711b](https://github.com/gohugoio/hugo/commit/1123711b0979b1647d7c486f67af7503afb11abb) [@rnazmo](https://github.com/rnazmo)
* Fix TrimShortHTML [9c998753](https://github.com/gohugoio/hugo/commit/9c9987535f98714c8a4ec98903f54233735ef0e4) [@satotake](https://github.com/satotake) [#7081](https://github.com/gohugoio/hugo/issues/7081)
* Fix IsDescendant/IsAncestor for overlapping section names [4a39564e](https://github.com/gohugoio/hugo/commit/4a39564efe7b02a685598ae9dbae95e2326c0230) [@bep](https://github.com/bep) [#7096](https://github.com/gohugoio/hugo/issues/7096)
* fix typo in getting started [b6e097cf](https://github.com/gohugoio/hugo/commit/b6e097cfe65ecd1d47c805969082e6805563612b) [@matrixise](https://github.com/matrixise)
* Fix _build.list.local logic [523d5194](https://github.com/gohugoio/hugo/commit/523d51948fc20e2afb4721b43203c5ab696ae220) [@bep](https://github.com/bep) [#7089](https://github.com/gohugoio/hugo/issues/7089)
* Fix cache reset for a page's collections on server live reload [cfa73050](https://github.com/gohugoio/hugo/commit/cfa73050a49b2646fe3557cefa0ed31989b0eeeb) [@bep](https://github.com/bep) [#7085](https://github.com/gohugoio/hugo/issues/7085)
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./hugolib/site_stats_test.go | // Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"bytes"
"fmt"
"io/ioutil"
"testing"
"github.com/gohugoio/hugo/helpers"
qt "github.com/frankban/quicktest"
)
func TestSiteStats(t *testing.T) {
t.Parallel()
c := qt.New(t)
siteConfig := `
baseURL = "http://example.com/blog"
paginate = 1
defaultContentLanguage = "nn"
[languages]
[languages.nn]
languageName = "Nynorsk"
weight = 1
title = "Hugo på norsk"
[languages.en]
languageName = "English"
weight = 2
title = "Hugo in English"
`
pageTemplate := `---
title: "T%d"
tags:
%s
categories:
%s
aliases: [/Ali%d]
---
# Doc
`
b := newTestSitesBuilder(t).WithConfigFile("toml", siteConfig)
b.WithTemplates(
"_default/single.html", "Single|{{ .Title }}|{{ .Content }}",
"_default/list.html", `List|{{ .Title }}|Pages: {{ .Paginator.TotalPages }}|{{ .Content }}`,
"_default/terms.html", "Terms List|{{ .Title }}|{{ .Content }}",
)
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
pageID := i + j + 1
b.WithContent(fmt.Sprintf("content/sect/p%d.md", pageID),
fmt.Sprintf(pageTemplate, pageID, fmt.Sprintf("- tag%d", j), fmt.Sprintf("- category%d", j), pageID))
}
}
for i := 0; i < 5; i++ {
b.WithContent(fmt.Sprintf("assets/image%d.png", i+1), "image")
}
b.Build(BuildCfg{})
h := b.H
stats := []*helpers.ProcessingStats{
h.Sites[0].PathSpec.ProcessingStats,
h.Sites[1].PathSpec.ProcessingStats,
}
stats[0].Table(ioutil.Discard)
stats[1].Table(ioutil.Discard)
var buff bytes.Buffer
helpers.ProcessingStatsTable(&buff, stats...)
c.Assert(buff.String(), qt.Contains, "Pages | 19 | 6")
}
| // Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"bytes"
"fmt"
"io/ioutil"
"testing"
"github.com/gohugoio/hugo/helpers"
qt "github.com/frankban/quicktest"
)
func TestSiteStats(t *testing.T) {
t.Parallel()
c := qt.New(t)
siteConfig := `
baseURL = "http://example.com/blog"
paginate = 1
defaultContentLanguage = "nn"
[languages]
[languages.nn]
languageName = "Nynorsk"
weight = 1
title = "Hugo på norsk"
[languages.en]
languageName = "English"
weight = 2
title = "Hugo in English"
`
pageTemplate := `---
title: "T%d"
tags:
%s
categories:
%s
aliases: [/Ali%d]
---
# Doc
`
b := newTestSitesBuilder(t).WithConfigFile("toml", siteConfig)
b.WithTemplates(
"_default/single.html", "Single|{{ .Title }}|{{ .Content }}",
"_default/list.html", `List|{{ .Title }}|Pages: {{ .Paginator.TotalPages }}|{{ .Content }}`,
"_default/terms.html", "Terms List|{{ .Title }}|{{ .Content }}",
)
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
pageID := i + j + 1
b.WithContent(fmt.Sprintf("content/sect/p%d.md", pageID),
fmt.Sprintf(pageTemplate, pageID, fmt.Sprintf("- tag%d", j), fmt.Sprintf("- category%d", j), pageID))
}
}
for i := 0; i < 5; i++ {
b.WithContent(fmt.Sprintf("assets/image%d.png", i+1), "image")
}
b.Build(BuildCfg{})
h := b.H
stats := []*helpers.ProcessingStats{
h.Sites[0].PathSpec.ProcessingStats,
h.Sites[1].PathSpec.ProcessingStats,
}
stats[0].Table(ioutil.Discard)
stats[1].Table(ioutil.Discard)
var buff bytes.Buffer
helpers.ProcessingStatsTable(&buff, stats...)
c.Assert(buff.String(), qt.Contains, "Pages | 19 | 6")
}
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./commands/genautocomplete.go | // Copyright 2015 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package commands
import (
"io"
"os"
"github.com/spf13/cobra"
jww "github.com/spf13/jwalterweatherman"
)
var _ cmder = (*genautocompleteCmd)(nil)
type genautocompleteCmd struct {
autocompleteTarget string
// bash, zsh, fish or powershell
autocompleteType string
*baseCmd
}
func newGenautocompleteCmd() *genautocompleteCmd {
cc := &genautocompleteCmd{}
cc.baseCmd = newBaseCmd(&cobra.Command{
Use: "autocomplete",
Short: "Generate shell autocompletion script for Hugo",
Long: `Generates a shell autocompletion script for Hugo.
The script is written to the console (stdout).
To write to file, add the ` + "`--completionfile=/path/to/file`" + ` flag.
Add ` + "`--type={bash, zsh, fish or powershell}`" + ` flag to set alternative
shell type.
Logout and in again to reload the completion scripts,
or just source them in directly:
$ . /etc/bash_completion or /path/to/file`,
RunE: func(cmd *cobra.Command, args []string) error {
var err error
var target io.Writer
if cc.autocompleteTarget == "" {
target = os.Stdout
} else {
target, _ = os.OpenFile(cc.autocompleteTarget, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
}
switch cc.autocompleteType {
case "bash":
err = cmd.Root().GenBashCompletion(target)
case "zsh":
err = cmd.Root().GenZshCompletion(target)
case "fish":
err = cmd.Root().GenFishCompletion(target, true)
case "powershell":
err = cmd.Root().GenPowerShellCompletion(target)
default:
return newUserError("Unsupported completion type")
}
if err != nil {
return err
}
if cc.autocompleteTarget != "" {
jww.FEEDBACK.Println(cc.autocompleteType+" completion file for Hugo saved to", cc.autocompleteTarget)
}
return nil
},
})
cc.cmd.PersistentFlags().StringVarP(&cc.autocompleteTarget, "completionfile", "f", "", "autocompletion file, defaults to stdout")
cc.cmd.PersistentFlags().StringVarP(&cc.autocompleteType, "type", "t", "bash", "autocompletion type (bash, zsh, fish, or powershell)")
return cc
}
| // Copyright 2015 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package commands
import (
"io"
"os"
"github.com/spf13/cobra"
jww "github.com/spf13/jwalterweatherman"
)
var _ cmder = (*genautocompleteCmd)(nil)
type genautocompleteCmd struct {
autocompleteTarget string
// bash, zsh, fish or powershell
autocompleteType string
*baseCmd
}
func newGenautocompleteCmd() *genautocompleteCmd {
cc := &genautocompleteCmd{}
cc.baseCmd = newBaseCmd(&cobra.Command{
Use: "autocomplete",
Short: "Generate shell autocompletion script for Hugo",
Long: `Generates a shell autocompletion script for Hugo.
The script is written to the console (stdout).
To write to file, add the ` + "`--completionfile=/path/to/file`" + ` flag.
Add ` + "`--type={bash, zsh, fish or powershell}`" + ` flag to set alternative
shell type.
Logout and in again to reload the completion scripts,
or just source them in directly:
$ . /etc/bash_completion or /path/to/file`,
RunE: func(cmd *cobra.Command, args []string) error {
var err error
var target io.Writer
if cc.autocompleteTarget == "" {
target = os.Stdout
} else {
target, _ = os.OpenFile(cc.autocompleteTarget, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
}
switch cc.autocompleteType {
case "bash":
err = cmd.Root().GenBashCompletion(target)
case "zsh":
err = cmd.Root().GenZshCompletion(target)
case "fish":
err = cmd.Root().GenFishCompletion(target, true)
case "powershell":
err = cmd.Root().GenPowerShellCompletion(target)
default:
return newUserError("Unsupported completion type")
}
if err != nil {
return err
}
if cc.autocompleteTarget != "" {
jww.FEEDBACK.Println(cc.autocompleteType+" completion file for Hugo saved to", cc.autocompleteTarget)
}
return nil
},
})
cc.cmd.PersistentFlags().StringVarP(&cc.autocompleteTarget, "completionfile", "f", "", "autocompletion file, defaults to stdout")
cc.cmd.PersistentFlags().StringVarP(&cc.autocompleteType, "type", "t", "bash", "autocompletion type (bash, zsh, fish, or powershell)")
return cc
}
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./output/outputFormat.go | // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package output
import (
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/gohugoio/hugo/media"
)
// Format represents an output representation, usually to a file on disk.
type Format struct {
// The Name is used as an identifier. Internal output formats (i.e. HTML and RSS)
// can be overridden by providing a new definition for those types.
Name string `json:"name"`
MediaType media.Type `json:"mediaType"`
// Must be set to a value when there are two or more conflicting mediatype for the same resource.
Path string `json:"path"`
// The base output file name used when not using "ugly URLs", defaults to "index".
BaseName string `json:"baseName"`
// The value to use for rel links
//
// See https://www.w3schools.com/tags/att_link_rel.asp
//
// AMP has a special requirement in this department, see:
// https://www.ampproject.org/docs/guides/deploy/discovery
// I.e.:
// <link rel="amphtml" href="https://www.example.com/url/to/amp/document.html">
Rel string `json:"rel"`
// The protocol to use, i.e. "webcal://". Defaults to the protocol of the baseURL.
Protocol string `json:"protocol"`
// IsPlainText decides whether to use text/template or html/template
// as template parser.
IsPlainText bool `json:"isPlainText"`
// IsHTML returns whether this format is int the HTML family. This includes
// HTML, AMP etc. This is used to decide when to create alias redirects etc.
IsHTML bool `json:"isHTML"`
// Enable to ignore the global uglyURLs setting.
NoUgly bool `json:"noUgly"`
// Enable if it doesn't make sense to include this format in an alternative
// format listing, CSS being one good example.
// Note that we use the term "alternative" and not "alternate" here, as it
// does not necessarily replace the other format, it is an alternative representation.
NotAlternative bool `json:"notAlternative"`
// Setting this will make this output format control the value of
// .Permalink and .RelPermalink for a rendered Page.
// If not set, these values will point to the main (first) output format
// configured. That is probably the behaviour you want in most situations,
// as you probably don't want to link back to the RSS version of a page, as an
// example. AMP would, however, be a good example of an output format where this
// behaviour is wanted.
Permalinkable bool `json:"permalinkable"`
// Setting this to a non-zero value will be used as the first sort criteria.
Weight int `json:"weight"`
}
// An ordered list of built-in output formats.
var (
AMPFormat = Format{
Name: "AMP",
MediaType: media.HTMLType,
BaseName: "index",
Path: "amp",
Rel: "amphtml",
IsHTML: true,
Permalinkable: true,
// See https://www.ampproject.org/learn/overview/
}
CalendarFormat = Format{
Name: "Calendar",
MediaType: media.CalendarType,
IsPlainText: true,
Protocol: "webcal://",
BaseName: "index",
Rel: "alternate",
}
CSSFormat = Format{
Name: "CSS",
MediaType: media.CSSType,
BaseName: "styles",
IsPlainText: true,
Rel: "stylesheet",
NotAlternative: true,
}
CSVFormat = Format{
Name: "CSV",
MediaType: media.CSVType,
BaseName: "index",
IsPlainText: true,
Rel: "alternate",
}
HTMLFormat = Format{
Name: "HTML",
MediaType: media.HTMLType,
BaseName: "index",
Rel: "canonical",
IsHTML: true,
Permalinkable: true,
// Weight will be used as first sort criteria. HTML will, by default,
// be rendered first, but set it to 10 so it's easy to put one above it.
Weight: 10,
}
JSONFormat = Format{
Name: "JSON",
MediaType: media.JSONType,
BaseName: "index",
IsPlainText: true,
Rel: "alternate",
}
RobotsTxtFormat = Format{
Name: "ROBOTS",
MediaType: media.TextType,
BaseName: "robots",
IsPlainText: true,
Rel: "alternate",
}
RSSFormat = Format{
Name: "RSS",
MediaType: media.RSSType,
BaseName: "index",
NoUgly: true,
Rel: "alternate",
}
SitemapFormat = Format{
Name: "Sitemap",
MediaType: media.XMLType,
BaseName: "sitemap",
NoUgly: true,
Rel: "sitemap",
}
)
// DefaultFormats contains the default output formats supported by Hugo.
var DefaultFormats = Formats{
AMPFormat,
CalendarFormat,
CSSFormat,
CSVFormat,
HTMLFormat,
JSONFormat,
RobotsTxtFormat,
RSSFormat,
SitemapFormat,
}
func init() {
sort.Sort(DefaultFormats)
}
// Formats is a slice of Format.
type Formats []Format
func (formats Formats) Len() int { return len(formats) }
func (formats Formats) Swap(i, j int) { formats[i], formats[j] = formats[j], formats[i] }
func (formats Formats) Less(i, j int) bool {
fi, fj := formats[i], formats[j]
if fi.Weight == fj.Weight {
return fi.Name < fj.Name
}
if fj.Weight == 0 {
return true
}
return fi.Weight > 0 && fi.Weight < fj.Weight
}
// GetBySuffix gets a output format given as suffix, e.g. "html".
// It will return false if no format could be found, or if the suffix given
// is ambiguous.
// The lookup is case insensitive.
func (formats Formats) GetBySuffix(suffix string) (f Format, found bool) {
for _, ff := range formats {
if strings.EqualFold(suffix, ff.MediaType.Suffix()) {
if found {
// ambiguous
found = false
return
}
f = ff
found = true
}
}
return
}
// GetByName gets a format by its identifier name.
func (formats Formats) GetByName(name string) (f Format, found bool) {
for _, ff := range formats {
if strings.EqualFold(name, ff.Name) {
f = ff
found = true
return
}
}
return
}
// GetByNames gets a list of formats given a list of identifiers.
func (formats Formats) GetByNames(names ...string) (Formats, error) {
var types []Format
for _, name := range names {
tpe, ok := formats.GetByName(name)
if !ok {
return types, fmt.Errorf("OutputFormat with key %q not found", name)
}
types = append(types, tpe)
}
return types, nil
}
// FromFilename gets a Format given a filename.
func (formats Formats) FromFilename(filename string) (f Format, found bool) {
// mytemplate.amp.html
// mytemplate.html
// mytemplate
var ext, outFormat string
parts := strings.Split(filename, ".")
if len(parts) > 2 {
outFormat = parts[1]
ext = parts[2]
} else if len(parts) > 1 {
ext = parts[1]
}
if outFormat != "" {
return formats.GetByName(outFormat)
}
if ext != "" {
f, found = formats.GetBySuffix(ext)
if !found && len(parts) == 2 {
// For extensionless output formats (e.g. Netlify's _redirects)
// we must fall back to using the extension as format lookup.
f, found = formats.GetByName(ext)
}
}
return
}
// DecodeFormats takes a list of output format configurations and merges those,
// in the order given, with the Hugo defaults as the last resort.
func DecodeFormats(mediaTypes media.Types, maps ...map[string]interface{}) (Formats, error) {
f := make(Formats, len(DefaultFormats))
copy(f, DefaultFormats)
for _, m := range maps {
for k, v := range m {
found := false
for i, vv := range f {
if strings.EqualFold(k, vv.Name) {
// Merge it with the existing
if err := decode(mediaTypes, v, &f[i]); err != nil {
return f, err
}
found = true
}
}
if !found {
var newOutFormat Format
newOutFormat.Name = k
if err := decode(mediaTypes, v, &newOutFormat); err != nil {
return f, err
}
// We need values for these
if newOutFormat.BaseName == "" {
newOutFormat.BaseName = "index"
}
if newOutFormat.Rel == "" {
newOutFormat.Rel = "alternate"
}
f = append(f, newOutFormat)
}
}
}
sort.Sort(f)
return f, nil
}
func decode(mediaTypes media.Types, input, output interface{}) error {
config := &mapstructure.DecoderConfig{
Metadata: nil,
Result: output,
WeaklyTypedInput: true,
DecodeHook: func(a reflect.Type, b reflect.Type, c interface{}) (interface{}, error) {
if a.Kind() == reflect.Map {
dataVal := reflect.Indirect(reflect.ValueOf(c))
for _, key := range dataVal.MapKeys() {
keyStr, ok := key.Interface().(string)
if !ok {
// Not a string key
continue
}
if strings.EqualFold(keyStr, "mediaType") {
// If mediaType is a string, look it up and replace it
// in the map.
vv := dataVal.MapIndex(key)
if mediaTypeStr, ok := vv.Interface().(string); ok {
mediaType, found := mediaTypes.GetByType(mediaTypeStr)
if !found {
return c, fmt.Errorf("media type %q not found", mediaTypeStr)
}
dataVal.SetMapIndex(key, reflect.ValueOf(mediaType))
}
}
}
}
return c, nil
},
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
}
// BaseFilename returns the base filename of f including an extension (ie.
// "index.xml").
func (f Format) BaseFilename() string {
return f.BaseName + f.MediaType.FullSuffix()
}
// MarshalJSON returns the JSON encoding of f.
func (f Format) MarshalJSON() ([]byte, error) {
type Alias Format
return json.Marshal(&struct {
MediaType string
Alias
}{
MediaType: f.MediaType.String(),
Alias: (Alias)(f),
})
}
| // Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package output
import (
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/gohugoio/hugo/media"
)
// Format represents an output representation, usually to a file on disk.
type Format struct {
// The Name is used as an identifier. Internal output formats (i.e. HTML and RSS)
// can be overridden by providing a new definition for those types.
Name string `json:"name"`
MediaType media.Type `json:"mediaType"`
// Must be set to a value when there are two or more conflicting mediatype for the same resource.
Path string `json:"path"`
// The base output file name used when not using "ugly URLs", defaults to "index".
BaseName string `json:"baseName"`
// The value to use for rel links
//
// See https://www.w3schools.com/tags/att_link_rel.asp
//
// AMP has a special requirement in this department, see:
// https://www.ampproject.org/docs/guides/deploy/discovery
// I.e.:
// <link rel="amphtml" href="https://www.example.com/url/to/amp/document.html">
Rel string `json:"rel"`
// The protocol to use, i.e. "webcal://". Defaults to the protocol of the baseURL.
Protocol string `json:"protocol"`
// IsPlainText decides whether to use text/template or html/template
// as template parser.
IsPlainText bool `json:"isPlainText"`
// IsHTML returns whether this format is int the HTML family. This includes
// HTML, AMP etc. This is used to decide when to create alias redirects etc.
IsHTML bool `json:"isHTML"`
// Enable to ignore the global uglyURLs setting.
NoUgly bool `json:"noUgly"`
// Enable if it doesn't make sense to include this format in an alternative
// format listing, CSS being one good example.
// Note that we use the term "alternative" and not "alternate" here, as it
// does not necessarily replace the other format, it is an alternative representation.
NotAlternative bool `json:"notAlternative"`
// Setting this will make this output format control the value of
// .Permalink and .RelPermalink for a rendered Page.
// If not set, these values will point to the main (first) output format
// configured. That is probably the behaviour you want in most situations,
// as you probably don't want to link back to the RSS version of a page, as an
// example. AMP would, however, be a good example of an output format where this
// behaviour is wanted.
Permalinkable bool `json:"permalinkable"`
// Setting this to a non-zero value will be used as the first sort criteria.
Weight int `json:"weight"`
}
// An ordered list of built-in output formats.
var (
AMPFormat = Format{
Name: "AMP",
MediaType: media.HTMLType,
BaseName: "index",
Path: "amp",
Rel: "amphtml",
IsHTML: true,
Permalinkable: true,
// See https://www.ampproject.org/learn/overview/
}
CalendarFormat = Format{
Name: "Calendar",
MediaType: media.CalendarType,
IsPlainText: true,
Protocol: "webcal://",
BaseName: "index",
Rel: "alternate",
}
CSSFormat = Format{
Name: "CSS",
MediaType: media.CSSType,
BaseName: "styles",
IsPlainText: true,
Rel: "stylesheet",
NotAlternative: true,
}
CSVFormat = Format{
Name: "CSV",
MediaType: media.CSVType,
BaseName: "index",
IsPlainText: true,
Rel: "alternate",
}
HTMLFormat = Format{
Name: "HTML",
MediaType: media.HTMLType,
BaseName: "index",
Rel: "canonical",
IsHTML: true,
Permalinkable: true,
// Weight will be used as first sort criteria. HTML will, by default,
// be rendered first, but set it to 10 so it's easy to put one above it.
Weight: 10,
}
JSONFormat = Format{
Name: "JSON",
MediaType: media.JSONType,
BaseName: "index",
IsPlainText: true,
Rel: "alternate",
}
RobotsTxtFormat = Format{
Name: "ROBOTS",
MediaType: media.TextType,
BaseName: "robots",
IsPlainText: true,
Rel: "alternate",
}
RSSFormat = Format{
Name: "RSS",
MediaType: media.RSSType,
BaseName: "index",
NoUgly: true,
Rel: "alternate",
}
SitemapFormat = Format{
Name: "Sitemap",
MediaType: media.XMLType,
BaseName: "sitemap",
NoUgly: true,
Rel: "sitemap",
}
)
// DefaultFormats contains the default output formats supported by Hugo.
var DefaultFormats = Formats{
AMPFormat,
CalendarFormat,
CSSFormat,
CSVFormat,
HTMLFormat,
JSONFormat,
RobotsTxtFormat,
RSSFormat,
SitemapFormat,
}
func init() {
sort.Sort(DefaultFormats)
}
// Formats is a slice of Format.
type Formats []Format
func (formats Formats) Len() int { return len(formats) }
func (formats Formats) Swap(i, j int) { formats[i], formats[j] = formats[j], formats[i] }
func (formats Formats) Less(i, j int) bool {
fi, fj := formats[i], formats[j]
if fi.Weight == fj.Weight {
return fi.Name < fj.Name
}
if fj.Weight == 0 {
return true
}
return fi.Weight > 0 && fi.Weight < fj.Weight
}
// GetBySuffix gets a output format given as suffix, e.g. "html".
// It will return false if no format could be found, or if the suffix given
// is ambiguous.
// The lookup is case insensitive.
func (formats Formats) GetBySuffix(suffix string) (f Format, found bool) {
for _, ff := range formats {
if strings.EqualFold(suffix, ff.MediaType.Suffix()) {
if found {
// ambiguous
found = false
return
}
f = ff
found = true
}
}
return
}
// GetByName gets a format by its identifier name.
func (formats Formats) GetByName(name string) (f Format, found bool) {
for _, ff := range formats {
if strings.EqualFold(name, ff.Name) {
f = ff
found = true
return
}
}
return
}
// GetByNames gets a list of formats given a list of identifiers.
func (formats Formats) GetByNames(names ...string) (Formats, error) {
var types []Format
for _, name := range names {
tpe, ok := formats.GetByName(name)
if !ok {
return types, fmt.Errorf("OutputFormat with key %q not found", name)
}
types = append(types, tpe)
}
return types, nil
}
// FromFilename gets a Format given a filename.
func (formats Formats) FromFilename(filename string) (f Format, found bool) {
// mytemplate.amp.html
// mytemplate.html
// mytemplate
var ext, outFormat string
parts := strings.Split(filename, ".")
if len(parts) > 2 {
outFormat = parts[1]
ext = parts[2]
} else if len(parts) > 1 {
ext = parts[1]
}
if outFormat != "" {
return formats.GetByName(outFormat)
}
if ext != "" {
f, found = formats.GetBySuffix(ext)
if !found && len(parts) == 2 {
// For extensionless output formats (e.g. Netlify's _redirects)
// we must fall back to using the extension as format lookup.
f, found = formats.GetByName(ext)
}
}
return
}
// DecodeFormats takes a list of output format configurations and merges those,
// in the order given, with the Hugo defaults as the last resort.
func DecodeFormats(mediaTypes media.Types, maps ...map[string]interface{}) (Formats, error) {
f := make(Formats, len(DefaultFormats))
copy(f, DefaultFormats)
for _, m := range maps {
for k, v := range m {
found := false
for i, vv := range f {
if strings.EqualFold(k, vv.Name) {
// Merge it with the existing
if err := decode(mediaTypes, v, &f[i]); err != nil {
return f, err
}
found = true
}
}
if !found {
var newOutFormat Format
newOutFormat.Name = k
if err := decode(mediaTypes, v, &newOutFormat); err != nil {
return f, err
}
// We need values for these
if newOutFormat.BaseName == "" {
newOutFormat.BaseName = "index"
}
if newOutFormat.Rel == "" {
newOutFormat.Rel = "alternate"
}
f = append(f, newOutFormat)
}
}
}
sort.Sort(f)
return f, nil
}
func decode(mediaTypes media.Types, input, output interface{}) error {
config := &mapstructure.DecoderConfig{
Metadata: nil,
Result: output,
WeaklyTypedInput: true,
DecodeHook: func(a reflect.Type, b reflect.Type, c interface{}) (interface{}, error) {
if a.Kind() == reflect.Map {
dataVal := reflect.Indirect(reflect.ValueOf(c))
for _, key := range dataVal.MapKeys() {
keyStr, ok := key.Interface().(string)
if !ok {
// Not a string key
continue
}
if strings.EqualFold(keyStr, "mediaType") {
// If mediaType is a string, look it up and replace it
// in the map.
vv := dataVal.MapIndex(key)
if mediaTypeStr, ok := vv.Interface().(string); ok {
mediaType, found := mediaTypes.GetByType(mediaTypeStr)
if !found {
return c, fmt.Errorf("media type %q not found", mediaTypeStr)
}
dataVal.SetMapIndex(key, reflect.ValueOf(mediaType))
}
}
}
}
return c, nil
},
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
}
// BaseFilename returns the base filename of f including an extension (ie.
// "index.xml").
func (f Format) BaseFilename() string {
return f.BaseName + f.MediaType.FullSuffix()
}
// MarshalJSON returns the JSON encoding of f.
func (f Format) MarshalJSON() ([]byte, error) {
type Alias Format
return json.Marshal(&struct {
MediaType string
Alias
}{
MediaType: f.MediaType.String(),
Alias: (Alias)(f),
})
}
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./hugolib/testhelpers_test.go | package hugolib
import (
"bytes"
"fmt"
"image/jpeg"
"io"
"math/rand"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"testing"
"text/template"
"time"
"unicode/utf8"
"github.com/gohugoio/hugo/htesting"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/parser/metadecoders"
"github.com/google/go-cmp/cmp"
"github.com/gohugoio/hugo/parser"
"github.com/pkg/errors"
"github.com/fsnotify/fsnotify"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/resources/page"
"github.com/sanity-io/litter"
"github.com/spf13/afero"
"github.com/spf13/cast"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/tpl"
"github.com/spf13/viper"
"github.com/gohugoio/hugo/resources/resource"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/hugofs"
)
var (
deepEqualsPages = qt.CmpEquals(cmp.Comparer(func(p1, p2 *pageState) bool { return p1 == p2 }))
deepEqualsOutputFormats = qt.CmpEquals(cmp.Comparer(func(o1, o2 output.Format) bool {
return o1.Name == o2.Name && o1.MediaType.Type() == o2.MediaType.Type()
}))
)
type sitesBuilder struct {
Cfg config.Provider
environ []string
Fs *hugofs.Fs
T testing.TB
depsCfg deps.DepsCfg
*qt.C
logger loggers.Logger
rnd *rand.Rand
dumper litter.Options
// Used to test partial rebuilds.
changedFiles []string
removedFiles []string
// Aka the Hugo server mode.
running bool
H *HugoSites
theme string
// Default toml
configFormat string
configFileSet bool
viperSet bool
// Default is empty.
// TODO(bep) revisit this and consider always setting it to something.
// Consider this in relation to using the BaseFs.PublishFs to all publishing.
workingDir string
addNothing bool
// Base data/content
contentFilePairs []filenameContent
templateFilePairs []filenameContent
i18nFilePairs []filenameContent
dataFilePairs []filenameContent
// Additional data/content.
// As in "use the base, but add these on top".
contentFilePairsAdded []filenameContent
templateFilePairsAdded []filenameContent
i18nFilePairsAdded []filenameContent
dataFilePairsAdded []filenameContent
}
type filenameContent struct {
filename string
content string
}
func newTestSitesBuilder(t testing.TB) *sitesBuilder {
v := viper.New()
fs := hugofs.NewMem(v)
litterOptions := litter.Options{
HidePrivateFields: true,
StripPackageNames: true,
Separator: " ",
}
return &sitesBuilder{
T: t, C: qt.New(t), Fs: fs, configFormat: "toml",
dumper: litterOptions, rnd: rand.New(rand.NewSource(time.Now().Unix())),
}
}
func newTestSitesBuilderFromDepsCfg(t testing.TB, d deps.DepsCfg) *sitesBuilder {
c := qt.New(t)
litterOptions := litter.Options{
HidePrivateFields: true,
StripPackageNames: true,
Separator: " ",
}
b := &sitesBuilder{T: t, C: c, depsCfg: d, Fs: d.Fs, dumper: litterOptions, rnd: rand.New(rand.NewSource(time.Now().Unix()))}
workingDir := d.Cfg.GetString("workingDir")
b.WithWorkingDir(workingDir)
return b.WithViper(d.Cfg.(*viper.Viper))
}
func (s *sitesBuilder) Running() *sitesBuilder {
s.running = true
return s
}
func (s *sitesBuilder) WithNothingAdded() *sitesBuilder {
s.addNothing = true
return s
}
func (s *sitesBuilder) WithLogger(logger loggers.Logger) *sitesBuilder {
s.logger = logger
return s
}
func (s *sitesBuilder) WithWorkingDir(dir string) *sitesBuilder {
s.workingDir = filepath.FromSlash(dir)
return s
}
func (s *sitesBuilder) WithEnviron(env ...string) *sitesBuilder {
for i := 0; i < len(env); i += 2 {
s.environ = append(s.environ, fmt.Sprintf("%s=%s", env[i], env[i+1]))
}
return s
}
func (s *sitesBuilder) WithConfigTemplate(data interface{}, format, configTemplate string) *sitesBuilder {
s.T.Helper()
if format == "" {
format = "toml"
}
templ, err := template.New("test").Parse(configTemplate)
if err != nil {
s.Fatalf("Template parse failed: %s", err)
}
var b bytes.Buffer
templ.Execute(&b, data)
return s.WithConfigFile(format, b.String())
}
func (s *sitesBuilder) WithViper(v *viper.Viper) *sitesBuilder {
s.T.Helper()
if s.configFileSet {
s.T.Fatal("WithViper: use Viper or config.toml, not both")
}
defer func() {
s.viperSet = true
}()
// Write to a config file to make sure the tests follow the same code path.
var buff bytes.Buffer
m := v.AllSettings()
s.Assert(parser.InterfaceToConfig(m, metadecoders.TOML, &buff), qt.IsNil)
return s.WithConfigFile("toml", buff.String())
}
func (s *sitesBuilder) WithConfigFile(format, conf string) *sitesBuilder {
s.T.Helper()
if s.viperSet {
s.T.Fatal("WithConfigFile: use Viper or config.toml, not both")
}
s.configFileSet = true
filename := s.absFilename("config." + format)
writeSource(s.T, s.Fs, filename, conf)
s.configFormat = format
return s
}
func (s *sitesBuilder) WithThemeConfigFile(format, conf string) *sitesBuilder {
s.T.Helper()
if s.theme == "" {
s.theme = "test-theme"
}
filename := filepath.Join("themes", s.theme, "config."+format)
writeSource(s.T, s.Fs, s.absFilename(filename), conf)
return s
}
func (s *sitesBuilder) WithSourceFile(filenameContent ...string) *sitesBuilder {
s.T.Helper()
for i := 0; i < len(filenameContent); i += 2 {
writeSource(s.T, s.Fs, s.absFilename(filenameContent[i]), filenameContent[i+1])
}
return s
}
func (s *sitesBuilder) absFilename(filename string) string {
filename = filepath.FromSlash(filename)
if filepath.IsAbs(filename) {
return filename
}
if s.workingDir != "" && !strings.HasPrefix(filename, s.workingDir) {
filename = filepath.Join(s.workingDir, filename)
}
return filename
}
const commonConfigSections = `
[services]
[services.disqus]
shortname = "disqus_shortname"
[services.googleAnalytics]
id = "ga_id"
[privacy]
[privacy.disqus]
disable = false
[privacy.googleAnalytics]
respectDoNotTrack = true
anonymizeIP = true
[privacy.instagram]
simple = true
[privacy.twitter]
enableDNT = true
[privacy.vimeo]
disable = false
[privacy.youtube]
disable = false
privacyEnhanced = true
`
func (s *sitesBuilder) WithSimpleConfigFile() *sitesBuilder {
s.T.Helper()
return s.WithSimpleConfigFileAndBaseURL("http://example.com/")
}
func (s *sitesBuilder) WithSimpleConfigFileAndBaseURL(baseURL string) *sitesBuilder {
s.T.Helper()
return s.WithSimpleConfigFileAndSettings(map[string]interface{}{"baseURL": baseURL})
}
func (s *sitesBuilder) WithSimpleConfigFileAndSettings(settings interface{}) *sitesBuilder {
s.T.Helper()
var buf bytes.Buffer
parser.InterfaceToConfig(settings, metadecoders.TOML, &buf)
config := buf.String() + commonConfigSections
return s.WithConfigFile("toml", config)
}
func (s *sitesBuilder) WithDefaultMultiSiteConfig() *sitesBuilder {
defaultMultiSiteConfig := `
baseURL = "http://example.com/blog"
paginate = 1
disablePathToLower = true
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
[permalinks]
other = "/somewhere/else/:filename"
[blackfriday]
angledQuotes = true
[Taxonomies]
tag = "tags"
[Languages]
[Languages.en]
weight = 10
title = "In English"
languageName = "English"
[Languages.en.blackfriday]
angledQuotes = false
[[Languages.en.menu.main]]
url = "/"
name = "Home"
weight = 0
[Languages.fr]
weight = 20
title = "Le Français"
languageName = "Français"
[Languages.fr.Taxonomies]
plaque = "plaques"
[Languages.nn]
weight = 30
title = "På nynorsk"
languageName = "Nynorsk"
paginatePath = "side"
[Languages.nn.Taxonomies]
lag = "lag"
[[Languages.nn.menu.main]]
url = "/"
name = "Heim"
weight = 1
[Languages.nb]
weight = 40
title = "På bokmål"
languageName = "Bokmål"
paginatePath = "side"
[Languages.nb.Taxonomies]
lag = "lag"
` + commonConfigSections
return s.WithConfigFile("toml", defaultMultiSiteConfig)
}
func (s *sitesBuilder) WithSunset(in string) {
// Write a real image into one of the bundle above.
src, err := os.Open(filepath.FromSlash("testdata/sunset.jpg"))
s.Assert(err, qt.IsNil)
out, err := s.Fs.Source.Create(filepath.FromSlash(filepath.Join(s.workingDir, in)))
s.Assert(err, qt.IsNil)
_, err = io.Copy(out, src)
s.Assert(err, qt.IsNil)
out.Close()
src.Close()
}
func (s *sitesBuilder) createFilenameContent(pairs []string) []filenameContent {
var slice []filenameContent
s.appendFilenameContent(&slice, pairs...)
return slice
}
func (s *sitesBuilder) appendFilenameContent(slice *[]filenameContent, pairs ...string) {
if len(pairs)%2 != 0 {
panic("file content mismatch")
}
for i := 0; i < len(pairs); i += 2 {
c := filenameContent{
filename: pairs[i],
content: pairs[i+1],
}
*slice = append(*slice, c)
}
}
func (s *sitesBuilder) WithContent(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.contentFilePairs, filenameContent...)
return s
}
func (s *sitesBuilder) WithContentAdded(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.contentFilePairsAdded, filenameContent...)
return s
}
func (s *sitesBuilder) WithTemplates(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.templateFilePairs, filenameContent...)
return s
}
func (s *sitesBuilder) WithTemplatesAdded(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.templateFilePairsAdded, filenameContent...)
return s
}
func (s *sitesBuilder) WithData(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.dataFilePairs, filenameContent...)
return s
}
func (s *sitesBuilder) WithDataAdded(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.dataFilePairsAdded, filenameContent...)
return s
}
func (s *sitesBuilder) WithI18n(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.i18nFilePairs, filenameContent...)
return s
}
func (s *sitesBuilder) WithI18nAdded(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.i18nFilePairsAdded, filenameContent...)
return s
}
func (s *sitesBuilder) EditFiles(filenameContent ...string) *sitesBuilder {
for i := 0; i < len(filenameContent); i += 2 {
filename, content := filepath.FromSlash(filenameContent[i]), filenameContent[i+1]
absFilename := s.absFilename(filename)
s.changedFiles = append(s.changedFiles, absFilename)
writeSource(s.T, s.Fs, absFilename, content)
}
return s
}
func (s *sitesBuilder) RemoveFiles(filenames ...string) *sitesBuilder {
for _, filename := range filenames {
absFilename := s.absFilename(filename)
s.removedFiles = append(s.removedFiles, absFilename)
s.Assert(s.Fs.Source.Remove(absFilename), qt.IsNil)
}
return s
}
func (s *sitesBuilder) writeFilePairs(folder string, files []filenameContent) *sitesBuilder {
// We have had some "filesystem ordering" bugs that we have not discovered in
// our tests running with the in memory filesystem.
// That file system is backed by a map so not sure how this helps, but some
// randomness in tests doesn't hurt.
// TODO(bep) this turns out to be more confusing than helpful.
// s.rnd.Shuffle(len(files), func(i, j int) { files[i], files[j] = files[j], files[i] })
for _, fc := range files {
target := folder
// TODO(bep) clean up this magic.
if strings.HasPrefix(fc.filename, folder) {
target = ""
}
if s.workingDir != "" {
target = filepath.Join(s.workingDir, target)
}
writeSource(s.T, s.Fs, filepath.Join(target, fc.filename), fc.content)
}
return s
}
func (s *sitesBuilder) CreateSites() *sitesBuilder {
if err := s.CreateSitesE(); err != nil {
herrors.PrintStackTraceFromErr(err)
s.Fatalf("Failed to create sites: %s", err)
}
return s
}
func (s *sitesBuilder) LoadConfig() error {
if !s.configFileSet {
s.WithSimpleConfigFile()
}
cfg, _, err := LoadConfig(ConfigSourceDescriptor{
WorkingDir: s.workingDir,
Fs: s.Fs.Source,
Logger: s.logger,
Environ: s.environ,
Filename: "config." + s.configFormat,
}, func(cfg config.Provider) error {
return nil
})
if err != nil {
return err
}
s.Cfg = cfg
return nil
}
func (s *sitesBuilder) CreateSitesE() error {
if !s.addNothing {
if _, ok := s.Fs.Source.(*afero.OsFs); ok {
for _, dir := range []string{
"content/sect",
"layouts/_default",
"layouts/_default/_markup",
"layouts/partials",
"layouts/shortcodes",
"data",
"i18n",
} {
if err := os.MkdirAll(filepath.Join(s.workingDir, dir), 0777); err != nil {
return errors.Wrapf(err, "failed to create %q", dir)
}
}
}
s.addDefaults()
s.writeFilePairs("content", s.contentFilePairsAdded)
s.writeFilePairs("layouts", s.templateFilePairsAdded)
s.writeFilePairs("data", s.dataFilePairsAdded)
s.writeFilePairs("i18n", s.i18nFilePairsAdded)
s.writeFilePairs("i18n", s.i18nFilePairs)
s.writeFilePairs("data", s.dataFilePairs)
s.writeFilePairs("content", s.contentFilePairs)
s.writeFilePairs("layouts", s.templateFilePairs)
}
if err := s.LoadConfig(); err != nil {
return errors.Wrap(err, "failed to load config")
}
s.Fs.Destination = hugofs.NewCreateCountingFs(s.Fs.Destination)
depsCfg := s.depsCfg
depsCfg.Fs = s.Fs
depsCfg.Cfg = s.Cfg
depsCfg.Logger = s.logger
depsCfg.Running = s.running
sites, err := NewHugoSites(depsCfg)
if err != nil {
return errors.Wrap(err, "failed to create sites")
}
s.H = sites
return nil
}
func (s *sitesBuilder) BuildE(cfg BuildCfg) error {
if s.H == nil {
s.CreateSites()
}
return s.H.Build(cfg)
}
func (s *sitesBuilder) Build(cfg BuildCfg) *sitesBuilder {
s.T.Helper()
return s.build(cfg, false)
}
func (s *sitesBuilder) BuildFail(cfg BuildCfg) *sitesBuilder {
s.T.Helper()
return s.build(cfg, true)
}
func (s *sitesBuilder) changeEvents() []fsnotify.Event {
var events []fsnotify.Event
for _, v := range s.changedFiles {
events = append(events, fsnotify.Event{
Name: v,
Op: fsnotify.Write,
})
}
for _, v := range s.removedFiles {
events = append(events, fsnotify.Event{
Name: v,
Op: fsnotify.Remove,
})
}
return events
}
func (s *sitesBuilder) build(cfg BuildCfg, shouldFail bool) *sitesBuilder {
s.Helper()
defer func() {
s.changedFiles = nil
}()
if s.H == nil {
s.CreateSites()
}
err := s.H.Build(cfg, s.changeEvents()...)
if err == nil {
logErrorCount := s.H.NumLogErrors()
if logErrorCount > 0 {
err = fmt.Errorf("logged %d errors", logErrorCount)
}
}
if err != nil && !shouldFail {
herrors.PrintStackTraceFromErr(err)
s.Fatalf("Build failed: %s", err)
} else if err == nil && shouldFail {
s.Fatalf("Expected error")
}
return s
}
func (s *sitesBuilder) addDefaults() {
var (
contentTemplate = `---
title: doc1
weight: 1
tags:
- tag1
date: "2018-02-28"
---
# doc1
*some "content"*
{{< shortcode >}}
{{< lingo >}}
`
defaultContent = []string{
"content/sect/doc1.en.md", contentTemplate,
"content/sect/doc1.fr.md", contentTemplate,
"content/sect/doc1.nb.md", contentTemplate,
"content/sect/doc1.nn.md", contentTemplate,
}
listTemplateCommon = "{{ $p := .Paginator }}{{ $p.PageNumber }}|{{ .Title }}|{{ i18n \"hello\" }}|{{ .Permalink }}|Pager: {{ template \"_internal/pagination.html\" . }}|Kind: {{ .Kind }}|Content: {{ .Content }}|Len Pages: {{ len .Pages }}|Len RegularPages: {{ len .RegularPages }}| HasParent: {{ if .Parent }}YES{{ else }}NO{{ end }}"
defaultTemplates = []string{
"_default/single.html", "Single: {{ .Title }}|{{ i18n \"hello\" }}|{{.Language.Lang}}|RelPermalink: {{ .RelPermalink }}|Permalink: {{ .Permalink }}|{{ .Content }}|Resources: {{ range .Resources }}{{ .MediaType }}: {{ .RelPermalink}} -- {{ end }}|Summary: {{ .Summary }}|Truncated: {{ .Truncated }}|Parent: {{ .Parent.Title }}",
"_default/list.html", "List Page " + listTemplateCommon,
"index.html", "{{ $p := .Paginator }}Default Home Page {{ $p.PageNumber }}: {{ .Title }}|{{ .IsHome }}|{{ i18n \"hello\" }}|{{ .Permalink }}|{{ .Site.Data.hugo.slogan }}|String Resource: {{ ( \"Hugo Pipes\" | resources.FromString \"text/pipes.txt\").RelPermalink }}",
"index.fr.html", "{{ $p := .Paginator }}French Home Page {{ $p.PageNumber }}: {{ .Title }}|{{ .IsHome }}|{{ i18n \"hello\" }}|{{ .Permalink }}|{{ .Site.Data.hugo.slogan }}|String Resource: {{ ( \"Hugo Pipes\" | resources.FromString \"text/pipes.txt\").RelPermalink }}",
"_default/terms.html", "Taxonomy Term Page " + listTemplateCommon,
"_default/taxonomy.html", "Taxonomy List Page " + listTemplateCommon,
// Shortcodes
"shortcodes/shortcode.html", "Shortcode: {{ i18n \"hello\" }}",
// A shortcode in multiple languages
"shortcodes/lingo.html", "LingoDefault",
"shortcodes/lingo.fr.html", "LingoFrench",
// Special templates
"404.html", "404|{{ .Lang }}|{{ .Title }}",
"robots.txt", "robots|{{ .Lang }}|{{ .Title }}",
}
defaultI18n = []string{
"en.yaml", `
hello:
other: "Hello"
`,
"fr.yaml", `
hello:
other: "Bonjour"
`,
}
defaultData = []string{
"hugo.toml", "slogan = \"Hugo Rocks!\"",
}
)
if len(s.contentFilePairs) == 0 {
s.writeFilePairs("content", s.createFilenameContent(defaultContent))
}
if len(s.templateFilePairs) == 0 {
s.writeFilePairs("layouts", s.createFilenameContent(defaultTemplates))
}
if len(s.dataFilePairs) == 0 {
s.writeFilePairs("data", s.createFilenameContent(defaultData))
}
if len(s.i18nFilePairs) == 0 {
s.writeFilePairs("i18n", s.createFilenameContent(defaultI18n))
}
}
func (s *sitesBuilder) Fatalf(format string, args ...interface{}) {
s.T.Helper()
s.T.Fatalf(format, args...)
}
func (s *sitesBuilder) AssertFileContentFn(filename string, f func(s string) bool) {
s.T.Helper()
content := s.FileContent(filename)
if !f(content) {
s.Fatalf("Assert failed for %q in content\n%s", filename, content)
}
}
func (s *sitesBuilder) AssertHome(matches ...string) {
s.AssertFileContent("public/index.html", matches...)
}
func (s *sitesBuilder) AssertFileContent(filename string, matches ...string) {
s.T.Helper()
content := s.FileContent(filename)
for _, m := range matches {
lines := strings.Split(m, "\n")
for _, match := range lines {
match = strings.TrimSpace(match)
if match == "" {
continue
}
if !strings.Contains(content, match) {
s.Fatalf("No match for %q in content for %s\n%s\n%q", match, filename, content, content)
}
}
}
}
func (s *sitesBuilder) AssertFileDoesNotExist(filename string) {
if s.CheckExists(filename) {
s.Fatalf("File %q exists but must not exist.", filename)
}
}
func (s *sitesBuilder) AssertImage(width, height int, filename string) {
filename = filepath.Join(s.workingDir, filename)
f, err := s.Fs.Destination.Open(filename)
s.Assert(err, qt.IsNil)
defer f.Close()
cfg, err := jpeg.DecodeConfig(f)
s.Assert(err, qt.IsNil)
s.Assert(cfg.Width, qt.Equals, width)
s.Assert(cfg.Height, qt.Equals, height)
}
func (s *sitesBuilder) AssertNoDuplicateWrites() {
s.Helper()
d := s.Fs.Destination.(hugofs.DuplicatesReporter)
s.Assert(d.ReportDuplicates(), qt.Equals, "")
}
func (s *sitesBuilder) FileContent(filename string) string {
s.T.Helper()
filename = filepath.FromSlash(filename)
if !strings.HasPrefix(filename, s.workingDir) {
filename = filepath.Join(s.workingDir, filename)
}
return readDestination(s.T, s.Fs, filename)
}
func (s *sitesBuilder) AssertObject(expected string, object interface{}) {
s.T.Helper()
got := s.dumper.Sdump(object)
expected = strings.TrimSpace(expected)
if expected != got {
fmt.Println(got)
diff := htesting.DiffStrings(expected, got)
s.Fatalf("diff:\n%s\nexpected\n%s\ngot\n%s", diff, expected, got)
}
}
func (s *sitesBuilder) AssertFileContentRe(filename string, matches ...string) {
content := readDestination(s.T, s.Fs, filename)
for _, match := range matches {
r := regexp.MustCompile("(?s)" + match)
if !r.MatchString(content) {
s.Fatalf("No match for %q in content for %s\n%q", match, filename, content)
}
}
}
func (s *sitesBuilder) CheckExists(filename string) bool {
return destinationExists(s.Fs, filepath.Clean(filename))
}
func (s *sitesBuilder) GetPage(ref string) page.Page {
p, err := s.H.Sites[0].getPageNew(nil, ref)
s.Assert(err, qt.IsNil)
return p
}
func (s *sitesBuilder) GetPageRel(p page.Page, ref string) page.Page {
p, err := s.H.Sites[0].getPageNew(p, ref)
s.Assert(err, qt.IsNil)
return p
}
func newTestHelper(cfg config.Provider, fs *hugofs.Fs, t testing.TB) testHelper {
return testHelper{
Cfg: cfg,
Fs: fs,
C: qt.New(t),
}
}
type testHelper struct {
Cfg config.Provider
Fs *hugofs.Fs
*qt.C
}
func (th testHelper) assertFileContent(filename string, matches ...string) {
th.Helper()
filename = th.replaceDefaultContentLanguageValue(filename)
content := readDestination(th, th.Fs, filename)
for _, match := range matches {
match = th.replaceDefaultContentLanguageValue(match)
th.Assert(strings.Contains(content, match), qt.Equals, true, qt.Commentf(match+" not in: \n"+content))
}
}
func (th testHelper) assertFileContentRegexp(filename string, matches ...string) {
filename = th.replaceDefaultContentLanguageValue(filename)
content := readDestination(th, th.Fs, filename)
for _, match := range matches {
match = th.replaceDefaultContentLanguageValue(match)
r := regexp.MustCompile(match)
matches := r.MatchString(content)
if !matches {
fmt.Println(match+":\n", content)
}
th.Assert(matches, qt.Equals, true)
}
}
func (th testHelper) assertFileNotExist(filename string) {
exists, err := helpers.Exists(filename, th.Fs.Destination)
th.Assert(err, qt.IsNil)
th.Assert(exists, qt.Equals, false)
}
func (th testHelper) replaceDefaultContentLanguageValue(value string) string {
defaultInSubDir := th.Cfg.GetBool("defaultContentLanguageInSubDir")
replace := th.Cfg.GetString("defaultContentLanguage") + "/"
if !defaultInSubDir {
value = strings.Replace(value, replace, "", 1)
}
return value
}
func loadTestConfig(fs afero.Fs, withConfig ...func(cfg config.Provider) error) (*viper.Viper, error) {
v, _, err := LoadConfig(ConfigSourceDescriptor{Fs: fs}, withConfig...)
return v, err
}
func newTestCfgBasic() (*viper.Viper, *hugofs.Fs) {
mm := afero.NewMemMapFs()
v := viper.New()
v.Set("defaultContentLanguageInSubdir", true)
fs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(mm), v)
return v, fs
}
func newTestCfg(withConfig ...func(cfg config.Provider) error) (*viper.Viper, *hugofs.Fs) {
mm := afero.NewMemMapFs()
v, err := loadTestConfig(mm, func(cfg config.Provider) error {
// Default is false, but true is easier to use as default in tests
cfg.Set("defaultContentLanguageInSubdir", true)
for _, w := range withConfig {
w(cfg)
}
return nil
})
if err != nil && err != ErrNoConfigFile {
panic(err)
}
fs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(mm), v)
return v, fs
}
func newTestSitesFromConfig(t testing.TB, afs afero.Fs, tomlConfig string, layoutPathContentPairs ...string) (testHelper, *HugoSites) {
if len(layoutPathContentPairs)%2 != 0 {
t.Fatalf("Layouts must be provided in pairs")
}
c := qt.New(t)
writeToFs(t, afs, filepath.Join("content", ".gitkeep"), "")
writeToFs(t, afs, "config.toml", tomlConfig)
cfg, err := LoadConfigDefault(afs)
c.Assert(err, qt.IsNil)
fs := hugofs.NewFrom(afs, cfg)
th := newTestHelper(cfg, fs, t)
for i := 0; i < len(layoutPathContentPairs); i += 2 {
writeSource(t, fs, layoutPathContentPairs[i], layoutPathContentPairs[i+1])
}
h, err := NewHugoSites(deps.DepsCfg{Fs: fs, Cfg: cfg})
c.Assert(err, qt.IsNil)
return th, h
}
func createWithTemplateFromNameValues(additionalTemplates ...string) func(templ tpl.TemplateManager) error {
return func(templ tpl.TemplateManager) error {
for i := 0; i < len(additionalTemplates); i += 2 {
err := templ.AddTemplate(additionalTemplates[i], additionalTemplates[i+1])
if err != nil {
return err
}
}
return nil
}
}
// TODO(bep) replace these with the builder
func buildSingleSite(t testing.TB, depsCfg deps.DepsCfg, buildCfg BuildCfg) *Site {
t.Helper()
return buildSingleSiteExpected(t, false, false, depsCfg, buildCfg)
}
func buildSingleSiteExpected(t testing.TB, expectSiteInitError, expectBuildError bool, depsCfg deps.DepsCfg, buildCfg BuildCfg) *Site {
t.Helper()
b := newTestSitesBuilderFromDepsCfg(t, depsCfg).WithNothingAdded()
err := b.CreateSitesE()
if expectSiteInitError {
b.Assert(err, qt.Not(qt.IsNil))
return nil
} else {
b.Assert(err, qt.IsNil)
}
h := b.H
b.Assert(len(h.Sites), qt.Equals, 1)
if expectBuildError {
b.Assert(h.Build(buildCfg), qt.Not(qt.IsNil))
return nil
}
b.Assert(h.Build(buildCfg), qt.IsNil)
return h.Sites[0]
}
func writeSourcesToSource(t *testing.T, base string, fs *hugofs.Fs, sources ...[2]string) {
for _, src := range sources {
writeSource(t, fs, filepath.Join(base, src[0]), src[1])
}
}
func getPage(in page.Page, ref string) page.Page {
p, err := in.GetPage(ref)
if err != nil {
panic(err)
}
return p
}
func content(c resource.ContentProvider) string {
cc, err := c.Content()
if err != nil {
panic(err)
}
ccs, err := cast.ToStringE(cc)
if err != nil {
panic(err)
}
return ccs
}
func pagesToString(pages ...page.Page) string {
var paths []string
for _, p := range pages {
paths = append(paths, p.Path())
}
sort.Strings(paths)
return strings.Join(paths, "|")
}
func dumpPages(pages ...page.Page) {
fmt.Println("---------")
for _, p := range pages {
var meta interface{}
if p.File() != nil && p.File().FileInfo() != nil {
meta = p.File().FileInfo().Meta()
}
fmt.Printf("Kind: %s Title: %-10s RelPermalink: %-10s Path: %-10s sections: %s Lang: %s Meta: %v\n",
p.Kind(), p.Title(), p.RelPermalink(), p.Path(), p.SectionsPath(), p.Lang(), meta)
}
}
func dumpSPages(pages ...*pageState) {
for i, p := range pages {
fmt.Printf("%d: Kind: %s Title: %-10s RelPermalink: %-10s Path: %-10s sections: %s\n",
i+1,
p.Kind(), p.Title(), p.RelPermalink(), p.Path(), p.SectionsPath())
}
}
func printStringIndexes(s string) {
lines := strings.Split(s, "\n")
i := 0
for _, line := range lines {
for _, r := range line {
fmt.Printf("%-3s", strconv.Itoa(i))
i += utf8.RuneLen(r)
}
i++
fmt.Println()
for _, r := range line {
fmt.Printf("%-3s", string(r))
}
fmt.Println()
}
}
// See https://github.com/golang/go/issues/19280
// Not in use.
var parallelEnabled = true
func parallel(t *testing.T) {
if parallelEnabled {
t.Parallel()
}
}
func skipSymlink(t *testing.T) {
if runtime.GOOS == "windows" && os.Getenv("CI") == "" {
t.Skip("skip symlink test on local Windows (needs admin)")
}
}
func captureStderr(f func() error) (string, error) {
old := os.Stderr
r, w, _ := os.Pipe()
os.Stderr = w
err := f()
w.Close()
os.Stderr = old
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String(), err
}
func captureStdout(f func() error) (string, error) {
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
err := f()
w.Close()
os.Stdout = old
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String(), err
}
| package hugolib
import (
"bytes"
"fmt"
"image/jpeg"
"io"
"math/rand"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"testing"
"text/template"
"time"
"unicode/utf8"
"github.com/gohugoio/hugo/htesting"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/parser/metadecoders"
"github.com/google/go-cmp/cmp"
"github.com/gohugoio/hugo/parser"
"github.com/pkg/errors"
"github.com/fsnotify/fsnotify"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/resources/page"
"github.com/sanity-io/litter"
"github.com/spf13/afero"
"github.com/spf13/cast"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/tpl"
"github.com/spf13/viper"
"github.com/gohugoio/hugo/resources/resource"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/hugofs"
)
var (
deepEqualsPages = qt.CmpEquals(cmp.Comparer(func(p1, p2 *pageState) bool { return p1 == p2 }))
deepEqualsOutputFormats = qt.CmpEquals(cmp.Comparer(func(o1, o2 output.Format) bool {
return o1.Name == o2.Name && o1.MediaType.Type() == o2.MediaType.Type()
}))
)
type sitesBuilder struct {
Cfg config.Provider
environ []string
Fs *hugofs.Fs
T testing.TB
depsCfg deps.DepsCfg
*qt.C
logger loggers.Logger
rnd *rand.Rand
dumper litter.Options
// Used to test partial rebuilds.
changedFiles []string
removedFiles []string
// Aka the Hugo server mode.
running bool
H *HugoSites
theme string
// Default toml
configFormat string
configFileSet bool
viperSet bool
// Default is empty.
// TODO(bep) revisit this and consider always setting it to something.
// Consider this in relation to using the BaseFs.PublishFs to all publishing.
workingDir string
addNothing bool
// Base data/content
contentFilePairs []filenameContent
templateFilePairs []filenameContent
i18nFilePairs []filenameContent
dataFilePairs []filenameContent
// Additional data/content.
// As in "use the base, but add these on top".
contentFilePairsAdded []filenameContent
templateFilePairsAdded []filenameContent
i18nFilePairsAdded []filenameContent
dataFilePairsAdded []filenameContent
}
type filenameContent struct {
filename string
content string
}
func newTestSitesBuilder(t testing.TB) *sitesBuilder {
v := viper.New()
fs := hugofs.NewMem(v)
litterOptions := litter.Options{
HidePrivateFields: true,
StripPackageNames: true,
Separator: " ",
}
return &sitesBuilder{
T: t, C: qt.New(t), Fs: fs, configFormat: "toml",
dumper: litterOptions, rnd: rand.New(rand.NewSource(time.Now().Unix())),
}
}
func newTestSitesBuilderFromDepsCfg(t testing.TB, d deps.DepsCfg) *sitesBuilder {
c := qt.New(t)
litterOptions := litter.Options{
HidePrivateFields: true,
StripPackageNames: true,
Separator: " ",
}
b := &sitesBuilder{T: t, C: c, depsCfg: d, Fs: d.Fs, dumper: litterOptions, rnd: rand.New(rand.NewSource(time.Now().Unix()))}
workingDir := d.Cfg.GetString("workingDir")
b.WithWorkingDir(workingDir)
return b.WithViper(d.Cfg.(*viper.Viper))
}
func (s *sitesBuilder) Running() *sitesBuilder {
s.running = true
return s
}
func (s *sitesBuilder) WithNothingAdded() *sitesBuilder {
s.addNothing = true
return s
}
func (s *sitesBuilder) WithLogger(logger loggers.Logger) *sitesBuilder {
s.logger = logger
return s
}
func (s *sitesBuilder) WithWorkingDir(dir string) *sitesBuilder {
s.workingDir = filepath.FromSlash(dir)
return s
}
func (s *sitesBuilder) WithEnviron(env ...string) *sitesBuilder {
for i := 0; i < len(env); i += 2 {
s.environ = append(s.environ, fmt.Sprintf("%s=%s", env[i], env[i+1]))
}
return s
}
func (s *sitesBuilder) WithConfigTemplate(data interface{}, format, configTemplate string) *sitesBuilder {
s.T.Helper()
if format == "" {
format = "toml"
}
templ, err := template.New("test").Parse(configTemplate)
if err != nil {
s.Fatalf("Template parse failed: %s", err)
}
var b bytes.Buffer
templ.Execute(&b, data)
return s.WithConfigFile(format, b.String())
}
func (s *sitesBuilder) WithViper(v *viper.Viper) *sitesBuilder {
s.T.Helper()
if s.configFileSet {
s.T.Fatal("WithViper: use Viper or config.toml, not both")
}
defer func() {
s.viperSet = true
}()
// Write to a config file to make sure the tests follow the same code path.
var buff bytes.Buffer
m := v.AllSettings()
s.Assert(parser.InterfaceToConfig(m, metadecoders.TOML, &buff), qt.IsNil)
return s.WithConfigFile("toml", buff.String())
}
func (s *sitesBuilder) WithConfigFile(format, conf string) *sitesBuilder {
s.T.Helper()
if s.viperSet {
s.T.Fatal("WithConfigFile: use Viper or config.toml, not both")
}
s.configFileSet = true
filename := s.absFilename("config." + format)
writeSource(s.T, s.Fs, filename, conf)
s.configFormat = format
return s
}
func (s *sitesBuilder) WithThemeConfigFile(format, conf string) *sitesBuilder {
s.T.Helper()
if s.theme == "" {
s.theme = "test-theme"
}
filename := filepath.Join("themes", s.theme, "config."+format)
writeSource(s.T, s.Fs, s.absFilename(filename), conf)
return s
}
func (s *sitesBuilder) WithSourceFile(filenameContent ...string) *sitesBuilder {
s.T.Helper()
for i := 0; i < len(filenameContent); i += 2 {
writeSource(s.T, s.Fs, s.absFilename(filenameContent[i]), filenameContent[i+1])
}
return s
}
func (s *sitesBuilder) absFilename(filename string) string {
filename = filepath.FromSlash(filename)
if filepath.IsAbs(filename) {
return filename
}
if s.workingDir != "" && !strings.HasPrefix(filename, s.workingDir) {
filename = filepath.Join(s.workingDir, filename)
}
return filename
}
const commonConfigSections = `
[services]
[services.disqus]
shortname = "disqus_shortname"
[services.googleAnalytics]
id = "ga_id"
[privacy]
[privacy.disqus]
disable = false
[privacy.googleAnalytics]
respectDoNotTrack = true
anonymizeIP = true
[privacy.instagram]
simple = true
[privacy.twitter]
enableDNT = true
[privacy.vimeo]
disable = false
[privacy.youtube]
disable = false
privacyEnhanced = true
`
func (s *sitesBuilder) WithSimpleConfigFile() *sitesBuilder {
s.T.Helper()
return s.WithSimpleConfigFileAndBaseURL("http://example.com/")
}
func (s *sitesBuilder) WithSimpleConfigFileAndBaseURL(baseURL string) *sitesBuilder {
s.T.Helper()
return s.WithSimpleConfigFileAndSettings(map[string]interface{}{"baseURL": baseURL})
}
func (s *sitesBuilder) WithSimpleConfigFileAndSettings(settings interface{}) *sitesBuilder {
s.T.Helper()
var buf bytes.Buffer
parser.InterfaceToConfig(settings, metadecoders.TOML, &buf)
config := buf.String() + commonConfigSections
return s.WithConfigFile("toml", config)
}
func (s *sitesBuilder) WithDefaultMultiSiteConfig() *sitesBuilder {
defaultMultiSiteConfig := `
baseURL = "http://example.com/blog"
paginate = 1
disablePathToLower = true
defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
[permalinks]
other = "/somewhere/else/:filename"
[blackfriday]
angledQuotes = true
[Taxonomies]
tag = "tags"
[Languages]
[Languages.en]
weight = 10
title = "In English"
languageName = "English"
[Languages.en.blackfriday]
angledQuotes = false
[[Languages.en.menu.main]]
url = "/"
name = "Home"
weight = 0
[Languages.fr]
weight = 20
title = "Le Français"
languageName = "Français"
[Languages.fr.Taxonomies]
plaque = "plaques"
[Languages.nn]
weight = 30
title = "På nynorsk"
languageName = "Nynorsk"
paginatePath = "side"
[Languages.nn.Taxonomies]
lag = "lag"
[[Languages.nn.menu.main]]
url = "/"
name = "Heim"
weight = 1
[Languages.nb]
weight = 40
title = "På bokmål"
languageName = "Bokmål"
paginatePath = "side"
[Languages.nb.Taxonomies]
lag = "lag"
` + commonConfigSections
return s.WithConfigFile("toml", defaultMultiSiteConfig)
}
func (s *sitesBuilder) WithSunset(in string) {
// Write a real image into one of the bundle above.
src, err := os.Open(filepath.FromSlash("testdata/sunset.jpg"))
s.Assert(err, qt.IsNil)
out, err := s.Fs.Source.Create(filepath.FromSlash(filepath.Join(s.workingDir, in)))
s.Assert(err, qt.IsNil)
_, err = io.Copy(out, src)
s.Assert(err, qt.IsNil)
out.Close()
src.Close()
}
func (s *sitesBuilder) createFilenameContent(pairs []string) []filenameContent {
var slice []filenameContent
s.appendFilenameContent(&slice, pairs...)
return slice
}
func (s *sitesBuilder) appendFilenameContent(slice *[]filenameContent, pairs ...string) {
if len(pairs)%2 != 0 {
panic("file content mismatch")
}
for i := 0; i < len(pairs); i += 2 {
c := filenameContent{
filename: pairs[i],
content: pairs[i+1],
}
*slice = append(*slice, c)
}
}
func (s *sitesBuilder) WithContent(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.contentFilePairs, filenameContent...)
return s
}
func (s *sitesBuilder) WithContentAdded(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.contentFilePairsAdded, filenameContent...)
return s
}
func (s *sitesBuilder) WithTemplates(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.templateFilePairs, filenameContent...)
return s
}
func (s *sitesBuilder) WithTemplatesAdded(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.templateFilePairsAdded, filenameContent...)
return s
}
func (s *sitesBuilder) WithData(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.dataFilePairs, filenameContent...)
return s
}
func (s *sitesBuilder) WithDataAdded(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.dataFilePairsAdded, filenameContent...)
return s
}
func (s *sitesBuilder) WithI18n(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.i18nFilePairs, filenameContent...)
return s
}
func (s *sitesBuilder) WithI18nAdded(filenameContent ...string) *sitesBuilder {
s.appendFilenameContent(&s.i18nFilePairsAdded, filenameContent...)
return s
}
func (s *sitesBuilder) EditFiles(filenameContent ...string) *sitesBuilder {
for i := 0; i < len(filenameContent); i += 2 {
filename, content := filepath.FromSlash(filenameContent[i]), filenameContent[i+1]
absFilename := s.absFilename(filename)
s.changedFiles = append(s.changedFiles, absFilename)
writeSource(s.T, s.Fs, absFilename, content)
}
return s
}
func (s *sitesBuilder) RemoveFiles(filenames ...string) *sitesBuilder {
for _, filename := range filenames {
absFilename := s.absFilename(filename)
s.removedFiles = append(s.removedFiles, absFilename)
s.Assert(s.Fs.Source.Remove(absFilename), qt.IsNil)
}
return s
}
func (s *sitesBuilder) writeFilePairs(folder string, files []filenameContent) *sitesBuilder {
// We have had some "filesystem ordering" bugs that we have not discovered in
// our tests running with the in memory filesystem.
// That file system is backed by a map so not sure how this helps, but some
// randomness in tests doesn't hurt.
// TODO(bep) this turns out to be more confusing than helpful.
// s.rnd.Shuffle(len(files), func(i, j int) { files[i], files[j] = files[j], files[i] })
for _, fc := range files {
target := folder
// TODO(bep) clean up this magic.
if strings.HasPrefix(fc.filename, folder) {
target = ""
}
if s.workingDir != "" {
target = filepath.Join(s.workingDir, target)
}
writeSource(s.T, s.Fs, filepath.Join(target, fc.filename), fc.content)
}
return s
}
func (s *sitesBuilder) CreateSites() *sitesBuilder {
if err := s.CreateSitesE(); err != nil {
herrors.PrintStackTraceFromErr(err)
s.Fatalf("Failed to create sites: %s", err)
}
return s
}
func (s *sitesBuilder) LoadConfig() error {
if !s.configFileSet {
s.WithSimpleConfigFile()
}
cfg, _, err := LoadConfig(ConfigSourceDescriptor{
WorkingDir: s.workingDir,
Fs: s.Fs.Source,
Logger: s.logger,
Environ: s.environ,
Filename: "config." + s.configFormat,
}, func(cfg config.Provider) error {
return nil
})
if err != nil {
return err
}
s.Cfg = cfg
return nil
}
func (s *sitesBuilder) CreateSitesE() error {
if !s.addNothing {
if _, ok := s.Fs.Source.(*afero.OsFs); ok {
for _, dir := range []string{
"content/sect",
"layouts/_default",
"layouts/_default/_markup",
"layouts/partials",
"layouts/shortcodes",
"data",
"i18n",
} {
if err := os.MkdirAll(filepath.Join(s.workingDir, dir), 0777); err != nil {
return errors.Wrapf(err, "failed to create %q", dir)
}
}
}
s.addDefaults()
s.writeFilePairs("content", s.contentFilePairsAdded)
s.writeFilePairs("layouts", s.templateFilePairsAdded)
s.writeFilePairs("data", s.dataFilePairsAdded)
s.writeFilePairs("i18n", s.i18nFilePairsAdded)
s.writeFilePairs("i18n", s.i18nFilePairs)
s.writeFilePairs("data", s.dataFilePairs)
s.writeFilePairs("content", s.contentFilePairs)
s.writeFilePairs("layouts", s.templateFilePairs)
}
if err := s.LoadConfig(); err != nil {
return errors.Wrap(err, "failed to load config")
}
s.Fs.Destination = hugofs.NewCreateCountingFs(s.Fs.Destination)
depsCfg := s.depsCfg
depsCfg.Fs = s.Fs
depsCfg.Cfg = s.Cfg
depsCfg.Logger = s.logger
depsCfg.Running = s.running
sites, err := NewHugoSites(depsCfg)
if err != nil {
return errors.Wrap(err, "failed to create sites")
}
s.H = sites
return nil
}
func (s *sitesBuilder) BuildE(cfg BuildCfg) error {
if s.H == nil {
s.CreateSites()
}
return s.H.Build(cfg)
}
func (s *sitesBuilder) Build(cfg BuildCfg) *sitesBuilder {
s.T.Helper()
return s.build(cfg, false)
}
func (s *sitesBuilder) BuildFail(cfg BuildCfg) *sitesBuilder {
s.T.Helper()
return s.build(cfg, true)
}
func (s *sitesBuilder) changeEvents() []fsnotify.Event {
var events []fsnotify.Event
for _, v := range s.changedFiles {
events = append(events, fsnotify.Event{
Name: v,
Op: fsnotify.Write,
})
}
for _, v := range s.removedFiles {
events = append(events, fsnotify.Event{
Name: v,
Op: fsnotify.Remove,
})
}
return events
}
func (s *sitesBuilder) build(cfg BuildCfg, shouldFail bool) *sitesBuilder {
s.Helper()
defer func() {
s.changedFiles = nil
}()
if s.H == nil {
s.CreateSites()
}
err := s.H.Build(cfg, s.changeEvents()...)
if err == nil {
logErrorCount := s.H.NumLogErrors()
if logErrorCount > 0 {
err = fmt.Errorf("logged %d errors", logErrorCount)
}
}
if err != nil && !shouldFail {
herrors.PrintStackTraceFromErr(err)
s.Fatalf("Build failed: %s", err)
} else if err == nil && shouldFail {
s.Fatalf("Expected error")
}
return s
}
func (s *sitesBuilder) addDefaults() {
var (
contentTemplate = `---
title: doc1
weight: 1
tags:
- tag1
date: "2018-02-28"
---
# doc1
*some "content"*
{{< shortcode >}}
{{< lingo >}}
`
defaultContent = []string{
"content/sect/doc1.en.md", contentTemplate,
"content/sect/doc1.fr.md", contentTemplate,
"content/sect/doc1.nb.md", contentTemplate,
"content/sect/doc1.nn.md", contentTemplate,
}
listTemplateCommon = "{{ $p := .Paginator }}{{ $p.PageNumber }}|{{ .Title }}|{{ i18n \"hello\" }}|{{ .Permalink }}|Pager: {{ template \"_internal/pagination.html\" . }}|Kind: {{ .Kind }}|Content: {{ .Content }}|Len Pages: {{ len .Pages }}|Len RegularPages: {{ len .RegularPages }}| HasParent: {{ if .Parent }}YES{{ else }}NO{{ end }}"
defaultTemplates = []string{
"_default/single.html", "Single: {{ .Title }}|{{ i18n \"hello\" }}|{{.Language.Lang}}|RelPermalink: {{ .RelPermalink }}|Permalink: {{ .Permalink }}|{{ .Content }}|Resources: {{ range .Resources }}{{ .MediaType }}: {{ .RelPermalink}} -- {{ end }}|Summary: {{ .Summary }}|Truncated: {{ .Truncated }}|Parent: {{ .Parent.Title }}",
"_default/list.html", "List Page " + listTemplateCommon,
"index.html", "{{ $p := .Paginator }}Default Home Page {{ $p.PageNumber }}: {{ .Title }}|{{ .IsHome }}|{{ i18n \"hello\" }}|{{ .Permalink }}|{{ .Site.Data.hugo.slogan }}|String Resource: {{ ( \"Hugo Pipes\" | resources.FromString \"text/pipes.txt\").RelPermalink }}",
"index.fr.html", "{{ $p := .Paginator }}French Home Page {{ $p.PageNumber }}: {{ .Title }}|{{ .IsHome }}|{{ i18n \"hello\" }}|{{ .Permalink }}|{{ .Site.Data.hugo.slogan }}|String Resource: {{ ( \"Hugo Pipes\" | resources.FromString \"text/pipes.txt\").RelPermalink }}",
"_default/terms.html", "Taxonomy Term Page " + listTemplateCommon,
"_default/taxonomy.html", "Taxonomy List Page " + listTemplateCommon,
// Shortcodes
"shortcodes/shortcode.html", "Shortcode: {{ i18n \"hello\" }}",
// A shortcode in multiple languages
"shortcodes/lingo.html", "LingoDefault",
"shortcodes/lingo.fr.html", "LingoFrench",
// Special templates
"404.html", "404|{{ .Lang }}|{{ .Title }}",
"robots.txt", "robots|{{ .Lang }}|{{ .Title }}",
}
defaultI18n = []string{
"en.yaml", `
hello:
other: "Hello"
`,
"fr.yaml", `
hello:
other: "Bonjour"
`,
}
defaultData = []string{
"hugo.toml", "slogan = \"Hugo Rocks!\"",
}
)
if len(s.contentFilePairs) == 0 {
s.writeFilePairs("content", s.createFilenameContent(defaultContent))
}
if len(s.templateFilePairs) == 0 {
s.writeFilePairs("layouts", s.createFilenameContent(defaultTemplates))
}
if len(s.dataFilePairs) == 0 {
s.writeFilePairs("data", s.createFilenameContent(defaultData))
}
if len(s.i18nFilePairs) == 0 {
s.writeFilePairs("i18n", s.createFilenameContent(defaultI18n))
}
}
func (s *sitesBuilder) Fatalf(format string, args ...interface{}) {
s.T.Helper()
s.T.Fatalf(format, args...)
}
func (s *sitesBuilder) AssertFileContentFn(filename string, f func(s string) bool) {
s.T.Helper()
content := s.FileContent(filename)
if !f(content) {
s.Fatalf("Assert failed for %q in content\n%s", filename, content)
}
}
func (s *sitesBuilder) AssertHome(matches ...string) {
s.AssertFileContent("public/index.html", matches...)
}
func (s *sitesBuilder) AssertFileContent(filename string, matches ...string) {
s.T.Helper()
content := s.FileContent(filename)
for _, m := range matches {
lines := strings.Split(m, "\n")
for _, match := range lines {
match = strings.TrimSpace(match)
if match == "" {
continue
}
if !strings.Contains(content, match) {
s.Fatalf("No match for %q in content for %s\n%s\n%q", match, filename, content, content)
}
}
}
}
func (s *sitesBuilder) AssertFileDoesNotExist(filename string) {
if s.CheckExists(filename) {
s.Fatalf("File %q exists but must not exist.", filename)
}
}
func (s *sitesBuilder) AssertImage(width, height int, filename string) {
filename = filepath.Join(s.workingDir, filename)
f, err := s.Fs.Destination.Open(filename)
s.Assert(err, qt.IsNil)
defer f.Close()
cfg, err := jpeg.DecodeConfig(f)
s.Assert(err, qt.IsNil)
s.Assert(cfg.Width, qt.Equals, width)
s.Assert(cfg.Height, qt.Equals, height)
}
func (s *sitesBuilder) AssertNoDuplicateWrites() {
s.Helper()
d := s.Fs.Destination.(hugofs.DuplicatesReporter)
s.Assert(d.ReportDuplicates(), qt.Equals, "")
}
func (s *sitesBuilder) FileContent(filename string) string {
s.T.Helper()
filename = filepath.FromSlash(filename)
if !strings.HasPrefix(filename, s.workingDir) {
filename = filepath.Join(s.workingDir, filename)
}
return readDestination(s.T, s.Fs, filename)
}
func (s *sitesBuilder) AssertObject(expected string, object interface{}) {
s.T.Helper()
got := s.dumper.Sdump(object)
expected = strings.TrimSpace(expected)
if expected != got {
fmt.Println(got)
diff := htesting.DiffStrings(expected, got)
s.Fatalf("diff:\n%s\nexpected\n%s\ngot\n%s", diff, expected, got)
}
}
func (s *sitesBuilder) AssertFileContentRe(filename string, matches ...string) {
content := readDestination(s.T, s.Fs, filename)
for _, match := range matches {
r := regexp.MustCompile("(?s)" + match)
if !r.MatchString(content) {
s.Fatalf("No match for %q in content for %s\n%q", match, filename, content)
}
}
}
func (s *sitesBuilder) CheckExists(filename string) bool {
return destinationExists(s.Fs, filepath.Clean(filename))
}
func (s *sitesBuilder) GetPage(ref string) page.Page {
p, err := s.H.Sites[0].getPageNew(nil, ref)
s.Assert(err, qt.IsNil)
return p
}
func (s *sitesBuilder) GetPageRel(p page.Page, ref string) page.Page {
p, err := s.H.Sites[0].getPageNew(p, ref)
s.Assert(err, qt.IsNil)
return p
}
func newTestHelper(cfg config.Provider, fs *hugofs.Fs, t testing.TB) testHelper {
return testHelper{
Cfg: cfg,
Fs: fs,
C: qt.New(t),
}
}
type testHelper struct {
Cfg config.Provider
Fs *hugofs.Fs
*qt.C
}
func (th testHelper) assertFileContent(filename string, matches ...string) {
th.Helper()
filename = th.replaceDefaultContentLanguageValue(filename)
content := readDestination(th, th.Fs, filename)
for _, match := range matches {
match = th.replaceDefaultContentLanguageValue(match)
th.Assert(strings.Contains(content, match), qt.Equals, true, qt.Commentf(match+" not in: \n"+content))
}
}
func (th testHelper) assertFileContentRegexp(filename string, matches ...string) {
filename = th.replaceDefaultContentLanguageValue(filename)
content := readDestination(th, th.Fs, filename)
for _, match := range matches {
match = th.replaceDefaultContentLanguageValue(match)
r := regexp.MustCompile(match)
matches := r.MatchString(content)
if !matches {
fmt.Println(match+":\n", content)
}
th.Assert(matches, qt.Equals, true)
}
}
func (th testHelper) assertFileNotExist(filename string) {
exists, err := helpers.Exists(filename, th.Fs.Destination)
th.Assert(err, qt.IsNil)
th.Assert(exists, qt.Equals, false)
}
func (th testHelper) replaceDefaultContentLanguageValue(value string) string {
defaultInSubDir := th.Cfg.GetBool("defaultContentLanguageInSubDir")
replace := th.Cfg.GetString("defaultContentLanguage") + "/"
if !defaultInSubDir {
value = strings.Replace(value, replace, "", 1)
}
return value
}
func loadTestConfig(fs afero.Fs, withConfig ...func(cfg config.Provider) error) (*viper.Viper, error) {
v, _, err := LoadConfig(ConfigSourceDescriptor{Fs: fs}, withConfig...)
return v, err
}
func newTestCfgBasic() (*viper.Viper, *hugofs.Fs) {
mm := afero.NewMemMapFs()
v := viper.New()
v.Set("defaultContentLanguageInSubdir", true)
fs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(mm), v)
return v, fs
}
func newTestCfg(withConfig ...func(cfg config.Provider) error) (*viper.Viper, *hugofs.Fs) {
mm := afero.NewMemMapFs()
v, err := loadTestConfig(mm, func(cfg config.Provider) error {
// Default is false, but true is easier to use as default in tests
cfg.Set("defaultContentLanguageInSubdir", true)
for _, w := range withConfig {
w(cfg)
}
return nil
})
if err != nil && err != ErrNoConfigFile {
panic(err)
}
fs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(mm), v)
return v, fs
}
func newTestSitesFromConfig(t testing.TB, afs afero.Fs, tomlConfig string, layoutPathContentPairs ...string) (testHelper, *HugoSites) {
if len(layoutPathContentPairs)%2 != 0 {
t.Fatalf("Layouts must be provided in pairs")
}
c := qt.New(t)
writeToFs(t, afs, filepath.Join("content", ".gitkeep"), "")
writeToFs(t, afs, "config.toml", tomlConfig)
cfg, err := LoadConfigDefault(afs)
c.Assert(err, qt.IsNil)
fs := hugofs.NewFrom(afs, cfg)
th := newTestHelper(cfg, fs, t)
for i := 0; i < len(layoutPathContentPairs); i += 2 {
writeSource(t, fs, layoutPathContentPairs[i], layoutPathContentPairs[i+1])
}
h, err := NewHugoSites(deps.DepsCfg{Fs: fs, Cfg: cfg})
c.Assert(err, qt.IsNil)
return th, h
}
func createWithTemplateFromNameValues(additionalTemplates ...string) func(templ tpl.TemplateManager) error {
return func(templ tpl.TemplateManager) error {
for i := 0; i < len(additionalTemplates); i += 2 {
err := templ.AddTemplate(additionalTemplates[i], additionalTemplates[i+1])
if err != nil {
return err
}
}
return nil
}
}
// TODO(bep) replace these with the builder
func buildSingleSite(t testing.TB, depsCfg deps.DepsCfg, buildCfg BuildCfg) *Site {
t.Helper()
return buildSingleSiteExpected(t, false, false, depsCfg, buildCfg)
}
func buildSingleSiteExpected(t testing.TB, expectSiteInitError, expectBuildError bool, depsCfg deps.DepsCfg, buildCfg BuildCfg) *Site {
t.Helper()
b := newTestSitesBuilderFromDepsCfg(t, depsCfg).WithNothingAdded()
err := b.CreateSitesE()
if expectSiteInitError {
b.Assert(err, qt.Not(qt.IsNil))
return nil
} else {
b.Assert(err, qt.IsNil)
}
h := b.H
b.Assert(len(h.Sites), qt.Equals, 1)
if expectBuildError {
b.Assert(h.Build(buildCfg), qt.Not(qt.IsNil))
return nil
}
b.Assert(h.Build(buildCfg), qt.IsNil)
return h.Sites[0]
}
func writeSourcesToSource(t *testing.T, base string, fs *hugofs.Fs, sources ...[2]string) {
for _, src := range sources {
writeSource(t, fs, filepath.Join(base, src[0]), src[1])
}
}
func getPage(in page.Page, ref string) page.Page {
p, err := in.GetPage(ref)
if err != nil {
panic(err)
}
return p
}
func content(c resource.ContentProvider) string {
cc, err := c.Content()
if err != nil {
panic(err)
}
ccs, err := cast.ToStringE(cc)
if err != nil {
panic(err)
}
return ccs
}
func pagesToString(pages ...page.Page) string {
var paths []string
for _, p := range pages {
paths = append(paths, p.Path())
}
sort.Strings(paths)
return strings.Join(paths, "|")
}
func dumpPages(pages ...page.Page) {
fmt.Println("---------")
for _, p := range pages {
var meta interface{}
if p.File() != nil && p.File().FileInfo() != nil {
meta = p.File().FileInfo().Meta()
}
fmt.Printf("Kind: %s Title: %-10s RelPermalink: %-10s Path: %-10s sections: %s Lang: %s Meta: %v\n",
p.Kind(), p.Title(), p.RelPermalink(), p.Path(), p.SectionsPath(), p.Lang(), meta)
}
}
func dumpSPages(pages ...*pageState) {
for i, p := range pages {
fmt.Printf("%d: Kind: %s Title: %-10s RelPermalink: %-10s Path: %-10s sections: %s\n",
i+1,
p.Kind(), p.Title(), p.RelPermalink(), p.Path(), p.SectionsPath())
}
}
func printStringIndexes(s string) {
lines := strings.Split(s, "\n")
i := 0
for _, line := range lines {
for _, r := range line {
fmt.Printf("%-3s", strconv.Itoa(i))
i += utf8.RuneLen(r)
}
i++
fmt.Println()
for _, r := range line {
fmt.Printf("%-3s", string(r))
}
fmt.Println()
}
}
// See https://github.com/golang/go/issues/19280
// Not in use.
var parallelEnabled = true
func parallel(t *testing.T) {
if parallelEnabled {
t.Parallel()
}
}
func skipSymlink(t *testing.T) {
if runtime.GOOS == "windows" && os.Getenv("CI") == "" {
t.Skip("skip symlink test on local Windows (needs admin)")
}
}
func captureStderr(f func() error) (string, error) {
old := os.Stderr
r, w, _ := os.Pipe()
os.Stderr = w
err := f()
w.Close()
os.Stderr = old
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String(), err
}
func captureStdout(f func() error) (string, error) {
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
err := f()
w.Close()
os.Stdout = old
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String(), err
}
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./docs/content/en/functions/fileExists.md | ---
title: "fileExists"
linktitle: "fileExists"
date: 2017-08-31T22:38:22+02:00
description: Checks whether a file exists under the given path.
godocref:
publishdate: 2017-08-31T22:38:22+02:00
lastmod: 2017-08-31T22:38:22+02:00
categories: [functions]
menu:
docs:
parent: "functions"
signature: ["fileExists PATH"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
`fileExists` allows you to check if a file exists under a given path, e.g. before inserting code into a template:
```
{{ if (fileExists "static/img/banner.jpg") -}}
<img src="{{ "img/banner.jpg" | absURL }}" />
{{- end }}
```
In the example above, a banner from the `static` folder should be shown if the given path points to an existing file. | ---
title: "fileExists"
linktitle: "fileExists"
date: 2017-08-31T22:38:22+02:00
description: Checks whether a file exists under the given path.
godocref:
publishdate: 2017-08-31T22:38:22+02:00
lastmod: 2017-08-31T22:38:22+02:00
categories: [functions]
menu:
docs:
parent: "functions"
signature: ["fileExists PATH"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
`fileExists` allows you to check if a file exists under a given path, e.g. before inserting code into a template:
```
{{ if (fileExists "static/img/banner.jpg") -}}
<img src="{{ "img/banner.jpg" | absURL }}" />
{{- end }}
```
In the example above, a banner from the `static` folder should be shown if the given path points to an existing file. | -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./resources/testdata/circle.svg | <svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
Sorry, your browser does not support inline SVG.
</svg>
| <svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
Sorry, your browser does not support inline SVG.
</svg>
| -1 |
gohugoio/hugo | 8,131 | markup: Allow arbitrary Asciidoc extension in unsafe mode | This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | gzagatti | "2021-01-11T08:36:17Z" | "2021-02-22T12:52:04Z" | c8f45d1d861f596821afc068bd12eb1213aba5ce | 01dd7c16af6204d18d530f9d3018689215482170 | markup: Allow arbitrary Asciidoc extension in unsafe mode. This PR implements proposal #7698 which allows for arbitrary Asciidoc extensions in unsafe mode expanding the range of possibilities when using this markup language.
The proposal allows for arbitrary extension when [`SafeMode`](https://docs.asciidoctor.org/asciidoctor/latest/safe-modes/) option is set to `unsafe`. Any stricter mode would prevent arbitrary extensions and only those listed in the [configuration](https://github.com/gohugoio/hugo/blob/master/markup/asciidocext/asciidocext_config/config.go#L40) would be allowed. | ./docs/content/en/showcase/stackimpact/featured.png | PNG
IHDR $~ gAMA a sRGB 8PLTE&)1+.6-08,/7(+3),4*-5'*1'*2}/2:.1903;14<25= 36>46<$'/(+2)$
wx{,/6& &,8 w HIK~&# #,NOQgilBCF:;>TTVopsՊ~{acfXY[ kά\]`'%9Vn<>C+"'&'su^!VwȌ555g..-#El05A[)/<&2F"N~>@Z W(IDATxaSHǃ
QT/E&)A`R4t,:7N}S?m6 V[Y%>neVH xqX @ w ; w ; r r @ @ w ; @ w ; r r r i ~._ң; ॸ=<EB Aۇׇy ~GOMv+&>KG +/r\^A]?țd2ܪNwl?BN/= @gOurONt!> ,̣wYTaJ[//)1
dUEkwnyRunل5㞪ۮgw8ăB?ܐ#gW偒YAJf5͢(G^<j]\uۉunB @/_LI٥?</,]b>q[FZFQ)
ֹߪ }Zv&Ξiyx1!$x$%vPBa}:4Urt/sY&=f8HanzʹNξo-Mz}3K
-2\Q-QVC"$.l=wjQbvP
JomgQѢ4sRZ]xX9\N./?oK8^7FbrOtb+o+ߧK܅tOJmu{65cOcQ꾋Suv۞NNy_ʝH4IgdYnDghv\D"ˇǜ$Qa
SAHtyqgKfCŊQ
bJd)#F-vpla#SZϐ_3(LDy<[yE/el}uNhe9@~dN*UTrk64+;s{#w|h)J9>j+'Aj(<7Ycm%%WaXh4,=xSͲ4f|U^Nhrr(+_{։,Z ZrsӒԨ.J!L6#CׂIWrF2**Mez6`F,I8WCRh-t%OUpՃ ,ЊmX?C:#}oEXެƢ0>+Ġ/!n*i\r:{d\UtPUr*|"s3/sSvn¢U7r4=\E)#4v7GfüAVgwd2tMXӯ;u4GV;4Im4
BVkoajnSp%oCau5}kJQǷy%6<MJ:AOZ&
$B8:K*賣Euh-t.7ti9HFl4`zKpɂ)IαoGYJ4cFnȦnMvtnR}Wrjo7fi"`=6]~r/M&בŋ
!/o^\g$Jз"Bܳ]ܙ7Ҝ4{XnfOG9}"h4z4߳X7}
LЁ
d垚G`>ð@YbHQ=Jk.rWbH]K
75$mUnyCJ&m1t۫
eEX-zSas,p\zEP}Xd,~yhlC
ZO5H=XFj5J.T#mӧV)
U@TycUJXvZ.V35zjjYzZJ-g^P>7^[06nYyغ+{N'GI`Qv\]ˠŦ8]~Ϋbpr_eCןM45ꅺY>{NH﹟6ΌTNtߟE1,SLKr?g7nag4-Z0_ˑ7bs#db;hZ1br7G%~&%}XՒNZWJZpʝ]0ƫ빎V+wFǣfs{W w_;mrцũKem6F^)EU.KIg/tcֱ0LlɊ4v,;Ŏ+ҡ4Ri˗% {difv:`G£WGnOh{n5̯\щ݉;XfOExbLe7-i;rJ;SepԝvGn6O^O3BXqI)ڕ*iW?̿ŇYuUop=+]\.77
7ַymPjf~|-;p-\l7$e!Y-uIDE#> $RpDfԐH7
akRȲ9γeT
#©E-t[B8lQ
=7?=MΌr|6 )ḽuIVT4xj ,yglgԲ
((W=nOE{sqHZ<bDy;FD^D=!aх#k,/8obV"rإ1YUS݇% \>.3
#ʽRp
>n?
jOPh+r vr~]o?{G_5JCp)}AN+4~i"_eWpnc24
_ys{ELXF pк8McV5<ނ4lLh]w<ge͡}/Hagv\%B9Z;7KM[摔s#p;(j|zhu'VakJ(\"d0l"SPx൭N'_wА5ܡ``2V:S@}ݲe4:AY)C{:4L;c)[F]WpǿF@>o|v` [7{Q]iӍrǠ̞Z?_6p]ϳe
-s{pHDȞ]Ww~
VqBpwY}zw}yQpOeY%' c~H[+};m8zme X𩡛;] AH!J5_6PWQI<NY2>!qb[닐Uw{MA
FASŊ7TcRܱ=Az4p~"E;4E rߛ}\..s LPP wlRfT*~![p_(nsٻi;K?rO=(Se:ʨii:3G=JIx"&=g];ny) Ɓ+laɣ
8l*OТr_]K[xƞ{jVH<K*3w{8m7HՋG]zemQPVIvbY{{8QDŽF>Y0װC#KUWrOo>,)C1%_G(;&&ܯs\k[xG[2nr?
hi0*wVvh/DУw
&|k"܇,M T/F'Y7ݦ1}
w!IDW%ܻ^pu^5 ܞZ;=T 9P8yM`m[0X\:BQG$;8]hG-+wr9h14~;oվ_Zw}~պyԙ}]_qU-;Ld7ĠP0,N,/~>w
"*N\Pmpb(7#vrG(qۀ;Lc*d R]CޓgnqDȷ w&i_1ȃ=^pAS6n.bxPd(RmPWMZٮPݎ'aml-rc=0OuN4ac=pO'2kPCCo|l2R}v;jo
|}vm ϖ)-}S'w2'(IoLSXt0F>Rp0
_C#CŎ0.䕵NM(}
r瞧BV}1*EZ &p6u7ܖ sh= B[&} we2zn0}*M<p$zc˴>jRW+8mwhA9`g+w];|< <6=euR_QyCzw>^i{*o1=)sWP^re|өsEC<%/6˛ֶz=8r.9}>a
|舓\4esR8Yi:~<b2u#/f;eM/;dmngqݤ_kOMkg:p d`$bR[*o}CfR3Q8^3J!C2MpZpsne(~=P ]rwxB@ *kޒU϶4:yjFUgMJm-rq7g
H=sIv璻+2f=.לOܷ^lַV M5_Di:pyyr^/_>61|1{I#Tܝҧ?fO+Cr@
"U&c5gFEill")
GF&rwn'2Nvh+eq+ZFeUNm:f{At;Nur}`ry^6SfoKƹT>}JFEų,s}QscWꆺ^ݦ'ܩٞFXG~m&EگTUޓv}\hr"<=4}W:R_^>OfDˢ6eD]ݭ{~[fi4}a'1uݗV>Li"w-sfmLv}|a+aKÞGgZ7[ɝgM-a7a>dVӁf1a|bΔHr˜Ș3r7t<PՑfj4c&BԑgSY^9IYR1wU.?K5V<s,#n'gZ.[;A=SjT3ˠ
5]G
WG&R%'yr#nC"h,ɶvvYoڢY;>L}rwprQo'8qsbJ57LԚgKqBg9fꗛ_Ka3mNrsZI锃v9ff}Q"~8M
Ձo(ioz`e#:zWQ-
MpSљlB,s0jv-r{RfnY@دDsMF:Ic^r~Wh.}NYeu
-}f9X+Qt:O -Y*Z>k7
3YWVP{zD.j9bލ
F2jUn*;r&[ŏwi6ںQN[hݭݡevfj--3v|6i4''lbQqU-d<ʛ2E)gQ.=6"W:9DoKxWLz<K~D;5q%NeoEȝnhy͠#mב;^qtto?Ax4W_Jd2: [jiSҪKc)k&n}-$dzk=}MZ#,/%77TJXr[4?ղf*/)K*smzVҥkRb~ؘѭ˴/N kVxS\d+bbtAτx8wa/."ʃ˯gYOwMWW~:`<7^CO/8q=˞iM`zGN,Ҳ=nqGvjb(qI) 2.tf>\1r Q3POxճX$s,fB*.<\gn]*I#=Zg:g*auXѓ,5 &]Vf[+*gXVzH&`k̛U+ҶrR"dމR"H91ҕ`Y*aXÊM[x"_v;](O~Uv7Үٗ_fr6wĔu(FcəH*>ahxIBDwǭvӓpΦvŘe?[- gNJWo{s_2ډQG*;,+7EגxT]YG."q'r)D`;6RO.ө}:N[JdorgS+C\Ȟ~b)~`xZyO6s3?:9>;S{лZcz4&>3wCT:=hS#'{5L7ͫ< ہ|T>?t Ӑ; (wD`3NXq w m{O^_]w@o;xԕ¥r/'s ^\'
/.ː; ܷ r #'J/^u@ 7ga Nz; E w @ w ; w ; r U ; r r @ @ w ; w ; r r ? mo%xM7 Nәio8!#Ym>Bۆ_[āw<ehߋs<H7ܐI^},>
=Z,BEuWgYc<J-ʤna@Ǔ}*醵QP(N}LZ
2z,nVf]w4|6Nijkcâс`FU[L6ĦRE_ڌuXO f-C{Bwml&oQP
&spCubqf9fhZ(Ay2sbec@ XQ夘'Y?[<*
(EwЦ
[]:R;4IHaɜMHLE]nDTM?~gf"L'XԞ07Hj]4PI&8"Hl<fHmDKMX[B9sT>2|3iVlV6
%$tzltHJf| b{F+qI͍>1j7t`B
V0;9TMb!*;s07oy5%!i7g0aRfFgFȆ'}(0U91; dh S"۴<W`RaZќ}Dl&lJ%]KpV&Cqa;;:{̀3r}=iNsѣC;"}<%wZ̎a Q0I>pFQ>7Og
=]#hM{¶6s/{j23NdsO
P4wbty
bPVޮ"T=iqv)\%w&qW^h2N殱P'q\ZX*3)ܠ;zxA̝3r,VcmH|e&hm qɽ2<MhTҴ7vyNۘ\˟5[AO3VK{IOQDLQG'7o>ebМ6(³6}Hsb)y&bE~5쪓; -fm(+>ib1ݲA]KS/u8l"qHq4_ ]m)
@TmvO}IH("bSS45.ҸpJ':s(d/sgM@d+X0YB)0ƦaRc*]e΅7$cP)&? 61{~63rP
hBs*
<r.!zF̝ZL,]{qvְJn4VB疚5I!V'/1CWAV)i5m̬7}_@sW^
&YWx&@wO+˯<WO6Pֹ^չ)PYH=]<,c6$k_VGBxJuEYMr
t]HM"WN:6VA2:uZ*>21{s͔A%MxTVg`&meM,2[Oo4:
p9eDO-*9BUŔ8b$AۅwnG)E.p*4dQB
Wu]b=gJPf)FE1:7sSsn>a-;mfؕg'_`y亮SY/U`ljP0\*3EOhI&/'y~Gs'剦<jQmIfaB5TM^YMi
ƤeVI:T¤y VCs xchkiH:c: 6Āt@Dh_>{NP(@69|S
7*cEv9A:fHC.ghz*21AcX:@l ~y"%&[[M_ >No[1v R+?8á¿QE;N`ކ#~BmD,~Tw*_PxxD >)-n?7Xd?W9kVZ⧔er*Շ4n*Hj[!>Ҋ~Y]>];tEjjjjjjjjjj7vΛ)lr1M]*-+-{[pn'y wzL=/|zv4<$[*?9>Ι@G^ʻ/{kBb'iNTo'"bnχt~]_fBQ^v
n{˅gho{ixx6D]
U~y{1s`{~5
W^Cq!v>6e+Pq
;y|3UL*Z8|y#.k[c#
=ׅ"BynدlxwtztezdwIa-}tpΗ\@FD[p,_zzx9OGkޘIkw =wAGB'M娔By5ʀDFBcT D}-a:06wҜ;LjrvsؽHn1/ Pґs1µ=\`V3L]N e&ȱ:W'UR,㸟+fB;l\Uj<yE電q%Hp08qwp{kKܔwrB$J[TJN`Bb c{o^=h:om2@";բ)xVیfdy2uB3ءΡtamy{ozPC+_*KPC0$폴wgPPվmȽt9JڨY+ 3)J"svK@ @8cFr4Wiږټ66V>5=0bw}dvagjYMBl[EdA@SyLk#Vێ8&P8I7Aud̲dŋmnBpaFϼ4b1yГ:祧l]E(uR{2=RA#&pkS~ZO
T
Gqqe);6U+\䫘<rvMhGP)rꀢj̨S5qep8Fs.ϹUqşxHۆz *g
KM#36jW8yL#>i:,uBr1
a|K䠤U<$vĮ
0-i@GE~,j%UXIz~b@';삒Z~/[i R0̼ܳM]YnP$
._3%U:Q-#[}e䭈+*P@=:Kkg#loV_Z jטϩH5uupw$$2Þ?wQZwp(
4ӟb|-wx8khKږXM)d%>T
0^mjvHAyjsp?e d7|3@87l>bà!珀9{Lg❷~0ϩxIi:b:hE4Yֳim/'S6q#A/@ji|:|P!K"ıJtP?Dݿec.byϴVRci!l@(!Kc#^.G?[Dv)^0bm,nNmP V %f/PZkQswb&Z%-Ki2\AR5$oM*9<n)5T"v"Z/fOm{XLEiQ됰)>=pW+*"c&di!ǰv#-QmZ.b_!]44́o(Cwn̯ :B#n/`SdjLdt.CC"^))k`kݧyHFbfDTMp!ruj#}=9=eעsbP
n`ywsP4+
)>jpwMdUYxjM&I=nU;fL*̕q!G
#BwhF;;E
l(G{&JZ5ęnaf[X1a,A~pGeۼ9\Ф^+ }=CO6_521 $cI/ŃWj۷P[;rUk
w <cTTD{}9V]
b2ՑXzQIC:8ڞWM{Ubnw9;W,iw8jhҥnfZxl;n'k,}$ 9s-QxAK
R6xɮPzcʉaȪ^30u:"wVD]0Daխh{.*1m
/^~n|'
sLC
q
#<55p@,[i~B
G/KΡ۽6hoA9ݘJzF8e}(sCiBVTݐ"5pr<;g!—; "y%>([~MlLAaIWpzE,iz*eijx-p'6KiVW?
Zu4SU\"w-pڎ}EKX]vZN(BY
){ie*<w$aaN@$GIT^AչVe9<,Y!?Y:Hp"',[pz⼚Ԗ ݼGp_ImoMOWLܯWu~'BB^q
ܥ21_poHfռ_*ع!4r/X
f+Y{arigJ:+6W6'
|Kz5bm| !=4wcH{*Ϙ^@Dw% 4r)8Q6LHДז {Zk"Wv +»-r#C:[fV!]pߛ5pCΨW !s/FȧMoc">ܷݏ|Hטu|집{"q4%roOJs%o@;=33Ǘaܯw^+VB+3OI'\S53S;@unO'Vz4Zpkv]<V
u]\4p/CQ$%674
Q-Hz͝TӵN=ܥ 4=p{J1# />;F{oKQnQ
.\jÕ%|VvlnX{/_;Mmsp;ƹUpwF+zmm|"K,s)CeG]E:RԨ}͏a V;A+ˀ4Ǩ[O@oUps^%l<tq,=OǸ?ҡ?]
1譬
O5
\
c5Ju"j:,kdU4EPz.{ȹ \&Qtwvn@pE} m6qFC?ڳ4LwTwelWtS?"?H"tgZ$ǤRA):liQX
B<P\6p/
/B swp5oJjG\78=G ֟t,Z
`~uItܩ=ꢂ;~SrHȏT2#+X븂;{A[{}\Wm4)4
.چPLi+(E
,a+ɀF.cu.JVN>wp}jb4r 0vgi|+Տ
5/#</:6yU,E!^=p7pf-FfzӴEghlId%-A4w-)Rc'NiH)Lzy[I2s/egR]{%Dzw++#`7,f"\z&sWeZFdl¯웰KTi[LlO)X"tTHy!I#I`﹖$$G;Xe`P#0hab~
j~>$-%1:lsDtVr}y-4ΕZ?so)Oyrb2H :c;X88ozK4b/CD+2A/P"Xc
G)lSZWZC
ʻ.d;#=m99
n~
x5MT
.K_](9devFr;؟٫{uO]B:EF{Șý!ϭE_U9ʧ :͐{?g!<$Go"^ȻGJbNx(@gPhKkH<J#QVԲY=Y;>S鷞qyE+>sVC?|&֥Yj8U_?z&~SP?en>;h"46֯O&8
[.HOb|dBFZ6d=]Eo-
IDZ][SػqU$1"QOtZlE"9 D:0i{j-|'\2~&RFK~ 7?6lS78I{ `;D ߅QK++ aR_F{x% aP p^ m_b2{ Z|GP q=cb_1{*m{V{{{{{{{{{{{; ; u0/'/PhzNWR?$`lSxJwPR9)9I__/]iN bip1ӝWͰN>z,"^V|*WY]M^KxUPfgiL뮒ڵ٦|C:hh#{>;(L3v)C[J@ĔncQ7=9mQ'Wh+
)YKpS|aY6k6y6Nu'wpW̴-WR j\h SN)eDS4ijS'HPBwUi|(:J'7eCwZ$XK@sʹabDFQ45ŔI|So>vϝL
,&a9
٢NE 0&w_ymgыWK5CȴGJbK cDuK*
tQ3ǔ#}. ``nU=Dr^jX%On&x̪ά0g֍|gG+kq%F]+0g5 +DӚ~rH?w9룺3-@ec%[ɕ&єr^mgDߣ&ܑ\;C(DsXqӰ2mr2s|B}G-W_p!?/㸵×&ۃnBpL`|#{i4='M+?)Eo
~dJpSJ}|Qrq|;,od=WŧJ>sh0lI}i "9un~k o([ׄo(8Y0%clj,Y\?wy$Xsǔ7j1NPX!傆,1Oo Sh#dP(#Pl<V[{p]#5.@eY%3Lm#UܩC\Fi}ٖnG-6>&R}*4/c@J_x4]+$|Ӊ)^Wfzqe|0C79Cg`ۨ4`ipVRdQ#Yw>5FTs/#Y;:p3XAR. bW%4C8e)$HuM[fE$D)g]ztٕ/'ۤ00eMtH`5;hJSv&n
\V˘d%YN%M5Q*oĪM2qg_%~msR`f4M-P!,̪QAFR uJ~vQNxQ5N7s}>%chuZ,]ЖtMS^~!N䳬$IAY_ZT"J|$U]tC
zI2~h*
DkňL<(Pkv.&iixI؏-*^%quLquBiExXEw>w<s-$];|8xd!<>%@[k$kXA lܴ !
tup[=@-@uYN$Z~6m`F;R -|:J)*0/1+
Z!k0Rfz^Ǹ9wY%b R
*c{E j+,ƄBJ,tb>s"@4w ŚK0!Ի{D34@e;BxVKNzM4)iwfݻHWznSe UP+]::sF*֡g2%p.;P2!z#T#כU-<N^l<ȱR{Is{]Ht|
d^}Ұ[8LRvA)-*!: %283MXUM5VC)Hğ R sޯܫ<ĸn0<<Àȱx&wG);
c~Ϥ/TaJ苀Bǔ>x4cF2]^fgH+Y.8OvKDp73Ȁ;{%ωo?eYn1fYV~ԃ源;PLCC;7c䝹jR_}L",'J7m=?ŖN>WK@_8G jAߴ*٘2=myj=/s}7>PCr__tp4pD
z*jy=0
Ӡgԡ'l>vi*^&jែYUKJʰwYIMulb2zdzbS-+ynQ2[~!6w_uS&YpE~Sbj扽/o,r~K&xj\v Gdxƌ-;7mUJcxɢ nJ'2QMn:"⪥
5WjqB*J~ɣw;Kp
a4cC_=N28ǪV+}!)KV[Iejc+~
g$OpeǔHWGpow8w+pOyMƉ=w[bA
BWUԜ:8}HЁ;tgp"=Rz<,B@]Ef(eHD饧P)g<lQ<N΄Ǡ=Bu+ءgeLaV~O՛5;客Po=s
0.C }s30p;xRm70%اl1;<ꧢg)o=.Խ(A>Ӣn-'SeA;O|=>=G9~,=Z[bi8me6ϨzɓP-=dz> Vy
>r Ki<0 aJa[h=jr4)(={ .-Ôs`&p_)3R1.こKÈSM)~RجopSRp9Vo7-Ps˯釽v\xLK3xsN| %'$y<(?ރ{ɍ:ҋg"KoV=w ] /T>tEð&p
x:Bw..vܛHb$Y.C|yn&p'у=OH;gbwmˑ*Ԓ@.u/w ɞۺ K\&nw(FR=5ĚFᠷ%PY{?ϐw#pw'"`'pwo%!Ά#jO;X57-_|#Ha2`NjAE"0na&\wUdRK*wK$[wꠜ<(:wo Up.i
wUb,Σc4u~'8DWAܽ~/us~B%Gn0 jeQikcpLMC9Ӂ{757Thcrஜ !U [<CWwLfRw+Ҫэ&dԠC$)2-V 9fR2 vvRx.
uPXͅ{yS\h}šׁ{(#d"ԉJ=ToLaY`q)2'UͩiE
H)&
VX@2͔A4bFJKL]#lwE ܅¥<<{5QiD!eJSJ5."u@1dbM.=A
P1% "TwFi?*fD]\C`\bA4{"/s)X:
;@z1a^ 4$iGrOO$
!>/m"ˢxq 7/@D=3l\/Avq <6wwRq$9(fl1K
Zf9wS:pzH5KL>z BTH5
5ֱpaimsWdR>"'!EV2M9u:xCL,4Ϛ}yN{@!cig~&͎kJ(~}mY VґhSWYL37co,(B3:?;<{
R`I 2T?]
prPO`<Xu,
e}++'J.; iprpΙYnCUָbiv92ipr("b,2.<QSxgEx-F7]̭O ".Q|eAƲq,
F< g+c1J<b'sbfr;e),htyS@*dvu"mX'!83TIq^sH)bGTiI<H`u)b>qQ)m_]
UP?<4q9vbn"\)]So,م*xYݵisoQPԯ.V|^Υ߹7~};:wqtޜ'u39Eώ)fhӀ^ArG]K/Yη꓾ٔJ(l)i5RH]
XQƌ`< 9&B8OG3sJUR,2?Ejf|b9p\U뺊rdeprS% Fj4N=ԯ u̡h,m)˘SSw]L_">G&}w³PwWwܷ6rM!Qt攚njޒѽ,*/愛@M-yZ=Pߛ>#vWw\dQi{xxWbV%[Κlv˽YѴ^::ώN,a`ɥcϡp=U"w 'N334rTS PÙZbU,7KvfaQ<tzM-ڝ NMĎKmO<N\ KsҊD/)0pfyeM{@s=~ dݍ fWn/Lurgӏ= jvnپwơ9Y8&axTF$Lozh`+(7ERQzri*wXj?|َi=Kч~Y?
r:3O¿q>)= <
`)Xpr ^;L!%I`8c/ KN_:,Z@H
( H?Baf2Swr/h${irWKx)?CEdPfa|__۟6;@,ggJ~iI?^ϼC&Wծv]jWծv]jWծv]jWծv]jWծv]j_־( X
y0S-
+ [3q6?tkbBNCySrRѓ?:1z-i*>$+Ҍ9qLt8-ɓ'~Dg$oH{RɟS:ElU08moJ9=dz2Y~J-8'#:Bx0.˲/7'OʧmH֍ :|ܩT/OޞK
O&]9m#,sδ"VR.,JsdyjC*>d5|BkωaQZ D N0Rz6~InO1ZeW⍳sYc#8#1FE@ʶM#hhwG(<.p!c.)8g@PP<I9_(]ӋՁ+Y dKdsODTOAEVR%qrYސX^nQ343\ygB+Np"Y㓝P_"ld&"¨!,rUU' %jQWlŔ7.c Ll'&eT=:#kաaS<#fN1m+OtNV,q
/B<ȿ`FDaE0,m bQCB,s[MӯEMj}x\O!Rܥ) ĽCX[4jzYM4 Uˤүʼ'Z'R atSL<_WN+FpFN|Q]~wf uh&Igr}}:j^*RHWKq#D4j'ڑt2XJU=K= at@Kjh>nqX@'S[U5S})=tQh`OS85;ƭCF"@V`\)1<Sb0[ҲJYs=7n
Qsr?ye`iB q fyYRcZs[\,si50lrF:NyuTs-uD)UkAVK
ꏃ؎
1iE) 'v[4c凎xePAz**g$
!Eu!2c 6³@uW/gırǵ""`
mJm/>VIP2yN[CHZNp"B;s@aw%d)/PZ1zFDajrZ r@Bf
9_ךԏ,[^zDB_JXJeײH
h
=;jW)B_낡LoK5SQxpv7K_8{xXÇrP|]V[-Ztjv wq2yQs%@9x(ax
xɑ A.v8t&gCu@=l#)e^4y"a>C/wmN6m*6>v::7VSX8_kGY6KaYSc`%фկ,2S+^>3AaxK1-9nL}Z>
VoeP`v0iͽ=EVy:|ԁN9~>&QA W6opieRy.2 }G*s|P6ؠlVw_FNk.tK$i
0q/u2E,xv¯Nge0[.U/Ǡ`,lBUĪ3t99~TsF<Ua_kADh]1gYVoO/ծU=Z|UC_R#f?:6kޣqLJړqkc< |