hugo/resources/resource_transformers/postcss/postcss.go
Bjørn Erik Pedersen 7285e74090
all: Rework page store, add a dynacache, improve partial rebuilds, and some general spring cleaning
There are some breaking changes in this commit, see #11455.

Closes #11455
Closes #11549

This fixes a set of bugs (see issue list) and it is also paying some technical debt accumulated over the years. We now build with Staticcheck enabled in the CI build.

The performance should be about the same as before for regular sized Hugo sites, but it should perform and scale much better to larger data sets, as objects that uses lots of memory (e.g. rendered Markdown, big JSON files read into maps with transform.Unmarshal etc.) will now get automatically garbage collected if needed. Performance on partial rebuilds when running the server in fast render mode should be the same, but the change detection should be much more accurate.

A list of the notable new features:

* A new dependency tracker that covers (almost) all of Hugo's API and is used to do fine grained partial rebuilds when running the server.
* A new and simpler tree document store which allows fast lookups and prefix-walking in all dimensions (e.g. language) concurrently.
* You can now configure an upper memory limit allowing for much larger data sets and/or running on lower specced PCs.
We have lifted the "no resources in sub folders" restriction for branch bundles (e.g. sections).
Memory Limit
* Hugos will, by default, set aside a quarter of the total system memory, but you can set this via the OS environment variable HUGO_MEMORYLIMIT (in gigabytes). This is backed by a partitioned LRU cache used throughout Hugo. A cache that gets dynamically resized in low memory situations, allowing Go's Garbage Collector to free the memory.

New Dependency Tracker: Hugo has had a rule based coarse grained approach to server rebuilds that has worked mostly pretty well, but there have been some surprises (e.g. stale content). This is now revamped with a new dependency tracker that can quickly calculate the delta given a changed resource (e.g. a content file, template, JS file etc.). This handles transitive relations, e.g. $page -> js.Build -> JS import, or $page1.Content -> render hook -> site.GetPage -> $page2.Title, or $page1.Content -> shortcode -> partial -> site.RegularPages -> $page2.Content -> shortcode ..., and should also handle changes to aggregated values (e.g. site.Lastmod) effectively.

This covers all of Hugo's API with 2 known exceptions (a list that may not be fully exhaustive):

Changes to files loaded with template func os.ReadFile may not be handled correctly. We recommend loading resources with resources.Get
Changes to Hugo objects (e.g. Page) passed in the template context to lang.Translate may not be detected correctly. We recommend having simple i18n templates without too much data context passed in other than simple types such as strings and numbers.
Note that the cachebuster configuration (when A changes then rebuild B) works well with the above, but we recommend that you revise that configuration, as it in most situations should not be needed. One example where it is still needed is with TailwindCSS and using changes to hugo_stats.json to trigger new CSS rebuilds.

Document Store: Previously, a little simplified, we split the document store (where we store pages and resources) in a tree per language. This worked pretty well, but the structure made some operations harder than they needed to be. We have now restructured it into one Radix tree for all languages. Internally the language is considered to be a dimension of that tree, and the tree can be viewed in all dimensions concurrently. This makes some operations re. language simpler (e.g. finding translations is just a slice range), but the idea is that it should also be relatively inexpensive to add more dimensions if needed (e.g. role).

Fixes #10169
Fixes #10364
Fixes #10482
Fixes #10630
Fixes #10656
Fixes #10694
Fixes #10918
Fixes #11262
Fixes #11439
Fixes #11453
Fixes #11457
Fixes #11466
Fixes #11540
Fixes #11551
Fixes #11556
Fixes #11654
Fixes #11661
Fixes #11663
Fixes #11664
Fixes #11669
Fixes #11671
Fixes #11807
Fixes #11808
Fixes #11809
Fixes #11815
Fixes #11840
Fixes #11853
Fixes #11860
Fixes #11883
Fixes #11904
Fixes #7388
Fixes #7425
Fixes #7436
Fixes #7544
Fixes #7882
Fixes #7960
Fixes #8255
Fixes #8307
Fixes #8863
Fixes #8927
Fixes #9192
Fixes #9324
2024-01-27 16:28:14 +01:00

443 lines
11 KiB
Go

// Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package postcss
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/gohugoio/hugo/common/collections"
"github.com/gohugoio/hugo/common/hexec"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/common/text"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/common/hugo"
"github.com/gohugoio/hugo/resources/internal"
"github.com/spf13/afero"
"github.com/spf13/cast"
"github.com/mitchellh/mapstructure"
"github.com/gohugoio/hugo/common/herrors"
"github.com/gohugoio/hugo/resources"
"github.com/gohugoio/hugo/resources/resource"
)
const importIdentifier = "@import"
var (
cssSyntaxErrorRe = regexp.MustCompile(`> (\d+) \|`)
shouldImportRe = regexp.MustCompile(`^@import ["'].*["'];?\s*(/\*.*\*/)?$`)
)
// New creates a new Client with the given specification.
func New(rs *resources.Spec) *Client {
return &Client{rs: rs}
}
func decodeOptions(m map[string]any) (opts Options, err error) {
if m == nil {
return
}
err = mapstructure.WeakDecode(m, &opts)
if !opts.NoMap {
// There was for a long time a discrepancy between documentation and
// implementation for the noMap property, so we need to support both
// camel and snake case.
opts.NoMap = cast.ToBool(m["no-map"])
}
return
}
// Client is the client used to do PostCSS transformations.
type Client struct {
rs *resources.Spec
}
// Process transforms the given Resource with the PostCSS processor.
func (c *Client) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) {
return res.Transform(&postcssTransformation{rs: c.rs, optionsm: options})
}
// Some of the options from https://github.com/postcss/postcss-cli
type Options struct {
// Set a custom path to look for a config file.
Config string
NoMap bool // Disable the default inline sourcemaps
// Enable inlining of @import statements.
// Does so recursively, but currently once only per file;
// that is, it's not possible to import the same file in
// different scopes (root, media query...)
// Note that this import routine does not care about the CSS spec,
// so you can have @import anywhere in the file.
InlineImports bool
// When InlineImports is enabled, we fail the build if an import cannot be resolved.
// You can enable this to allow the build to continue and leave the import statement in place.
// Note that the inline importer does not process url location or imports with media queries,
// so those will be left as-is even without enabling this option.
SkipInlineImportsNotFound bool
// Options for when not using a config file
Use string // List of postcss plugins to use
Parser string // Custom postcss parser
Stringifier string // Custom postcss stringifier
Syntax string // Custom postcss syntax
}
func (opts Options) toArgs() []string {
var args []string
if opts.NoMap {
args = append(args, "--no-map")
}
if opts.Use != "" {
args = append(args, "--use")
args = append(args, strings.Fields(opts.Use)...)
}
if opts.Parser != "" {
args = append(args, "--parser", opts.Parser)
}
if opts.Stringifier != "" {
args = append(args, "--stringifier", opts.Stringifier)
}
if opts.Syntax != "" {
args = append(args, "--syntax", opts.Syntax)
}
return args
}
type postcssTransformation struct {
optionsm map[string]any
rs *resources.Spec
}
func (t *postcssTransformation) Key() internal.ResourceTransformationKey {
return internal.NewResourceTransformationKey("postcss", t.optionsm)
}
// Transform shells out to postcss-cli to do the heavy lifting.
// For this to work, you need some additional tools. To install them globally:
// npm install -g postcss-cli
// npm install -g autoprefixer
func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error {
const binaryName = "postcss"
infol := t.rs.Logger.InfoCommand(binaryName)
infow := loggers.LevelLoggerToWriter(infol)
ex := t.rs.ExecHelper
var configFile string
var options Options
if t.optionsm != nil {
var err error
options, err = decodeOptions(t.optionsm)
if err != nil {
return err
}
}
if options.Config != "" {
configFile = options.Config
} else {
configFile = "postcss.config.js"
}
configFile = filepath.Clean(configFile)
// We need an absolute filename to the config file.
if !filepath.IsAbs(configFile) {
configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile)
if configFile == "" && options.Config != "" {
// Only fail if the user specified config file is not found.
return fmt.Errorf("postcss config %q not found", options.Config)
}
}
var cmdArgs []any
if configFile != "" {
infol.Logf("use config file %q", configFile)
cmdArgs = []any{"--config", configFile}
}
if optArgs := options.toArgs(); len(optArgs) > 0 {
cmdArgs = append(cmdArgs, collections.StringSliceToInterfaceSlice(optArgs)...)
}
var errBuf bytes.Buffer
stderr := io.MultiWriter(infow, &errBuf)
cmdArgs = append(cmdArgs, hexec.WithStderr(stderr))
cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To))
cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs)))
cmd, err := ex.Npx(binaryName, cmdArgs...)
if err != nil {
if hexec.IsNotFound(err) {
// This may be on a CI server etc. Will fall back to pre-built assets.
return &herrors.FeatureNotAvailableError{Cause: err}
}
return err
}
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
src := ctx.From
imp := newImportResolver(
ctx.From,
ctx.InPath,
options,
t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager,
)
if options.InlineImports {
var err error
src, err = imp.resolve()
if err != nil {
return err
}
}
go func() {
defer stdin.Close()
io.Copy(stdin, src)
}()
err = cmd.Run()
if err != nil {
if hexec.IsNotFound(err) {
return &herrors.FeatureNotAvailableError{
Cause: err,
}
}
return imp.toFileError(errBuf.String())
}
return nil
}
type fileOffset struct {
Filename string
Offset int
}
type importResolver struct {
r io.Reader
inPath string
opts Options
contentSeen map[string]bool
dependencyManager identity.Manager
linemap map[int]fileOffset
fs afero.Fs
logger loggers.Logger
}
func newImportResolver(r io.Reader, inPath string, opts Options, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver {
return &importResolver{
r: r,
dependencyManager: dependencyManager,
inPath: inPath,
fs: fs, logger: logger,
linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool),
opts: opts,
}
}
func (imp *importResolver) contentHash(filename string) ([]byte, string) {
b, err := afero.ReadFile(imp.fs, filename)
if err != nil {
return nil, ""
}
h := sha256.New()
h.Write(b)
return b, hex.EncodeToString(h.Sum(nil))
}
func (imp *importResolver) importRecursive(
lineNum int,
content string,
inPath string,
) (int, string, error) {
basePath := path.Dir(inPath)
var replacements []string
lines := strings.Split(content, "\n")
trackLine := func(i, offset int, line string) {
// TODO(bep) this is not very efficient.
imp.linemap[i+lineNum] = fileOffset{Filename: inPath, Offset: offset}
}
i := 0
for offset, line := range lines {
i++
lineTrimmed := strings.TrimSpace(line)
column := strings.Index(line, lineTrimmed)
line = lineTrimmed
if !imp.shouldImport(line) {
trackLine(i, offset, line)
} else {
path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';")
filename := filepath.Join(basePath, path)
imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))
importContent, hash := imp.contentHash(filename)
if importContent == nil {
if imp.opts.SkipInlineImportsNotFound {
trackLine(i, offset, line)
continue
}
pos := text.Position{
Filename: inPath,
LineNumber: offset + 1,
ColumnNumber: column + 1,
}
return 0, "", herrors.NewFileErrorFromFileInPos(fmt.Errorf("failed to resolve CSS @import \"%s\"", filename), pos, imp.fs, nil)
}
i--
if imp.contentSeen[hash] {
i++
// Just replace the line with an empty string.
replacements = append(replacements, []string{line, ""}...)
trackLine(i, offset, "IMPORT")
continue
}
imp.contentSeen[hash] = true
// Handle recursive imports.
l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename))
if err != nil {
return 0, "", err
}
trackLine(i, offset, line)
i += l
importContent = []byte(nested)
replacements = append(replacements, []string{line, string(importContent)}...)
}
}
if len(replacements) > 0 {
repl := strings.NewReplacer(replacements...)
content = repl.Replace(content)
}
return i, content, nil
}
func (imp *importResolver) resolve() (io.Reader, error) {
content, err := io.ReadAll(imp.r)
if err != nil {
return nil, err
}
contents := string(content)
_, newContent, err := imp.importRecursive(0, contents, imp.inPath)
if err != nil {
return nil, err
}
return strings.NewReader(newContent), nil
}
// See https://www.w3schools.com/cssref/pr_import_rule.asp
// We currently only support simple file imports, no urls, no media queries.
// So this is OK:
//
// @import "navigation.css";
//
// This is not:
//
// @import url("navigation.css");
// @import "mobstyle.css" screen and (max-width: 768px);
func (imp *importResolver) shouldImport(s string) bool {
if !strings.HasPrefix(s, importIdentifier) {
return false
}
if strings.Contains(s, "url(") {
return false
}
return shouldImportRe.MatchString(s)
}
func (imp *importResolver) toFileError(output string) error {
inErr := errors.New(output)
match := cssSyntaxErrorRe.FindStringSubmatch(output)
if match == nil {
return inErr
}
lineNum, err := strconv.Atoi(match[1])
if err != nil {
return inErr
}
file, ok := imp.linemap[lineNum]
if !ok {
return inErr
}
fi, err := imp.fs.Stat(file.Filename)
if err != nil {
return inErr
}
meta := fi.(hugofs.FileMetaInfo).Meta()
realFilename := meta.Filename
f, err := meta.Open()
if err != nil {
return inErr
}
defer f.Close()
ferr := herrors.NewFileErrorFromName(inErr, realFilename)
pos := ferr.Position()
pos.LineNumber = file.Offset + 1
return ferr.UpdatePosition(pos).UpdateContent(f, nil)
// return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher)
}