Compare commits

...

9 commits

Author SHA1 Message Date
Asanka Herath 2d238f7d3b
Merge b5c5a8bd76 into 4e483f5d4a 2024-04-21 10:15:49 +09:00
hugoreleaser 4e483f5d4a releaser: Bump versions for release of 0.125.2
[ci skip]
2024-04-20 15:29:44 +00:00
Bjørn Erik Pedersen 06d248910c Only add root sections to the section pages menu
Fixes #12399
2024-04-20 17:23:33 +02:00
Bjørn Erik Pedersen 004b694390 Fix partial rebuilds for SCSS fetched with GetMatch and similar
Fixes #12395
2024-04-20 15:09:12 +02:00
Joe Mooring da6112fc65 commands: Add gen chromastyles --lineNumbersTableStyle flag
For symmetry, also rename --linesStyle to --lineNumbersInlineStyle.

Closes #12393
2024-04-20 12:25:28 +02:00
Bjørn Erik Pedersen faf9fedc3d
resources/images: Fix TestColorLuminance on s390x 2024-04-19 11:21:50 +02:00
Joe Mooring 11aa893198
commands: Provide examples for chromastyles flags
Closes #12387
2024-04-18 12:16:36 -07:00
Asanka Herath b5c5a8bd76 Add configuration options for pandoc
Current options are:

  markup:
    pandoc:
      filters:
        - list
        - of
        - filters
      extensions:
        - list
        - of
        - extensions
      extraArgs:
        - --extra-arguments
        - --one-per-line

Generalize some Pandoc options.

Support configuring a bibliography in markup config

Anonymous Update

[pandoc] Allow page parameters to override site parameters.

This allows specifying things like this in the page frontmatter:

    ---
    title: Something
    bibliography:
      source: mybibliography.bib
    pandoc:
      filter:
        - make-diagrams.lua
    ...

These options are local to the page. Specifying the same under `markup`
in the site configuration applies those settings to all pages.

Paths (filters, bibliography, citation style) are resolved relative to
the page, site, and the `static` folder.

[pandoc] Support metadata

Support specifying Pandoc metadata in the site configuration and page
configuration using the following syntax:

Site (in `config.yaml`):

    ```yaml
    markup:
        pandoc:
                metadata:
                        link-citations: true
    ```

Or in frontmatter:

    ```yaml
    ---
    pandoc:
        metadata:
                link-citations: true
    ...
    ```

[pandoc] Simplify path management.

No need for any fancy path lookup gymnastics. `pandoc`'s
`--resource-path` option does the legwork of locating resources on
multiple directories.

[pandoc] Don't use x != "" to denote failure.
2023-09-13 15:24:21 -04:00
Asanka Herath c9e679075f Add configuration options for pandoc
Current options are:

  markup:
    pandoc:
      filters:
        - list
        - of
        - filters
      extensions:
        - list
        - of
        - extensions
      extraArgs:
        - --extra-arguments
        - --one-per-line

Generalize some Pandoc options.

Support configuring a bibliography in markup config

Anonymous Update

[pandoc] Allow page parameters to override site parameters.

This allows specifying things like this in the page frontmatter:

    ---
    title: Something
    bibliography:
      source: mybibliography.bib
    pandoc:
      filter:
        - make-diagrams.lua
    ...

These options are local to the page. Specifying the same under `markup`
in the site configuration applies those settings to all pages.

Paths (filters, bibliography, citation style) are resolved relative to
the page, site, and the `static` folder.

[pandoc] Support metadata

Support specifying Pandoc metadata in the site configuration and page
configuration using the following syntax:

Site (in `config.yaml`):

    ```yaml
    markup:
        pandoc:
                metadata:
                        link-citations: true
    ```

Or in frontmatter:

    ```yaml
    ---
    pandoc:
        metadata:
                link-citations: true
    ...
    ```

[pandoc] Simplify path management.

No need for any fancy path lookup gymnastics. `pandoc`'s
`--resource-path` option does the legwork of locating resources on
multiple directories.

[pandoc] Don't use x != "" to denote failure.
2023-09-13 12:54:33 -04:00
17 changed files with 441 additions and 74 deletions

View file

@ -140,16 +140,25 @@ func (c *Cache) DrainEvictedIdentities() []identity.Identity {
}
// ClearMatching clears all partition for which the predicate returns true.
func (c *Cache) ClearMatching(predicate func(k, v any) bool) {
func (c *Cache) ClearMatching(predicatePartition func(k string, p PartitionManager) bool, predicateValue func(k, v any) bool) {
if predicatePartition == nil {
predicatePartition = func(k string, p PartitionManager) bool { return true }
}
if predicateValue == nil {
panic("nil predicateValue")
}
g := rungroup.Run[PartitionManager](context.Background(), rungroup.Config[PartitionManager]{
NumWorkers: len(c.partitions),
Handle: func(ctx context.Context, partition PartitionManager) error {
partition.clearMatching(predicate)
partition.clearMatching(predicateValue)
return nil
},
})
for _, p := range c.partitions {
for k, p := range c.partitions {
if !predicatePartition(k, p) {
continue
}
g.Enqueue(p)
}
@ -356,6 +365,7 @@ func GetOrCreatePartition[K comparable, V any](c *Cache, name string, opts Optio
trace: c.opts.Log.Logger().WithLevel(logg.LevelTrace).WithField("partition", name),
opts: opts,
}
c.partitions[name] = partition
return partition

View file

@ -156,7 +156,7 @@ func TestClear(t *testing.T) {
cache = newTestCache(t)
cache.ClearMatching(func(k, v any) bool {
cache.ClearMatching(nil, func(k, v any) bool {
return k.(string) == "clearOnRebuild"
})

View file

@ -128,6 +128,7 @@ type rootCommand struct {
verbose bool
debug bool
quiet bool
devMode bool // Hidden flag.
renderToMemory bool
@ -423,29 +424,33 @@ func (r *rootCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
func (r *rootCommand) createLogger(running bool) (loggers.Logger, error) {
level := logg.LevelWarn
if r.logLevel != "" {
switch strings.ToLower(r.logLevel) {
case "debug":
level = logg.LevelDebug
case "info":
level = logg.LevelInfo
case "warn", "warning":
level = logg.LevelWarn
case "error":
level = logg.LevelError
default:
return nil, fmt.Errorf("invalid log level: %q, must be one of debug, warn, info or error", r.logLevel)
}
if r.devMode {
level = logg.LevelTrace
} else {
if r.verbose {
hugo.Deprecate("--verbose", "use --logLevel info", "v0.114.0")
hugo.Deprecate("--verbose", "use --logLevel info", "v0.114.0")
level = logg.LevelInfo
}
if r.logLevel != "" {
switch strings.ToLower(r.logLevel) {
case "debug":
level = logg.LevelDebug
case "info":
level = logg.LevelInfo
case "warn", "warning":
level = logg.LevelWarn
case "error":
level = logg.LevelError
default:
return nil, fmt.Errorf("invalid log level: %q, must be one of debug, warn, info or error", r.logLevel)
}
} else {
if r.verbose {
hugo.Deprecate("--verbose", "use --logLevel info", "v0.114.0")
hugo.Deprecate("--verbose", "use --logLevel info", "v0.114.0")
level = logg.LevelInfo
}
if r.debug {
hugo.Deprecate("--debug", "use --logLevel debug", "v0.114.0")
level = logg.LevelDebug
if r.debug {
hugo.Deprecate("--debug", "use --logLevel debug", "v0.114.0")
level = logg.LevelDebug
}
}
}
@ -505,10 +510,13 @@ Complete documentation is available at https://gohugo.io/.`
cmd.PersistentFlags().BoolVarP(&r.verbose, "verbose", "v", false, "verbose output")
cmd.PersistentFlags().BoolVarP(&r.debug, "debug", "", false, "debug output")
cmd.PersistentFlags().BoolVarP(&r.devMode, "devMode", "", false, "only used for internal testing, flag hidden.")
cmd.PersistentFlags().StringVar(&r.logLevel, "logLevel", "", "log level (debug|info|warn|error)")
_ = cmd.RegisterFlagCompletionFunc("logLevel", cobra.FixedCompletions([]string{"debug", "info", "warn", "error"}, cobra.ShellCompDirectiveNoFileComp))
cmd.Flags().BoolVarP(&r.buildWatch, "watch", "w", false, "watch filesystem for changes and recreate as needed")
cmd.PersistentFlags().MarkHidden("devMode")
// Configure local flags
applyLocalFlagsBuild(cmd, r)

View file

@ -45,9 +45,10 @@ func newGenCommand() *genCommand {
genmandir string
// Chroma flags.
style string
highlightStyle string
linesStyle string
style string
highlightStyle string
lineNumbersInlineStyle string
lineNumbersTableStyle string
)
newChromaStyles := func() simplecobra.Commander {
@ -63,8 +64,11 @@ See https://xyproto.github.io/splash/docs/all.html for a preview of the availabl
if highlightStyle != "" {
builder.Add(chroma.LineHighlight, highlightStyle)
}
if linesStyle != "" {
builder.Add(chroma.LineNumbers, linesStyle)
if lineNumbersInlineStyle != "" {
builder.Add(chroma.LineNumbers, lineNumbersInlineStyle)
}
if lineNumbersTableStyle != "" {
builder.Add(chroma.LineNumbersTable, lineNumbersTableStyle)
}
style, err := builder.Build()
if err != nil {
@ -78,10 +82,12 @@ See https://xyproto.github.io/splash/docs/all.html for a preview of the availabl
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.PersistentFlags().StringVar(&style, "style", "friendly", "highlighter style (see https://xyproto.github.io/splash/docs/)")
_ = cmd.RegisterFlagCompletionFunc("style", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&highlightStyle, "highlightStyle", "", "style used for highlighting lines (see https://github.com/alecthomas/chroma)")
cmd.PersistentFlags().StringVar(&highlightStyle, "highlightStyle", "", `foreground and background colors for highlighted lines, e.g. --highlightStyle "#fff000 bg:#000fff"`)
_ = cmd.RegisterFlagCompletionFunc("highlightStyle", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&linesStyle, "linesStyle", "", "style used for line numbers (see https://github.com/alecthomas/chroma)")
_ = cmd.RegisterFlagCompletionFunc("linesStyle", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&lineNumbersInlineStyle, "lineNumbersInlineStyle", "", `foreground and background colors for inline line numbers, e.g. --lineNumbersInlineStyle "#fff000 bg:#000fff"`)
_ = cmd.RegisterFlagCompletionFunc("lineNumbersInlineStyle", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&lineNumbersTableStyle, "lineNumbersTableStyle", "", `foreground and background colors for table line numbers, e.g. --lineNumbersTableStyle "#fff000 bg:#000fff"`)
_ = cmd.RegisterFlagCompletionFunc("lineNumbersTableStyle", cobra.NoFileCompletions)
},
}
}

View file

@ -17,7 +17,7 @@ package hugo
// This should be the only one.
var CurrentVersion = Version{
Major: 0,
Minor: 126,
PatchLevel: 0,
Suffix: "-DEV",
Minor: 125,
PatchLevel: 2,
Suffix: "",
}

View file

@ -20,10 +20,11 @@ hugo gen chromastyles [flags] [args]
### Options
```
-h, --help help for chromastyles
--highlightStyle string style used for highlighting lines (see https://github.com/alecthomas/chroma)
--linesStyle string style used for line numbers (see https://github.com/alecthomas/chroma)
--style string highlighter style (see https://xyproto.github.io/splash/docs/) (default "friendly")
-h, --help help for chromastyles
--highlightStyle string foreground and background colors for highlighted lines, e.g. --highlightStyle "#fff000 bg:#000fff"
--lineNumbersInlineStyle string foreground and background colors for inline line numbers, e.g. --lineNumbersInlineStyle "#fff000 bg:#000fff"
--lineNumbersTableStyle string foreground and background colors for table line numbers, e.g. --lineNumbersTableStyle "#fff000 bg:#000fff"
--style string highlighter style (see https://xyproto.github.io/splash/docs/) (default "friendly")
```
### Options inherited from parent commands

View file

@ -16,6 +16,7 @@ package hqt
import (
"errors"
"fmt"
"math"
"reflect"
"strings"
@ -38,6 +39,11 @@ var IsSameType qt.Checker = &typeChecker{
argNames: []string{"got", "want"},
}
// IsSameFloat64 asserts that two float64 values are equal within a small delta.
var IsSameFloat64 = qt.CmpEquals(cmp.Comparer(func(a, b float64) bool {
return math.Abs(a-b) < 0.0001
}))
type argNames []string
func (a argNames) ArgNames() []string {

View file

@ -1084,7 +1084,7 @@ func (h *HugoSites) resolveAndClearStateForIdentities(
return b
}
h.MemCache.ClearMatching(shouldDelete)
h.MemCache.ClearMatching(nil, shouldDelete)
return ll, nil
}); err != nil {

View file

@ -23,6 +23,7 @@ import (
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/bep/logg"
@ -46,6 +47,7 @@ import (
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/page/siteidentities"
"github.com/gohugoio/hugo/resources/postpub"
"github.com/gohugoio/hugo/resources/resource"
"github.com/spf13/afero"
@ -758,15 +760,45 @@ func (h *HugoSites) processPartial(ctx context.Context, l logg.LevelLogger, conf
}
}
case files.ComponentFolderAssets:
logger.Println("Asset changed", pathInfo.Path())
p := pathInfo.Path()
logger.Println("Asset changed", p)
var matches []any
var mu sync.Mutex
h.MemCache.ClearMatching(
func(k string, pm dynacache.PartitionManager) bool {
// Avoid going through everything.
return strings.HasPrefix(k, "/res")
},
func(k, v any) bool {
if strings.Contains(k.(string), p) {
mu.Lock()
defer mu.Unlock()
switch vv := v.(type) {
case resource.Resources:
// GetMatch/Match.
for _, r := range vv {
matches = append(matches, r)
}
return true
default:
matches = append(matches, vv)
return true
}
}
return false
})
var hasID bool
r, _ := h.ResourceSpec.ResourceCache.Get(context.Background(), dynacache.CleanKey(pathInfo.Base()))
identity.WalkIdentitiesShallow(r, func(level int, rid identity.Identity) bool {
hasID = true
changes = append(changes, rid)
return false
})
for _, r := range matches {
identity.WalkIdentitiesShallow(r, func(level int, rid identity.Identity) bool {
hasID = true
changes = append(changes, rid)
return false
})
}
if !hasID {
changes = append(changes, pathInfo)
}

View file

@ -676,3 +676,37 @@ menu: main
b.AssertFileContent("public/fr/index.html", `<a href="/fr/p1/">p1</a>`)
b.AssertLogNotContains("WARN")
}
func TestSectionPagesIssue12399(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['rss','sitemap','taxonomy','term']
capitalizeListTitles = false
pluralizeListTitles = false
sectionPagesMenu = 'main'
-- content/p1.md --
---
title: p1
---
-- content/s1/p2.md --
---
title: p2
menus: main
---
-- content/s1/p3.md --
---
title: p3
---
-- layouts/_default/list.html --
{{ range site.Menus.main }}<a href="{{ .URL }}">{{ .Name }}</a>{{ end }}
-- layouts/_default/single.html --
{{ .Title }}
`
b := Test(t, files)
b.AssertFileExists("public/index.html", true)
b.AssertFileContent("public/index.html", `<a href="/s1/p2/">p2</a><a href="/s1/">s1</a>`)
}

View file

@ -659,7 +659,7 @@ func (s *Site) assembleMenus() error {
if sectionPagesMenu != "" {
if err := s.pageMap.forEachPage(pagePredicates.ShouldListGlobal, func(p *pageState) (bool, error) {
if p.IsHome() || !p.m.shouldBeCheckedForMenuDefinitions() {
if p.Kind() != kinds.KindSection || !p.m.shouldBeCheckedForMenuDefinitions() {
return false, nil
}

View file

@ -0,0 +1,25 @@
// 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 bibliography
type Config struct {
// File containing bibliography. E.g. 'my-doc.bibtex'. By default assumed
// to be in BibTex format.
Source string
// Path to .csl file describing citation file.
CitationStyle string
}
var Default Config

View file

@ -17,8 +17,10 @@ import (
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/markup/asciidocext/asciidocext_config"
"github.com/gohugoio/hugo/markup/bibliography"
"github.com/gohugoio/hugo/markup/goldmark/goldmark_config"
"github.com/gohugoio/hugo/markup/highlight"
"github.com/gohugoio/hugo/markup/pandoc/pandoc_config"
"github.com/gohugoio/hugo/markup/tableofcontents"
"github.com/mitchellh/mapstructure"
)
@ -33,12 +35,16 @@ type Config struct {
// Table of contents configuration
TableOfContents tableofcontents.Config
Bibliography bibliography.Config
// Configuration for the Goldmark markdown engine.
Goldmark goldmark_config.Config
// Configuration for the Asciidoc external markdown engine.
AsciidocExt asciidocext_config.Config
// Configuration for Pandoc external markdown engine.
Pandoc pandoc_config.Config
}
func Decode(cfg config.Provider) (conf Config, err error) {
@ -102,7 +108,9 @@ var Default = Config{
TableOfContents: tableofcontents.DefaultConfig,
Highlight: highlight.DefaultConfig,
Bibliography: bibliography.Default,
Goldmark: goldmark_config.Default,
Pandoc: pandoc_config.Default,
AsciidocExt: asciidocext_config.Default,
}

View file

@ -15,14 +15,34 @@
package pandoc
import (
"errors"
"strings"
"github.com/gohugoio/hugo/common/hexec"
"github.com/gohugoio/hugo/htesting"
"github.com/gohugoio/hugo/identity"
"github.com/mitchellh/mapstructure"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/markup/bibliography"
"github.com/gohugoio/hugo/markup/converter"
"github.com/gohugoio/hugo/markup/internal"
"github.com/gohugoio/hugo/markup/pandoc/pandoc_config"
"path"
)
type paramer interface {
Param(interface{}) (interface{}, error)
}
type searchPaths struct {
Paths []string
}
func (s *searchPaths) AsResourcePath() string {
return strings.Join(s.Paths, ":")
}
// Provider is the package entry point.
var Provider converter.ProviderProvider = provider{}
@ -31,19 +51,19 @@ type provider struct{}
func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) {
return converter.NewProvider("pandoc", func(ctx converter.DocumentContext) (converter.Converter, error) {
return &pandocConverter{
ctx: ctx,
cfg: cfg,
docCtx: ctx,
cfg: cfg,
}, nil
}), nil
}
type pandocConverter struct {
ctx converter.DocumentContext
cfg converter.ProviderConfig
docCtx converter.DocumentContext
cfg converter.ProviderConfig
}
func (c *pandocConverter) Convert(ctx converter.RenderContext) (converter.ResultRender, error) {
b, err := c.getPandocContent(ctx.Src, c.ctx)
b, err := c.getPandocContent(ctx.Src)
if err != nil {
return nil, err
}
@ -55,30 +75,50 @@ func (c *pandocConverter) Supports(feature identity.Identity) bool {
}
// getPandocContent calls pandoc as an external helper to convert pandoc markdown to HTML.
func (c *pandocConverter) getPandocContent(src []byte, ctx converter.DocumentContext) ([]byte, error) {
logger := c.cfg.Logger
binaryName := getPandocBinaryName()
if binaryName == "" {
logger.Println("pandoc not found in $PATH: Please install.\n",
" Leaving pandoc content unrendered.")
return src, nil
func (c *pandocConverter) getPandocContent(src []byte) ([]byte, error) {
pandocPath, pandocFound := getPandocBinaryName()
if !pandocFound {
return nil, errors.New("pandoc not found in $PATH: Please install.")
}
args := []string{"--mathjax"}
return internal.ExternallyRenderContent(c.cfg, ctx, src, binaryName, args)
var pandocConfig pandoc_config.Config = c.cfg.MarkupConfig().Pandoc
var bibConfig bibliography.Config = c.cfg.MarkupConfig().Bibliography
if pageParameters, ok := c.docCtx.Document.(paramer); ok {
if bibParam, err := pageParameters.Param("bibliography"); err == nil {
mapstructure.WeakDecode(bibParam, &bibConfig)
}
if pandocParam, err := pageParameters.Param("pandoc"); err == nil {
mapstructure.WeakDecode(pandocParam, &pandocConfig)
}
}
arguments := pandocConfig.AsPandocArguments()
if bibConfig.Source != "" {
arguments = append(arguments, "--citeproc", "--bibliography", bibConfig.Source)
if bibConfig.CitationStyle != "" {
arguments = append(arguments, "--csl", bibConfig.CitationStyle)
}
}
resourcePath := strings.Join([]string{path.Dir(c.docCtx.Filename), "static", "."}, ":")
arguments = append(arguments, "--resource-path", resourcePath)
renderedContent, _ := internal.ExternallyRenderContent(c.cfg, c.docCtx, src, pandocPath, arguments)
return renderedContent, nil
}
const pandocBinary = "pandoc"
func getPandocBinaryName() string {
if hexec.InPath(pandocBinary) {
return pandocBinary
}
return ""
func getPandocBinaryName() (string, bool) {
return pandocBinary, hexec.InPath(pandocBinary)
}
// Supports returns whether Pandoc is installed on this computer.
func Supports() bool {
hasBin := getPandocBinaryName() != ""
_, hasBin := getPandocBinaryName()
if htesting.SupportsAll() {
if !hasBin {
panic("pandoc not installed")

View file

@ -0,0 +1,165 @@
package pandoc_config
import (
"fmt"
"strings"
)
// Config contains configuration settings for Pandoc.
type Config struct {
// Input format. Use the 'Extensions' field to specify extensions thereof.
// Only specify the bare format here. Defaults to 'markdown' if empty. Invoke
// "pandoc --list-input-formats" to see the list of supported input formats
// including various Markdown dialects.
InputFormat string
// If true, the output format is HTML (i.e. "--to=html"). Otherwise the output
// format is HTML5 (i.e. "--to=html5").
UseLegacyHtml bool
// Equivalent to specifying "--mathjax". For compatibility, this option is
// always true if none of the other math options are used.
// See https://pandoc.org/MANUAL.html#math-rendering-in-html
UseMathjax bool
// Equivalent to specifying "--mathml".
// See https://pandoc.org/MANUAL.html#math-rendering-in-html
UseMathml bool
// Equivalent to specifying "--webtex".
// See https://pandoc.org/MANUAL.html#math-rendering-in-html. Uses the default
// Webtex rendering URL.
UseWebtex bool
// Equivalent to specifying "--katex".
// See https://pandoc.org/MANUAL.html#math-rendering-in-html
UseKatex bool
// List of filters to use. These translate to '--filter=' or '--lua-filter'
// arguments to the pandoc invocation. The order of elements in `Filters`
// is preserved when constructing the `pandoc` commandline.
//
// Use the prefix 'lua:' or the suffix '.lua' to indicate Lua filters.
Filters []string
// List of Pandoc Markdown extensions to use. No need to include default
// extensions. Specifying ["foo", "bar"] is equivalent to specifying
// --from=markdown+foo+bar on the pandoc commandline.
Extensions []string
// List of input format extensions to use. Specifying ["foo", "bar"] is
// equivalent to specifying --from=markdown+foo+bar on the pandoc commandline
// assuming InputFormat is "markdown".
InputExtensions []string
// List of output format extensions to use. Specifying ["foo", "bar"] is
// equivalent to specifying --to=html5+foo+bar on the pandoc commandline,
// assuming UseLegacyHTML is false. Invoke "pandoc --list-extensions=html5" to
// or "pandoc --list-extensions=html5" to see the list of extensions that can
// be specified here.
OutputExtensions []string
// Metadata. The dictionary keys and values are handled in the obvious way.
Metadata map[string]interface{}
// Extra commandline options passed to the pandoc invocation. These options
// are appended to the commandline after the format and filter options.
// Arguments are passed in literally. Hence must have the "--" or "-" prefix
// where applicable.
ExtraArgs []string
}
var Default = Config{
InputFormat: "markdown",
UseLegacyHtml: false,
UseMathjax: true,
}
func (c *Config) getInputArg() string {
var b strings.Builder
b.WriteString("--from=")
if len(c.InputFormat) > 0 {
b.WriteString(c.InputFormat)
} else {
b.WriteString("markdown")
}
for _, extension := range c.InputExtensions {
b.WriteString("+")
b.WriteString(extension)
}
return b.String()
}
func (c *Config) getOutputArg() string {
var b strings.Builder
b.WriteString("--to=")
if c.UseLegacyHtml {
b.WriteString("html")
} else {
b.WriteString("html5")
}
for _, extension := range c.OutputExtensions {
b.WriteString("+")
b.WriteString(extension)
}
return b.String()
}
func (c *Config) getMathRenderingArg() string {
switch {
case c.UseMathml:
return "--mathml"
case c.UseWebtex:
return "--webtex"
case c.UseKatex:
return "--katex"
default:
return "--mathjax"
}
}
func (c *Config) getMetadataArgs() []string {
var args []string
for k, iv := range c.Metadata {
var v string
if sv, ok := iv.(string); ok {
v = sv
} else if sv, ok := iv.(fmt.Stringer); ok {
v = sv.String()
} else {
v = fmt.Sprintf("%v", iv)
}
args = append(args, fmt.Sprintf("-M%s=%s", k, v))
}
return args
}
func (c *Config) getFilterArgs() []string {
var args []string
for _, filterPath := range c.Filters {
if strings.HasPrefix(filterPath, "lua:") || strings.HasSuffix(filterPath, ".lua") {
args = append(args, fmt.Sprintf("--lua-filter=%s", strings.TrimPrefix(filterPath, "lua:")))
} else {
args = append(args, fmt.Sprintf("--filter=%s", filterPath))
}
}
return args
}
// AsPandocArguments returns a list of strings that can be used as arguments to
// a "pandoc" invocation. All the settings contained in Config are represented
// in the returned list of arguments.
func (c *Config) AsPandocArguments() []string {
args := []string{
c.getInputArg(),
c.getOutputArg(),
c.getMathRenderingArg()}
args = append(args, c.getMetadataArgs()...)
args = append(args, c.getFilterArgs()...)
args = append(args, c.ExtraArgs...)
return args
}

View file

@ -18,6 +18,7 @@ import (
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/htesting/hqt"
)
func TestHexStringToColor(t *testing.T) {
@ -119,8 +120,8 @@ func TestReplaceColorInPalette(t *testing.T) {
func TestColorLuminance(t *testing.T) {
c := qt.New(t)
c.Assert(hexStringToColor("#000000").Luminance(), qt.Equals, 0.0)
c.Assert(hexStringToColor("#768a9a").Luminance(), qt.Equals, 0.24361603589088263)
c.Assert(hexStringToColor("#d5bc9f").Luminance(), qt.Equals, 0.5261577672685374)
c.Assert(hexStringToColor("#ffffff").Luminance(), qt.Equals, 1.0)
c.Assert(hexStringToColor("#000000").Luminance(), hqt.IsSameFloat64, 0.0)
c.Assert(hexStringToColor("#768a9a").Luminance(), hqt.IsSameFloat64, 0.24361603589088263)
c.Assert(hexStringToColor("#d5bc9f").Luminance(), hqt.IsSameFloat64, 0.5261577672685374)
c.Assert(hexStringToColor("#ffffff").Luminance(), hqt.IsSameFloat64, 1.0)
}

View file

@ -327,3 +327,34 @@ Styles: {{ $r.RelPermalink }}
b.AssertFileContent("public/index.html", "Styles: /scss/main.css")
}
func TestRebuildAssetGetMatch(t *testing.T) {
t.Parallel()
if !scss.Supports() {
t.Skip()
}
files := `
-- assets/scss/main.scss --
b {
color: red;
}
-- layouts/index.html --
{{ $r := resources.GetMatch "scss/main.scss" | toCSS }}
T1: {{ $r.Content }}
`
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
NeedsOsFS: true,
Running: true,
}).Build()
b.AssertFileContent("public/index.html", `color: red`)
b.EditFiles("assets/scss/main.scss", `b { color: blue; }`).Build()
b.AssertFileContent("public/index.html", `color: blue`)
}