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
2023-12-24 13:11:05 -05:00
// Copyright 2024 The Hugo Authors. All rights reserved.
2017-02-04 22:20:06 -05:00
//
// 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 (
2023-01-04 12:24:36 -05:00
"context"
2018-10-03 08:58:09 -04:00
"errors"
2022-04-26 13:57:04 -04:00
"fmt"
2023-02-18 17:43:26 -05:00
"io"
2023-06-05 03:53:53 -04:00
"log"
2020-12-02 07:23:25 -05:00
"os"
2023-01-04 12:24:36 -05:00
"os/signal"
2020-12-02 07:23:25 -05:00
"path/filepath"
2024-02-02 10:00:48 -05:00
"runtime"
2023-06-12 09:50:53 -04:00
"strings"
Add Hugo Modules
This commit implements Hugo Modules.
This is a broad subject, but some keywords include:
* A new `module` configuration section where you can import almost anything. You can configure both your own file mounts nd the file mounts of the modules you import. This is the new recommended way of configuring what you earlier put in `configDir`, `staticDir` etc. And it also allows you to mount folders in non-Hugo-projects, e.g. the `SCSS` folder in the Bootstrap GitHub project.
* A module consists of a set of mounts to the standard 7 component types in Hugo: `static`, `content`, `layouts`, `data`, `assets`, `i18n`, and `archetypes`. Yes, Theme Components can now include content, which should be very useful, especially in bigger multilingual projects.
* Modules not in your local file cache will be downloaded automatically and even "hot replaced" while the server is running.
* Hugo Modules supports and encourages semver versioned modules, and uses the minimal version selection algorithm to resolve versions.
* A new set of CLI commands are provided to manage all of this: `hugo mod init`, `hugo mod get`, `hugo mod graph`, `hugo mod tidy`, and `hugo mod vendor`.
All of the above is backed by Go Modules.
Fixes #5973
Fixes #5996
Fixes #6010
Fixes #5911
Fixes #5940
Fixes #6074
Fixes #6082
Fixes #6092
2019-05-03 03:16:58 -04:00
"sync"
2023-01-04 12:24:36 -05:00
"sync/atomic"
"syscall"
2020-12-02 07:23:25 -05:00
"time"
Add Hugo Modules
This commit implements Hugo Modules.
This is a broad subject, but some keywords include:
* A new `module` configuration section where you can import almost anything. You can configure both your own file mounts nd the file mounts of the modules you import. This is the new recommended way of configuring what you earlier put in `configDir`, `staticDir` etc. And it also allows you to mount folders in non-Hugo-projects, e.g. the `SCSS` folder in the Bootstrap GitHub project.
* A module consists of a set of mounts to the standard 7 component types in Hugo: `static`, `content`, `layouts`, `data`, `assets`, `i18n`, and `archetypes`. Yes, Theme Components can now include content, which should be very useful, especially in bigger multilingual projects.
* Modules not in your local file cache will be downloaded automatically and even "hot replaced" while the server is running.
* Hugo Modules supports and encourages semver versioned modules, and uses the minimal version selection algorithm to resolve versions.
* A new set of CLI commands are provided to manage all of this: `hugo mod init`, `hugo mod get`, `hugo mod graph`, `hugo mod tidy`, and `hugo mod vendor`.
All of the above is backed by Go Modules.
Fixes #5973
Fixes #5996
Fixes #6010
Fixes #5911
Fixes #5940
Fixes #6074
Fixes #6082
Fixes #6092
2019-05-03 03:16:58 -04:00
2023-05-18 13:32:49 -04:00
"go.uber.org/automaxprocs/maxprocs"
2023-07-03 20:53:49 -04:00
"github.com/bep/clocks"
2023-01-04 12:24:36 -05:00
"github.com/bep/lazycache"
2023-06-16 02:17:42 -04:00
"github.com/bep/logg"
2023-01-04 12:24:36 -05:00
"github.com/bep/overlayfs"
"github.com/bep/simplecobra"
Add Hugo Modules
This commit implements Hugo Modules.
This is a broad subject, but some keywords include:
* A new `module` configuration section where you can import almost anything. You can configure both your own file mounts nd the file mounts of the modules you import. This is the new recommended way of configuring what you earlier put in `configDir`, `staticDir` etc. And it also allows you to mount folders in non-Hugo-projects, e.g. the `SCSS` folder in the Bootstrap GitHub project.
* A module consists of a set of mounts to the standard 7 component types in Hugo: `static`, `content`, `layouts`, `data`, `assets`, `i18n`, and `archetypes`. Yes, Theme Components can now include content, which should be very useful, especially in bigger multilingual projects.
* Modules not in your local file cache will be downloaded automatically and even "hot replaced" while the server is running.
* Hugo Modules supports and encourages semver versioned modules, and uses the minimal version selection algorithm to resolve versions.
* A new set of CLI commands are provided to manage all of this: `hugo mod init`, `hugo mod get`, `hugo mod graph`, `hugo mod tidy`, and `hugo mod vendor`.
All of the above is backed by Go Modules.
Fixes #5973
Fixes #5996
Fixes #6010
Fixes #5911
Fixes #5940
Fixes #6074
Fixes #6082
Fixes #6092
2019-05-03 03:16:58 -04:00
2023-01-04 12:24:36 -05:00
"github.com/gohugoio/hugo/common/hstrings"
2022-04-26 13:57:04 -04:00
"github.com/gohugoio/hugo/common/htime"
2023-10-26 03:38:13 -04:00
"github.com/gohugoio/hugo/common/hugo"
2018-10-03 08:58:09 -04:00
"github.com/gohugoio/hugo/common/loggers"
2023-01-04 12:24:36 -05:00
"github.com/gohugoio/hugo/common/paths"
2018-04-07 05:27:22 -04:00
"github.com/gohugoio/hugo/config"
2023-01-04 12:24:36 -05:00
"github.com/gohugoio/hugo/config/allconfig"
2017-06-13 12:42:45 -04:00
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
2023-01-04 12:24:36 -05:00
"github.com/gohugoio/hugo/hugolib"
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
"github.com/gohugoio/hugo/resources/kinds"
2023-01-04 12:24:36 -05:00
"github.com/spf13/afero"
"github.com/spf13/cobra"
2017-02-04 22:20:06 -05:00
)
2023-10-26 03:38:13 -04:00
var errHelp = errors . New ( "help requested" )
Add Hugo Modules
This commit implements Hugo Modules.
This is a broad subject, but some keywords include:
* A new `module` configuration section where you can import almost anything. You can configure both your own file mounts nd the file mounts of the modules you import. This is the new recommended way of configuring what you earlier put in `configDir`, `staticDir` etc. And it also allows you to mount folders in non-Hugo-projects, e.g. the `SCSS` folder in the Bootstrap GitHub project.
* A module consists of a set of mounts to the standard 7 component types in Hugo: `static`, `content`, `layouts`, `data`, `assets`, `i18n`, and `archetypes`. Yes, Theme Components can now include content, which should be very useful, especially in bigger multilingual projects.
* Modules not in your local file cache will be downloaded automatically and even "hot replaced" while the server is running.
* Hugo Modules supports and encourages semver versioned modules, and uses the minimal version selection algorithm to resolve versions.
* A new set of CLI commands are provided to manage all of this: `hugo mod init`, `hugo mod get`, `hugo mod graph`, `hugo mod tidy`, and `hugo mod vendor`.
All of the above is backed by Go Modules.
Fixes #5973
Fixes #5996
Fixes #6010
Fixes #5911
Fixes #5940
Fixes #6074
Fixes #6082
Fixes #6092
2019-05-03 03:16:58 -04:00
2023-01-04 12:24:36 -05:00
// Execute executes a command.
func Execute ( args [ ] string ) error {
2023-05-18 13:32:49 -04:00
// Default GOMAXPROCS to be CPU limit aware, still respecting GOMAXPROCS env.
maxprocs . Set ( )
2023-01-04 12:24:36 -05:00
x , err := newExec ( )
if err != nil {
return err
}
args = mapLegacyArgs ( args )
cd , err := x . Execute ( context . Background ( ) , args )
if err != nil {
if err == errHelp {
cd . CobraCommand . Help ( )
fmt . Println ( )
return nil
}
if simplecobra . IsCommandError ( err ) {
// Print the help, but also return the error to fail the command.
cd . CobraCommand . Help ( )
fmt . Println ( )
}
}
return err
2018-10-03 08:58:09 -04:00
}
2023-01-04 12:24:36 -05:00
type commonConfig struct {
2023-05-19 06:54:42 -04:00
mu * sync . Mutex
2023-01-04 12:24:36 -05:00
configs * allconfig . Configs
cfg config . Provider
fs * hugofs . Fs
2022-03-18 03:54:44 -04:00
}
2023-01-04 12:24:36 -05:00
// This is the root command.
type rootCommand struct {
Printf func ( format string , v ... interface { } )
Println func ( a ... interface { } )
Out io . Writer
logger loggers . Logger
// The main cache busting key for the caches below.
configVersionID atomic . Int32
// Some, but not all commands need access to these.
// Some needs more than one, so keep them in a small cache.
commonConfigs * lazycache . Cache [ int32 , * commonConfig ]
hugoSites * lazycache . Cache [ int32 , * hugolib . HugoSites ]
commands [ ] simplecobra . Commander
// Flags
2023-05-17 06:45:51 -04:00
source string
buildWatch bool
environment string
2023-01-04 12:24:36 -05:00
2023-05-17 06:45:51 -04:00
// Common build flags.
2023-06-30 02:47:11 -04:00
baseURL string
gc bool
poll string
forceSyncStatic bool
2023-05-17 06:45:51 -04:00
// Profile flags (for debugging of performance problems)
cpuprofile string
memprofile string
mutexprofile string
traceprofile string
printm bool
2023-05-17 12:45:23 -04:00
2023-06-12 09:50:53 -04:00
logLevel string
verbose bool
debug bool
quiet bool
2024-04-20 05:05:35 -04:00
devMode bool // Hidden flag.
2023-06-12 09:50:53 -04:00
2023-05-17 12:45:23 -04:00
renderToMemory bool
cfgFile string
cfgDir string
2023-05-17 06:45:51 -04:00
}
2023-06-21 17:18:38 -04:00
func ( r * rootCommand ) isVerbose ( ) bool {
return r . logger . Level ( ) <= logg . LevelInfo
}
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) Build ( cd * simplecobra . Commandeer , bcfg hugolib . BuildCfg , cfg config . Provider ) ( * hugolib . HugoSites , error ) {
h , err := r . Hugo ( cfg )
if err != nil {
return nil , err
}
if err := h . Build ( bcfg ) ; err != nil {
return nil , err
2022-05-15 15:01:36 -04:00
}
2023-01-04 12:24:36 -05:00
return h , nil
2022-05-15 15:01:36 -04:00
}
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) Commands ( ) [ ] simplecobra . Commander {
return r . commands
2018-10-03 08:58:09 -04:00
}
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) ConfigFromConfig ( key int32 , oldConf * commonConfig ) ( * commonConfig , error ) {
cc , _ , err := r . commonConfigs . GetOrCreate ( key , func ( key int32 ) ( * commonConfig , error ) {
fs := oldConf . fs
configs , err := allconfig . LoadConfig (
allconfig . ConfigSourceDescriptor {
Flags : oldConf . cfg ,
Fs : fs . Source ,
Filename : r . cfgFile ,
ConfigDir : r . cfgDir ,
2023-05-21 08:25:16 -04:00
Logger : r . logger ,
2023-01-04 12:24:36 -05:00
Environment : r . environment ,
} ,
)
if err != nil {
return nil , err
}
2018-10-03 08:58:09 -04:00
2023-01-04 12:24:36 -05:00
if ! configs . Base . C . Clock . IsZero ( ) {
// TODO(bep) find a better place for this.
2023-07-03 20:53:49 -04:00
htime . Clock = clocks . Start ( configs . Base . C . Clock )
2023-01-04 12:24:36 -05:00
}
return & commonConfig {
2023-05-19 06:54:42 -04:00
mu : oldConf . mu ,
2023-01-04 12:24:36 -05:00
configs : configs ,
cfg : oldConf . cfg ,
fs : fs ,
} , nil
} )
2018-10-03 08:58:09 -04:00
2023-01-04 12:24:36 -05:00
return cc , err
2017-02-04 22:20:06 -05:00
}
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) ConfigFromProvider ( key int32 , cfg config . Provider ) ( * commonConfig , error ) {
if cfg == nil {
panic ( "cfg must be set" )
2017-02-04 22:20:06 -05:00
}
2023-01-04 12:24:36 -05:00
cc , _ , err := r . commonConfigs . GetOrCreate ( key , func ( key int32 ) ( * commonConfig , error ) {
var dir string
if r . source != "" {
dir , _ = filepath . Abs ( r . source )
} else {
dir , _ = os . Getwd ( )
}
2017-02-04 22:20:06 -05:00
2023-01-04 12:24:36 -05:00
if cfg == nil {
cfg = config . New ( )
}
2023-05-18 07:29:33 -04:00
2023-01-04 12:24:36 -05:00
if ! cfg . IsSet ( "workingDir" ) {
cfg . Set ( "workingDir" , dir )
2023-05-18 07:29:33 -04:00
} else {
2023-10-26 03:38:13 -04:00
if err := os . MkdirAll ( cfg . GetString ( "workingDir" ) , 0 o777 ) ; err != nil {
2023-05-18 07:29:33 -04:00
return nil , fmt . Errorf ( "failed to create workingDir: %w" , err )
}
}
// Load the config first to allow publishDir to be configured in config file.
configs , err := allconfig . LoadConfig (
allconfig . ConfigSourceDescriptor {
Flags : cfg ,
Fs : hugofs . Os ,
Filename : r . cfgFile ,
ConfigDir : r . cfgDir ,
Environment : r . environment ,
2023-05-21 08:25:16 -04:00
Logger : r . logger ,
2023-05-18 07:29:33 -04:00
} ,
)
if err != nil {
return nil , err
2023-01-04 12:24:36 -05:00
}
2023-05-18 07:29:33 -04:00
base := configs . Base
cfg . Set ( "publishDir" , base . PublishDir )
cfg . Set ( "publishDirStatic" , base . PublishDir )
cfg . Set ( "publishDirDynamic" , base . PublishDir )
:sparkles: Implement Page bundling and image handling
This commit is not the smallest in Hugo's history.
Some hightlights include:
* Page bundles (for complete articles, keeping images and content together etc.).
* Bundled images can be processed in as many versions/sizes as you need with the three methods `Resize`, `Fill` and `Fit`.
* Processed images are cached inside `resources/_gen/images` (default) in your project.
* Symbolic links (both files and dirs) are now allowed anywhere inside /content
* A new table based build summary
* The "Total in nn ms" now reports the total including the handling of the files inside /static. So if it now reports more than you're used to, it is just **more real** and probably faster than before (see below).
A site building benchmark run compared to `v0.31.1` shows that this should be slightly faster and use less memory:
```bash
▶ ./benchSite.sh "TOML,num_langs=.*,num_root_sections=5,num_pages=(500|1000),tags_per_page=5,shortcodes,render"
benchmark old ns/op new ns/op delta
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 101785785 78067944 -23.30%
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 185481057 149159919 -19.58%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 103149918 85679409 -16.94%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 203515478 169208775 -16.86%
benchmark old allocs new allocs delta
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 532464 391539 -26.47%
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 1056549 772702 -26.87%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 555974 406630 -26.86%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 1086545 789922 -27.30%
benchmark old bytes new bytes delta
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 53243246 43598155 -18.12%
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 105811617 86087116 -18.64%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 54558852 44545097 -18.35%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 106903858 86978413 -18.64%
```
Fixes #3651
Closes #3158
Fixes #1014
Closes #2021
Fixes #1240
Updates #3757
2017-07-24 03:00:23 -04:00
2023-01-04 12:24:36 -05:00
renderStaticToDisk := cfg . GetBool ( "renderStaticToDisk" )
2017-03-25 14:48:28 -04:00
2023-01-04 12:24:36 -05:00
sourceFs := hugofs . Os
2023-05-22 13:11:12 -04:00
var destinationFs afero . Fs
2024-02-05 03:44:28 -05:00
if cfg . GetBool ( "renderToMemory" ) {
2023-05-22 13:11:12 -04:00
destinationFs = afero . NewMemMapFs ( )
2023-01-04 12:24:36 -05:00
if renderStaticToDisk {
// Hybrid, render dynamic content to Root.
cfg . Set ( "publishDirDynamic" , "/" )
} else {
// Rendering to memoryFS, publish to Root regardless of publishDir.
cfg . Set ( "publishDirDynamic" , "/" )
cfg . Set ( "publishDirStatic" , "/" )
}
2024-02-05 03:44:28 -05:00
} else {
destinationFs = hugofs . Os
2023-01-04 12:24:36 -05:00
}
2022-04-26 13:57:04 -04:00
2023-05-22 13:11:12 -04:00
fs := hugofs . NewFromSourceAndDestination ( sourceFs , destinationFs , cfg )
2023-01-04 12:24:36 -05:00
if renderStaticToDisk {
dynamicFs := fs . PublishDir
publishDirStatic := cfg . GetString ( "publishDirStatic" )
workingDir := cfg . GetString ( "workingDir" )
absPublishDirStatic := paths . AbsPathify ( workingDir , publishDirStatic )
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
2023-12-24 13:11:05 -05:00
staticFs := hugofs . NewBasePathFs ( afero . NewOsFs ( ) , absPublishDirStatic )
2023-01-04 12:24:36 -05:00
// Serve from both the static and dynamic fs,
// the first will take priority.
// THis is a read-only filesystem,
// we do all the writes to
// fs.Destination and fs.DestinationStatic.
fs . PublishDirServer = overlayfs . New (
overlayfs . Options {
Fss : [ ] afero . Fs {
dynamicFs ,
staticFs ,
} ,
} ,
)
fs . PublishDirStatic = staticFs
2022-05-07 08:10:32 -04:00
2023-01-04 12:24:36 -05:00
}
2022-04-26 13:57:04 -04:00
2023-01-04 12:24:36 -05:00
if ! base . C . Clock . IsZero ( ) {
// TODO(bep) find a better place for this.
2023-07-03 20:53:49 -04:00
htime . Clock = clocks . Start ( configs . Base . C . Clock )
2023-01-04 12:24:36 -05:00
}
2018-03-18 06:07:24 -04:00
2023-06-30 02:47:11 -04:00
if base . PrintPathWarnings {
2023-01-04 12:24:36 -05:00
// Note that we only care about the "dynamic creates" here,
// so skip the static fs.
fs . PublishDir = hugofs . NewCreateCountingFs ( fs . PublishDir )
}
commonConfig := & commonConfig {
2023-05-19 06:54:42 -04:00
mu : & sync . Mutex { } ,
2023-01-04 12:24:36 -05:00
configs : configs ,
cfg : cfg ,
fs : fs ,
}
return commonConfig , nil
} )
2018-03-18 06:07:24 -04:00
2023-01-04 12:24:36 -05:00
return cc , err
Add Hugo Piper with SCSS support and much more
Before this commit, you would have to use page bundles to do image processing etc. in Hugo.
This commit adds
* A new `/assets` top-level project or theme dir (configurable via `assetDir`)
* A new template func, `resources.Get` which can be used to "get a resource" that can be further processed.
This means that you can now do this in your templates (or shortcodes):
```bash
{{ $sunset := (resources.Get "images/sunset.jpg").Fill "300x200" }}
```
This also adds a new `extended` build tag that enables powerful SCSS/SASS support with source maps. To compile this from source, you will also need a C compiler installed:
```
HUGO_BUILD_TAGS=extended mage install
```
Note that you can use output of the SCSS processing later in a non-SCSSS-enabled Hugo.
The `SCSS` processor is a _Resource transformation step_ and it can be chained with the many others in a pipeline:
```bash
{{ $css := resources.Get "styles.scss" | resources.ToCSS | resources.PostCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
The transformation funcs above have aliases, so it can be shortened to:
```bash
{{ $css := resources.Get "styles.scss" | toCSS | postCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
A quick tip would be to avoid the fingerprinting part, and possibly also the not-superfast `postCSS` when you're doing development, as it allows Hugo to be smarter about the rebuilding.
Documentation will follow, but have a look at the demo repo in https://github.com/bep/hugo-sass-test
New functions to create `Resource` objects:
* `resources.Get` (see above)
* `resources.FromString`: Create a Resource from a string.
New `Resource` transformation funcs:
* `resources.ToCSS`: Compile `SCSS` or `SASS` into `CSS`.
* `resources.PostCSS`: Process your CSS with PostCSS. Config file support (project or theme or passed as an option).
* `resources.Minify`: Currently supports `css`, `js`, `json`, `html`, `svg`, `xml`.
* `resources.Fingerprint`: Creates a fingerprinted version of the given Resource with Subresource Integrity..
* `resources.Concat`: Concatenates a list of Resource objects. Think of this as a poor man's bundler.
* `resources.ExecuteAsTemplate`: Parses and executes the given Resource and data context (e.g. .Site) as a Go template.
Fixes #4381
Fixes #4903
Fixes #4858
2018-02-20 04:02:14 -05:00
}
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) HugFromConfig ( conf * commonConfig ) ( * hugolib . HugoSites , error ) {
h , _ , err := r . hugoSites . GetOrCreate ( r . configVersionID . Load ( ) , func ( key int32 ) ( * hugolib . HugoSites , error ) {
2023-06-16 02:17:42 -04:00
depsCfg := deps . DepsCfg { Configs : conf . configs , Fs : conf . fs , LogOut : r . logger . Out ( ) , LogLevel : r . logger . Level ( ) }
2023-01-04 12:24:36 -05:00
return hugolib . NewHugoSites ( depsCfg )
} )
return h , err
Add Hugo Piper with SCSS support and much more
Before this commit, you would have to use page bundles to do image processing etc. in Hugo.
This commit adds
* A new `/assets` top-level project or theme dir (configurable via `assetDir`)
* A new template func, `resources.Get` which can be used to "get a resource" that can be further processed.
This means that you can now do this in your templates (or shortcodes):
```bash
{{ $sunset := (resources.Get "images/sunset.jpg").Fill "300x200" }}
```
This also adds a new `extended` build tag that enables powerful SCSS/SASS support with source maps. To compile this from source, you will also need a C compiler installed:
```
HUGO_BUILD_TAGS=extended mage install
```
Note that you can use output of the SCSS processing later in a non-SCSSS-enabled Hugo.
The `SCSS` processor is a _Resource transformation step_ and it can be chained with the many others in a pipeline:
```bash
{{ $css := resources.Get "styles.scss" | resources.ToCSS | resources.PostCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
The transformation funcs above have aliases, so it can be shortened to:
```bash
{{ $css := resources.Get "styles.scss" | toCSS | postCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
A quick tip would be to avoid the fingerprinting part, and possibly also the not-superfast `postCSS` when you're doing development, as it allows Hugo to be smarter about the rebuilding.
Documentation will follow, but have a look at the demo repo in https://github.com/bep/hugo-sass-test
New functions to create `Resource` objects:
* `resources.Get` (see above)
* `resources.FromString`: Create a Resource from a string.
New `Resource` transformation funcs:
* `resources.ToCSS`: Compile `SCSS` or `SASS` into `CSS`.
* `resources.PostCSS`: Process your CSS with PostCSS. Config file support (project or theme or passed as an option).
* `resources.Minify`: Currently supports `css`, `js`, `json`, `html`, `svg`, `xml`.
* `resources.Fingerprint`: Creates a fingerprinted version of the given Resource with Subresource Integrity..
* `resources.Concat`: Concatenates a list of Resource objects. Think of this as a poor man's bundler.
* `resources.ExecuteAsTemplate`: Parses and executes the given Resource and data context (e.g. .Site) as a Go template.
Fixes #4381
Fixes #4903
Fixes #4858
2018-02-20 04:02:14 -05:00
}
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) Hugo ( cfg config . Provider ) ( * hugolib . HugoSites , error ) {
h , _ , err := r . hugoSites . GetOrCreate ( r . configVersionID . Load ( ) , func ( key int32 ) ( * hugolib . HugoSites , error ) {
conf , err := r . ConfigFromProvider ( key , cfg )
if err != nil {
return nil , err
Add Hugo Piper with SCSS support and much more
Before this commit, you would have to use page bundles to do image processing etc. in Hugo.
This commit adds
* A new `/assets` top-level project or theme dir (configurable via `assetDir`)
* A new template func, `resources.Get` which can be used to "get a resource" that can be further processed.
This means that you can now do this in your templates (or shortcodes):
```bash
{{ $sunset := (resources.Get "images/sunset.jpg").Fill "300x200" }}
```
This also adds a new `extended` build tag that enables powerful SCSS/SASS support with source maps. To compile this from source, you will also need a C compiler installed:
```
HUGO_BUILD_TAGS=extended mage install
```
Note that you can use output of the SCSS processing later in a non-SCSSS-enabled Hugo.
The `SCSS` processor is a _Resource transformation step_ and it can be chained with the many others in a pipeline:
```bash
{{ $css := resources.Get "styles.scss" | resources.ToCSS | resources.PostCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
The transformation funcs above have aliases, so it can be shortened to:
```bash
{{ $css := resources.Get "styles.scss" | toCSS | postCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
A quick tip would be to avoid the fingerprinting part, and possibly also the not-superfast `postCSS` when you're doing development, as it allows Hugo to be smarter about the rebuilding.
Documentation will follow, but have a look at the demo repo in https://github.com/bep/hugo-sass-test
New functions to create `Resource` objects:
* `resources.Get` (see above)
* `resources.FromString`: Create a Resource from a string.
New `Resource` transformation funcs:
* `resources.ToCSS`: Compile `SCSS` or `SASS` into `CSS`.
* `resources.PostCSS`: Process your CSS with PostCSS. Config file support (project or theme or passed as an option).
* `resources.Minify`: Currently supports `css`, `js`, `json`, `html`, `svg`, `xml`.
* `resources.Fingerprint`: Creates a fingerprinted version of the given Resource with Subresource Integrity..
* `resources.Concat`: Concatenates a list of Resource objects. Think of this as a poor man's bundler.
* `resources.ExecuteAsTemplate`: Parses and executes the given Resource and data context (e.g. .Site) as a Go template.
Fixes #4381
Fixes #4903
Fixes #4858
2018-02-20 04:02:14 -05:00
}
2023-06-16 02:17:42 -04:00
depsCfg := deps . DepsCfg { Configs : conf . configs , Fs : conf . fs , LogOut : r . logger . Out ( ) , LogLevel : r . logger . Level ( ) }
2023-01-04 12:24:36 -05:00
return hugolib . NewHugoSites ( depsCfg )
} )
return h , err
Add Hugo Piper with SCSS support and much more
Before this commit, you would have to use page bundles to do image processing etc. in Hugo.
This commit adds
* A new `/assets` top-level project or theme dir (configurable via `assetDir`)
* A new template func, `resources.Get` which can be used to "get a resource" that can be further processed.
This means that you can now do this in your templates (or shortcodes):
```bash
{{ $sunset := (resources.Get "images/sunset.jpg").Fill "300x200" }}
```
This also adds a new `extended` build tag that enables powerful SCSS/SASS support with source maps. To compile this from source, you will also need a C compiler installed:
```
HUGO_BUILD_TAGS=extended mage install
```
Note that you can use output of the SCSS processing later in a non-SCSSS-enabled Hugo.
The `SCSS` processor is a _Resource transformation step_ and it can be chained with the many others in a pipeline:
```bash
{{ $css := resources.Get "styles.scss" | resources.ToCSS | resources.PostCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
The transformation funcs above have aliases, so it can be shortened to:
```bash
{{ $css := resources.Get "styles.scss" | toCSS | postCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
A quick tip would be to avoid the fingerprinting part, and possibly also the not-superfast `postCSS` when you're doing development, as it allows Hugo to be smarter about the rebuilding.
Documentation will follow, but have a look at the demo repo in https://github.com/bep/hugo-sass-test
New functions to create `Resource` objects:
* `resources.Get` (see above)
* `resources.FromString`: Create a Resource from a string.
New `Resource` transformation funcs:
* `resources.ToCSS`: Compile `SCSS` or `SASS` into `CSS`.
* `resources.PostCSS`: Process your CSS with PostCSS. Config file support (project or theme or passed as an option).
* `resources.Minify`: Currently supports `css`, `js`, `json`, `html`, `svg`, `xml`.
* `resources.Fingerprint`: Creates a fingerprinted version of the given Resource with Subresource Integrity..
* `resources.Concat`: Concatenates a list of Resource objects. Think of this as a poor man's bundler.
* `resources.ExecuteAsTemplate`: Parses and executes the given Resource and data context (e.g. .Site) as a Go template.
Fixes #4381
Fixes #4903
Fixes #4858
2018-02-20 04:02:14 -05:00
}
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) Name ( ) string {
return "hugo"
Add Hugo Piper with SCSS support and much more
Before this commit, you would have to use page bundles to do image processing etc. in Hugo.
This commit adds
* A new `/assets` top-level project or theme dir (configurable via `assetDir`)
* A new template func, `resources.Get` which can be used to "get a resource" that can be further processed.
This means that you can now do this in your templates (or shortcodes):
```bash
{{ $sunset := (resources.Get "images/sunset.jpg").Fill "300x200" }}
```
This also adds a new `extended` build tag that enables powerful SCSS/SASS support with source maps. To compile this from source, you will also need a C compiler installed:
```
HUGO_BUILD_TAGS=extended mage install
```
Note that you can use output of the SCSS processing later in a non-SCSSS-enabled Hugo.
The `SCSS` processor is a _Resource transformation step_ and it can be chained with the many others in a pipeline:
```bash
{{ $css := resources.Get "styles.scss" | resources.ToCSS | resources.PostCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
The transformation funcs above have aliases, so it can be shortened to:
```bash
{{ $css := resources.Get "styles.scss" | toCSS | postCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
A quick tip would be to avoid the fingerprinting part, and possibly also the not-superfast `postCSS` when you're doing development, as it allows Hugo to be smarter about the rebuilding.
Documentation will follow, but have a look at the demo repo in https://github.com/bep/hugo-sass-test
New functions to create `Resource` objects:
* `resources.Get` (see above)
* `resources.FromString`: Create a Resource from a string.
New `Resource` transformation funcs:
* `resources.ToCSS`: Compile `SCSS` or `SASS` into `CSS`.
* `resources.PostCSS`: Process your CSS with PostCSS. Config file support (project or theme or passed as an option).
* `resources.Minify`: Currently supports `css`, `js`, `json`, `html`, `svg`, `xml`.
* `resources.Fingerprint`: Creates a fingerprinted version of the given Resource with Subresource Integrity..
* `resources.Concat`: Concatenates a list of Resource objects. Think of this as a poor man's bundler.
* `resources.ExecuteAsTemplate`: Parses and executes the given Resource and data context (e.g. .Site) as a Go template.
Fixes #4381
Fixes #4903
Fixes #4858
2018-02-20 04:02:14 -05:00
}
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) Run ( ctx context . Context , cd * simplecobra . Commandeer , args [ ] string ) error {
2024-04-20 09:36:54 -04:00
b := newHugoBuilder ( r , nil )
2023-01-04 12:24:36 -05:00
if ! r . buildWatch {
2024-04-20 09:36:54 -04:00
defer b . postBuild ( "Total" , time . Now ( ) )
Add Hugo Piper with SCSS support and much more
Before this commit, you would have to use page bundles to do image processing etc. in Hugo.
This commit adds
* A new `/assets` top-level project or theme dir (configurable via `assetDir`)
* A new template func, `resources.Get` which can be used to "get a resource" that can be further processed.
This means that you can now do this in your templates (or shortcodes):
```bash
{{ $sunset := (resources.Get "images/sunset.jpg").Fill "300x200" }}
```
This also adds a new `extended` build tag that enables powerful SCSS/SASS support with source maps. To compile this from source, you will also need a C compiler installed:
```
HUGO_BUILD_TAGS=extended mage install
```
Note that you can use output of the SCSS processing later in a non-SCSSS-enabled Hugo.
The `SCSS` processor is a _Resource transformation step_ and it can be chained with the many others in a pipeline:
```bash
{{ $css := resources.Get "styles.scss" | resources.ToCSS | resources.PostCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
The transformation funcs above have aliases, so it can be shortened to:
```bash
{{ $css := resources.Get "styles.scss" | toCSS | postCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
A quick tip would be to avoid the fingerprinting part, and possibly also the not-superfast `postCSS` when you're doing development, as it allows Hugo to be smarter about the rebuilding.
Documentation will follow, but have a look at the demo repo in https://github.com/bep/hugo-sass-test
New functions to create `Resource` objects:
* `resources.Get` (see above)
* `resources.FromString`: Create a Resource from a string.
New `Resource` transformation funcs:
* `resources.ToCSS`: Compile `SCSS` or `SASS` into `CSS`.
* `resources.PostCSS`: Process your CSS with PostCSS. Config file support (project or theme or passed as an option).
* `resources.Minify`: Currently supports `css`, `js`, `json`, `html`, `svg`, `xml`.
* `resources.Fingerprint`: Creates a fingerprinted version of the given Resource with Subresource Integrity..
* `resources.Concat`: Concatenates a list of Resource objects. Think of this as a poor man's bundler.
* `resources.ExecuteAsTemplate`: Parses and executes the given Resource and data context (e.g. .Site) as a Go template.
Fixes #4381
Fixes #4903
Fixes #4858
2018-02-20 04:02:14 -05:00
}
2023-05-24 03:26:30 -04:00
if err := b . loadConfig ( cd , false ) ; err != nil {
2023-01-04 12:24:36 -05:00
return err
Add Hugo Piper with SCSS support and much more
Before this commit, you would have to use page bundles to do image processing etc. in Hugo.
This commit adds
* A new `/assets` top-level project or theme dir (configurable via `assetDir`)
* A new template func, `resources.Get` which can be used to "get a resource" that can be further processed.
This means that you can now do this in your templates (or shortcodes):
```bash
{{ $sunset := (resources.Get "images/sunset.jpg").Fill "300x200" }}
```
This also adds a new `extended` build tag that enables powerful SCSS/SASS support with source maps. To compile this from source, you will also need a C compiler installed:
```
HUGO_BUILD_TAGS=extended mage install
```
Note that you can use output of the SCSS processing later in a non-SCSSS-enabled Hugo.
The `SCSS` processor is a _Resource transformation step_ and it can be chained with the many others in a pipeline:
```bash
{{ $css := resources.Get "styles.scss" | resources.ToCSS | resources.PostCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
The transformation funcs above have aliases, so it can be shortened to:
```bash
{{ $css := resources.Get "styles.scss" | toCSS | postCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
A quick tip would be to avoid the fingerprinting part, and possibly also the not-superfast `postCSS` when you're doing development, as it allows Hugo to be smarter about the rebuilding.
Documentation will follow, but have a look at the demo repo in https://github.com/bep/hugo-sass-test
New functions to create `Resource` objects:
* `resources.Get` (see above)
* `resources.FromString`: Create a Resource from a string.
New `Resource` transformation funcs:
* `resources.ToCSS`: Compile `SCSS` or `SASS` into `CSS`.
* `resources.PostCSS`: Process your CSS with PostCSS. Config file support (project or theme or passed as an option).
* `resources.Minify`: Currently supports `css`, `js`, `json`, `html`, `svg`, `xml`.
* `resources.Fingerprint`: Creates a fingerprinted version of the given Resource with Subresource Integrity..
* `resources.Concat`: Concatenates a list of Resource objects. Think of this as a poor man's bundler.
* `resources.ExecuteAsTemplate`: Parses and executes the given Resource and data context (e.g. .Site) as a Go template.
Fixes #4381
Fixes #4903
Fixes #4858
2018-02-20 04:02:14 -05:00
}
2023-01-04 12:24:36 -05:00
err := func ( ) error {
if r . buildWatch {
defer r . timeTrack ( time . Now ( ) , "Built" )
}
2024-02-05 08:27:35 -05:00
err := b . build ( )
2024-02-02 10:00:48 -05:00
if err != nil {
return err
}
return nil
2023-01-04 12:24:36 -05:00
} ( )
if err != nil {
return err
Add Hugo Piper with SCSS support and much more
Before this commit, you would have to use page bundles to do image processing etc. in Hugo.
This commit adds
* A new `/assets` top-level project or theme dir (configurable via `assetDir`)
* A new template func, `resources.Get` which can be used to "get a resource" that can be further processed.
This means that you can now do this in your templates (or shortcodes):
```bash
{{ $sunset := (resources.Get "images/sunset.jpg").Fill "300x200" }}
```
This also adds a new `extended` build tag that enables powerful SCSS/SASS support with source maps. To compile this from source, you will also need a C compiler installed:
```
HUGO_BUILD_TAGS=extended mage install
```
Note that you can use output of the SCSS processing later in a non-SCSSS-enabled Hugo.
The `SCSS` processor is a _Resource transformation step_ and it can be chained with the many others in a pipeline:
```bash
{{ $css := resources.Get "styles.scss" | resources.ToCSS | resources.PostCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
The transformation funcs above have aliases, so it can be shortened to:
```bash
{{ $css := resources.Get "styles.scss" | toCSS | postCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
A quick tip would be to avoid the fingerprinting part, and possibly also the not-superfast `postCSS` when you're doing development, as it allows Hugo to be smarter about the rebuilding.
Documentation will follow, but have a look at the demo repo in https://github.com/bep/hugo-sass-test
New functions to create `Resource` objects:
* `resources.Get` (see above)
* `resources.FromString`: Create a Resource from a string.
New `Resource` transformation funcs:
* `resources.ToCSS`: Compile `SCSS` or `SASS` into `CSS`.
* `resources.PostCSS`: Process your CSS with PostCSS. Config file support (project or theme or passed as an option).
* `resources.Minify`: Currently supports `css`, `js`, `json`, `html`, `svg`, `xml`.
* `resources.Fingerprint`: Creates a fingerprinted version of the given Resource with Subresource Integrity..
* `resources.Concat`: Concatenates a list of Resource objects. Think of this as a poor man's bundler.
* `resources.ExecuteAsTemplate`: Parses and executes the given Resource and data context (e.g. .Site) as a Go template.
Fixes #4381
Fixes #4903
Fixes #4858
2018-02-20 04:02:14 -05:00
}
2023-01-04 12:24:36 -05:00
if ! r . buildWatch {
// Done.
return nil
2018-03-18 06:07:24 -04:00
}
2023-01-04 12:24:36 -05:00
watchDirs , err := b . getDirList ( )
if err != nil {
return err
2018-10-26 11:02:53 -04:00
}
2023-01-04 12:24:36 -05:00
watchGroups := helpers . ExtractAndGroupRootPaths ( watchDirs )
:sparkles: Implement Page bundling and image handling
This commit is not the smallest in Hugo's history.
Some hightlights include:
* Page bundles (for complete articles, keeping images and content together etc.).
* Bundled images can be processed in as many versions/sizes as you need with the three methods `Resize`, `Fill` and `Fit`.
* Processed images are cached inside `resources/_gen/images` (default) in your project.
* Symbolic links (both files and dirs) are now allowed anywhere inside /content
* A new table based build summary
* The "Total in nn ms" now reports the total including the handling of the files inside /static. So if it now reports more than you're used to, it is just **more real** and probably faster than before (see below).
A site building benchmark run compared to `v0.31.1` shows that this should be slightly faster and use less memory:
```bash
▶ ./benchSite.sh "TOML,num_langs=.*,num_root_sections=5,num_pages=(500|1000),tags_per_page=5,shortcodes,render"
benchmark old ns/op new ns/op delta
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 101785785 78067944 -23.30%
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 185481057 149159919 -19.58%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 103149918 85679409 -16.94%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 203515478 169208775 -16.86%
benchmark old allocs new allocs delta
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 532464 391539 -26.47%
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 1056549 772702 -26.87%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 555974 406630 -26.86%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 1086545 789922 -27.30%
benchmark old bytes new bytes delta
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 53243246 43598155 -18.12%
BenchmarkSiteBuilding/TOML,num_langs=1,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 105811617 86087116 -18.64%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=500,tags_per_page=5,shortcodes,render-4 54558852 44545097 -18.35%
BenchmarkSiteBuilding/TOML,num_langs=3,num_root_sections=5,num_pages=1000,tags_per_page=5,shortcodes,render-4 106903858 86978413 -18.64%
```
Fixes #3651
Closes #3158
Fixes #1014
Closes #2021
Fixes #1240
Updates #3757
2017-07-24 03:00:23 -04:00
2023-01-04 12:24:36 -05:00
for _ , group := range watchGroups {
r . Printf ( "Watching for changes in %s\n" , group )
2018-03-18 06:07:24 -04:00
}
2023-01-04 12:24:36 -05:00
watcher , err := b . newWatcher ( r . poll , watchDirs ... )
if err != nil {
return err
2018-03-18 06:07:24 -04:00
}
2023-01-04 12:24:36 -05:00
defer watcher . Close ( )
2018-11-15 03:28:02 -05:00
2023-01-04 12:24:36 -05:00
r . Println ( "Press Ctrl+C to stop" )
2018-03-18 06:07:24 -04:00
2023-01-04 12:24:36 -05:00
sigs := make ( chan os . Signal , 1 )
signal . Notify ( sigs , syscall . SIGINT , syscall . SIGTERM )
2018-03-18 06:07:24 -04:00
2023-01-04 12:24:36 -05:00
<- sigs
2018-03-18 06:07:24 -04:00
2023-01-04 12:24:36 -05:00
return nil
}
2018-04-07 05:27:22 -04:00
2023-05-17 12:45:23 -04:00
func ( r * rootCommand ) PreRun ( cd , runner * simplecobra . Commandeer ) error {
2023-01-04 12:24:36 -05:00
r . Out = os . Stdout
if r . quiet {
r . Out = io . Discard
}
2023-06-05 03:53:53 -04:00
// Used by mkcert (server).
log . SetOutput ( r . Out )
2023-01-04 12:24:36 -05:00
r . Printf = func ( format string , v ... interface { } ) {
if ! r . quiet {
fmt . Fprintf ( r . Out , format , v ... )
2021-08-31 06:08:11 -04:00
}
2018-03-18 06:07:24 -04:00
}
2023-01-04 12:24:36 -05:00
r . Println = func ( a ... interface { } ) {
if ! r . quiet {
fmt . Fprintln ( r . Out , a ... )
}
2022-04-26 13:57:04 -04:00
}
2023-01-04 12:24:36 -05:00
_ , running := runner . Command . ( * serverCommand )
var err error
r . logger , err = r . createLogger ( running )
2022-05-07 08:10:32 -04:00
if err != nil {
return err
2018-03-18 06:07:24 -04:00
}
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
2023-12-24 13:11:05 -05:00
r . commonConfigs = lazycache . New ( lazycache . Options [ int32 , * commonConfig ] { MaxEntries : 5 } )
// We don't want to keep stale HugoSites in memory longer than needed.
r . hugoSites = lazycache . New ( lazycache . Options [ int32 , * hugolib . HugoSites ] {
MaxEntries : 1 ,
OnEvict : func ( key int32 , value * hugolib . HugoSites ) {
value . Close ( )
2024-02-02 10:00:48 -05:00
runtime . GC ( )
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
2023-12-24 13:11:05 -05:00
} ,
} )
2018-10-03 08:58:09 -04:00
2023-01-04 12:24:36 -05:00
return nil
}
func ( r * rootCommand ) createLogger ( running bool ) ( loggers . Logger , error ) {
2023-06-16 02:17:42 -04:00
level := logg . LevelWarn
2018-03-18 06:07:24 -04:00
2024-04-20 05:05:35 -04:00
if r . devMode {
level = logg . LevelTrace
2023-06-16 02:17:42 -04:00
} else {
2024-04-20 05:05:35 -04:00
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
}
2023-06-16 02:17:42 -04:00
2024-04-20 05:05:35 -04:00
if r . debug {
hugo . Deprecate ( "--debug" , "use --logLevel debug" , "v0.114.0" )
level = logg . LevelDebug
}
2023-06-16 02:17:42 -04:00
}
2020-05-27 07:50:13 -04:00
}
2018-04-07 05:27:22 -04:00
2023-06-16 02:17:42 -04:00
optsLogger := loggers . Options {
2023-11-01 10:15:34 -04:00
DistinctLevel : logg . LevelWarn ,
Level : level ,
Stdout : r . Out ,
Stderr : r . Out ,
StoreErrors : running ,
2023-06-16 02:17:42 -04:00
}
return loggers . New ( optsLogger ) , nil
2023-01-04 12:24:36 -05:00
}
2018-03-18 06:07:24 -04:00
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) Reset ( ) {
r . logger . Reset ( )
2023-06-16 02:17:42 -04:00
loggers . Log ( ) . Reset ( )
2023-01-04 12:24:36 -05:00
}
2018-03-18 06:07:24 -04:00
2023-01-04 12:24:36 -05:00
// IsTestRun reports whether the command is running as a test.
func ( r * rootCommand ) IsTestRun ( ) bool {
return os . Getenv ( "HUGO_TESTRUN" ) != ""
}
2018-03-18 06:07:24 -04:00
2023-05-17 12:45:23 -04:00
func ( r * rootCommand ) Init ( cd * simplecobra . Commandeer ) error {
cmd := cd . CobraCommand
2023-01-04 12:24:36 -05:00
cmd . Use = "hugo [flags]"
cmd . Short = "hugo builds your site"
cmd . Long = ` hugo is the main command , used to build your Hugo site .
Hugo is a Fast and Flexible Static Site Generator
built with love by spf13 and friends in Go .
Complete documentation is available at https : //gohugo.io/.`
// Configure persistent flags
cmd . PersistentFlags ( ) . StringVarP ( & r . source , "source" , "s" , "" , "filesystem path to read files relative from" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . MarkFlagDirname ( "source" )
2023-05-17 06:45:51 -04:00
cmd . PersistentFlags ( ) . StringP ( "destination" , "d" , "" , "filesystem path to write files to" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . MarkFlagDirname ( "destination" )
2023-05-17 06:45:51 -04:00
2023-01-04 12:24:36 -05:00
cmd . PersistentFlags ( ) . StringVarP ( & r . environment , "environment" , "e" , "" , "build environment" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . RegisterFlagCompletionFunc ( "environment" , cobra . NoFileCompletions )
2023-01-04 12:24:36 -05:00
cmd . PersistentFlags ( ) . StringP ( "themesDir" , "" , "" , "filesystem path to themes directory" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . MarkFlagDirname ( "themesDir" )
2023-01-04 12:24:36 -05:00
cmd . PersistentFlags ( ) . StringP ( "ignoreVendorPaths" , "" , "" , "ignores any _vendor for module paths matching the given Glob pattern" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . RegisterFlagCompletionFunc ( "ignoreVendorPaths" , cobra . NoFileCompletions )
2023-01-04 12:24:36 -05:00
cmd . PersistentFlags ( ) . String ( "clock" , "" , "set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . RegisterFlagCompletionFunc ( "clock" , cobra . NoFileCompletions )
2023-01-04 12:24:36 -05:00
cmd . PersistentFlags ( ) . StringVar ( & r . cfgFile , "config" , "" , "config file (default is hugo.yaml|json|toml)" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . MarkFlagFilename ( "config" , config . ValidConfigFileExtensions ... )
2023-01-04 12:24:36 -05:00
cmd . PersistentFlags ( ) . StringVar ( & r . cfgDir , "configDir" , "config" , "config dir" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . MarkFlagDirname ( "configDir" )
2023-01-04 12:24:36 -05:00
cmd . PersistentFlags ( ) . BoolVar ( & r . quiet , "quiet" , false , "build in quiet mode" )
2024-02-05 03:44:28 -05:00
cmd . PersistentFlags ( ) . BoolVar ( & r . renderToMemory , "renderToMemory" , false , "render to memory (mostly useful when running the server)" )
2023-01-04 12:24:36 -05:00
cmd . PersistentFlags ( ) . BoolVarP ( & r . verbose , "verbose" , "v" , false , "verbose output" )
cmd . PersistentFlags ( ) . BoolVarP ( & r . debug , "debug" , "" , false , "debug output" )
2024-04-20 05:05:35 -04:00
cmd . PersistentFlags ( ) . BoolVarP ( & r . devMode , "devMode" , "" , false , "only used for internal testing, flag hidden." )
2023-06-12 09:50:53 -04:00
cmd . PersistentFlags ( ) . StringVar ( & r . logLevel , "logLevel" , "" , "log level (debug|info|warn|error)" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . RegisterFlagCompletionFunc ( "logLevel" , cobra . FixedCompletions ( [ ] string { "debug" , "info" , "warn" , "error" } , cobra . ShellCompDirectiveNoFileComp ) )
2023-01-04 12:24:36 -05:00
cmd . Flags ( ) . BoolVarP ( & r . buildWatch , "watch" , "w" , false , "watch filesystem for changes and recreate as needed" )
2024-04-20 05:05:35 -04:00
cmd . PersistentFlags ( ) . MarkHidden ( "devMode" )
2023-01-04 12:24:36 -05:00
// Configure local flags
2023-05-28 04:44:40 -04:00
applyLocalFlagsBuild ( cmd , r )
2023-05-17 06:45:51 -04:00
return nil
}
2023-05-28 04:44:40 -04:00
// A sub set of the complete build flags. These flags are used by new and mod.
func applyLocalFlagsBuildConfig ( cmd * cobra . Command , r * rootCommand ) {
cmd . Flags ( ) . StringSliceP ( "theme" , "t" , [ ] string { } , "themes to use (located in /themes/THEMENAME/)" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . MarkFlagDirname ( "theme" )
2023-05-28 04:44:40 -04:00
cmd . Flags ( ) . StringVarP ( & r . baseURL , "baseURL" , "b" , "" , "hostname (and path) to the root, e.g. https://spf13.com/" )
2023-07-29 14:30:52 -04:00
cmd . Flags ( ) . StringP ( "cacheDir" , "" , "" , "filesystem path to cache directory" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . MarkFlagDirname ( "cacheDir" )
2023-05-28 04:44:40 -04:00
cmd . Flags ( ) . StringP ( "contentDir" , "c" , "" , "filesystem path to content directory" )
Add segments config + --renderSegments flag
Named segments can be defined in `hugo.toml`.
* Eeach segment consists of zero or more `exclude` filters and zero or more `include` filters.
* Eeach filter consists of one or more field Glob matchers.
* Eeach filter in a section (`exclude` or `include`) is ORed together, each matcher in a filter is ANDed together.
The current list of fields that can be filtered are:
* path as defined in https://gohugo.io/methods/page/path/
* kind
* lang
* output (output format, e.g. html).
It is recommended to put coarse grained filters (e.g. for language and output format) in the excludes section, e.g.:
```toml
[segments.segment1]
[[segments.segment1.excludes]]
lang = "n*"
[[segments.segment1.excludes]]
no = "en"
output = "rss"
[[segments.segment1.includes]]
term = "{home,term,taxonomy}"
[[segments.segment1.includes]]
path = "{/docs,/docs/**}"
```
By default, Hugo will render all segments, but you can enable filters by setting the `renderSegments` option or `--renderSegments` flag, e.g:
```
hugo --renderSegments segment1,segment2
```
For segment `segment1` in the configuration above, this will:
* Skip rendering of all languages matching `n*`, e.g. `no`.
* Skip rendering of the output format `rss` for the `en` language.
* It will render all pages of kind `home`, `term` or `taxonomy`
* It will render the `/docs` section and all pages below.
Fixes #10106
2024-03-04 04:16:56 -05:00
cmd . Flags ( ) . StringSliceP ( "renderSegments" , "" , [ ] string { } , "named segments to render (configured in the segments config)" )
2023-05-28 04:44:40 -04:00
}
// Flags needed to do a build (used by hugo and hugo server commands)
func applyLocalFlagsBuild ( cmd * cobra . Command , r * rootCommand ) {
applyLocalFlagsBuildConfig ( cmd , r )
2023-01-04 12:24:36 -05:00
cmd . Flags ( ) . Bool ( "cleanDestinationDir" , false , "remove files from destination not found in static directories" )
cmd . Flags ( ) . BoolP ( "buildDrafts" , "D" , false , "include content marked as draft" )
cmd . Flags ( ) . BoolP ( "buildFuture" , "F" , false , "include content with publishdate in the future" )
cmd . Flags ( ) . BoolP ( "buildExpired" , "E" , false , "include expired content" )
cmd . Flags ( ) . BoolP ( "ignoreCache" , "" , false , "ignores the cache directory" )
cmd . Flags ( ) . Bool ( "enableGitInfo" , false , "add Git revision, date, author, and CODEOWNERS info to the pages" )
2023-05-28 07:06:26 -04:00
cmd . Flags ( ) . StringP ( "layoutDir" , "l" , "" , "filesystem path to layout directory" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . MarkFlagDirname ( "layoutDir" )
2023-05-17 12:45:23 -04:00
cmd . Flags ( ) . BoolVar ( & r . gc , "gc" , false , "enable to run some cleanup tasks (remove unused cache files) after the build" )
cmd . Flags ( ) . StringVar ( & r . poll , "poll" , "" , "set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . RegisterFlagCompletionFunc ( "poll" , cobra . NoFileCompletions )
2023-06-16 02:17:42 -04:00
cmd . Flags ( ) . Bool ( "panicOnWarning" , false , "panic on first WARNING log" )
2023-01-04 12:24:36 -05:00
cmd . Flags ( ) . Bool ( "templateMetrics" , false , "display metrics about template executions" )
cmd . Flags ( ) . Bool ( "templateMetricsHints" , false , "calculate some improvement hints when combined with --templateMetrics" )
2023-05-17 12:45:23 -04:00
cmd . Flags ( ) . BoolVar ( & r . forceSyncStatic , "forceSyncStatic" , false , "copy all files when static is changed." )
2023-01-04 12:24:36 -05:00
cmd . Flags ( ) . BoolP ( "noTimes" , "" , false , "don't sync modification time of files" )
cmd . Flags ( ) . BoolP ( "noChmod" , "" , false , "don't sync permission mode of files" )
cmd . Flags ( ) . BoolP ( "noBuildLock" , "" , false , "don't create .hugo_build.lock file" )
cmd . Flags ( ) . BoolP ( "printI18nWarnings" , "" , false , "print missing translations" )
2023-06-30 02:47:11 -04:00
cmd . Flags ( ) . BoolP ( "printPathWarnings" , "" , false , "print warnings on duplicate target paths etc." )
cmd . Flags ( ) . BoolP ( "printUnusedTemplates" , "" , false , "print warnings on unused templates." )
2023-05-17 12:45:23 -04:00
cmd . Flags ( ) . StringVarP ( & r . cpuprofile , "profile-cpu" , "" , "" , "write cpu profile to `file`" )
cmd . Flags ( ) . StringVarP ( & r . memprofile , "profile-mem" , "" , "" , "write memory profile to `file`" )
cmd . Flags ( ) . BoolVarP ( & r . printm , "printMemoryUsage" , "" , false , "print memory usage to screen at intervals" )
cmd . Flags ( ) . StringVarP ( & r . mutexprofile , "profile-mutex" , "" , "" , "write Mutex profile to `file`" )
cmd . Flags ( ) . StringVarP ( & r . traceprofile , "trace" , "" , "" , "write trace to `file` (not useful in general)" )
2023-01-04 12:24:36 -05:00
// Hide these for now.
cmd . Flags ( ) . MarkHidden ( "profile-cpu" )
cmd . Flags ( ) . MarkHidden ( "profile-mem" )
cmd . Flags ( ) . MarkHidden ( "profile-mutex" )
cmd . Flags ( ) . StringSlice ( "disableKinds" , [ ] string { } , "disable different kind of pages (home, RSS etc.)" )
completion: Improve existing argument completions, add many more
Do not offer filenames to arguments not taking one, complete arguments
of options taking resource kinds, directory names, --logLevel, release
--step, config and new --format.
As an internal refactoring, use higher level functions to set flag
completions. SetAnnotation works, but is more verbose than
alternatives, and uses bash specific wording.
While at it, move setting completions next to flag definitions
consistently.
Remove superfluous --destination completer setting, which is already
set elsewhere.
2024-04-07 16:33:17 -04:00
_ = cmd . RegisterFlagCompletionFunc ( "disableKinds" , cobra . FixedCompletions ( kinds . AllKinds , cobra . ShellCompDirectiveNoFileComp ) )
2023-01-04 12:24:36 -05:00
cmd . Flags ( ) . Bool ( "minify" , false , "minify any supported output format (HTML, XML etc.)" )
}
Add Hugo Piper with SCSS support and much more
Before this commit, you would have to use page bundles to do image processing etc. in Hugo.
This commit adds
* A new `/assets` top-level project or theme dir (configurable via `assetDir`)
* A new template func, `resources.Get` which can be used to "get a resource" that can be further processed.
This means that you can now do this in your templates (or shortcodes):
```bash
{{ $sunset := (resources.Get "images/sunset.jpg").Fill "300x200" }}
```
This also adds a new `extended` build tag that enables powerful SCSS/SASS support with source maps. To compile this from source, you will also need a C compiler installed:
```
HUGO_BUILD_TAGS=extended mage install
```
Note that you can use output of the SCSS processing later in a non-SCSSS-enabled Hugo.
The `SCSS` processor is a _Resource transformation step_ and it can be chained with the many others in a pipeline:
```bash
{{ $css := resources.Get "styles.scss" | resources.ToCSS | resources.PostCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
The transformation funcs above have aliases, so it can be shortened to:
```bash
{{ $css := resources.Get "styles.scss" | toCSS | postCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}" integrity="{{ $styles.Data.Digest }}" media="screen">
```
A quick tip would be to avoid the fingerprinting part, and possibly also the not-superfast `postCSS` when you're doing development, as it allows Hugo to be smarter about the rebuilding.
Documentation will follow, but have a look at the demo repo in https://github.com/bep/hugo-sass-test
New functions to create `Resource` objects:
* `resources.Get` (see above)
* `resources.FromString`: Create a Resource from a string.
New `Resource` transformation funcs:
* `resources.ToCSS`: Compile `SCSS` or `SASS` into `CSS`.
* `resources.PostCSS`: Process your CSS with PostCSS. Config file support (project or theme or passed as an option).
* `resources.Minify`: Currently supports `css`, `js`, `json`, `html`, `svg`, `xml`.
* `resources.Fingerprint`: Creates a fingerprinted version of the given Resource with Subresource Integrity..
* `resources.Concat`: Concatenates a list of Resource objects. Think of this as a poor man's bundler.
* `resources.ExecuteAsTemplate`: Parses and executes the given Resource and data context (e.g. .Site) as a Go template.
Fixes #4381
Fixes #4903
Fixes #4858
2018-02-20 04:02:14 -05:00
2023-01-04 12:24:36 -05:00
func ( r * rootCommand ) timeTrack ( start time . Time , name string ) {
elapsed := time . Since ( start )
r . Printf ( "%s in %v ms\n" , name , int ( 1000 * elapsed . Seconds ( ) ) )
}
2019-01-02 06:33:26 -05:00
2023-01-04 12:24:36 -05:00
type simpleCommand struct {
use string
name string
short string
long string
run func ( ctx context . Context , cd * simplecobra . Commandeer , rootCmd * rootCommand , args [ ] string ) error
2023-05-28 04:44:40 -04:00
withc func ( cmd * cobra . Command , r * rootCommand )
2023-01-04 12:24:36 -05:00
initc func ( cd * simplecobra . Commandeer ) error
2019-01-02 06:33:26 -05:00
2023-01-04 12:24:36 -05:00
commands [ ] simplecobra . Commander
Add support for theme composition and inheritance
This commit adds support for theme composition and inheritance in Hugo.
With this, it helps thinking about a theme as a set of ordered components:
```toml
theme = ["my-shortcodes", "base-theme", "hyde"]
```
The theme definition example above in `config.toml` creates a theme with the 3 components with presedence from left to right.
So, Hugo will, for any given file, data entry etc., look first in the project, and then in `my-shortcode`, `base-theme` and lastly `hyde`.
Hugo uses two different algorithms to merge the filesystems, depending on the file type:
* For `i18n` and `data` files, Hugo merges deeply using the translation id and data key inside the files.
* For `static`, `layouts` (templates) and `archetypes` files, these are merged on file level. So the left-most file will be chosen.
The name used in the `theme` definition above must match a folder in `/your-site/themes`, e.g. `/your-site/themes/my-shortcodes`. There are plans to improve on this and get a URL scheme so this can be resolved automatically.
Also note that a component that is part of a theme can have its own configuration file, e.g. `config.toml`. There are currently some restrictions to what a theme component can configure:
* `params` (global and per language)
* `menu` (global and per language)
* `outputformats` and `mediatypes`
The same rules apply here: The left-most param/menu etc. with the same ID will win. There are some hidden and experimental namespace support in the above, which we will work to improve in the future, but theme authors are encouraged to create their own namespaces to avoid naming conflicts.
A final note: Themes/components can also have a `theme` definition in their `config.toml` and similar, which is the "inheritance" part of this commit's title. This is currently not supported by the Hugo theme site. We will have to wait for some "auto dependency" feature to be implemented for that to happen, but this can be a powerful feature if you want to create your own theme-variant based on others.
Fixes #4460
Fixes #4450
2018-03-01 09:01:25 -05:00
2023-01-04 12:24:36 -05:00
rootCmd * rootCommand
}
Add support for theme composition and inheritance
This commit adds support for theme composition and inheritance in Hugo.
With this, it helps thinking about a theme as a set of ordered components:
```toml
theme = ["my-shortcodes", "base-theme", "hyde"]
```
The theme definition example above in `config.toml` creates a theme with the 3 components with presedence from left to right.
So, Hugo will, for any given file, data entry etc., look first in the project, and then in `my-shortcode`, `base-theme` and lastly `hyde`.
Hugo uses two different algorithms to merge the filesystems, depending on the file type:
* For `i18n` and `data` files, Hugo merges deeply using the translation id and data key inside the files.
* For `static`, `layouts` (templates) and `archetypes` files, these are merged on file level. So the left-most file will be chosen.
The name used in the `theme` definition above must match a folder in `/your-site/themes`, e.g. `/your-site/themes/my-shortcodes`. There are plans to improve on this and get a URL scheme so this can be resolved automatically.
Also note that a component that is part of a theme can have its own configuration file, e.g. `config.toml`. There are currently some restrictions to what a theme component can configure:
* `params` (global and per language)
* `menu` (global and per language)
* `outputformats` and `mediatypes`
The same rules apply here: The left-most param/menu etc. with the same ID will win. There are some hidden and experimental namespace support in the above, which we will work to improve in the future, but theme authors are encouraged to create their own namespaces to avoid naming conflicts.
A final note: Themes/components can also have a `theme` definition in their `config.toml` and similar, which is the "inheritance" part of this commit's title. This is currently not supported by the Hugo theme site. We will have to wait for some "auto dependency" feature to be implemented for that to happen, but this can be a powerful feature if you want to create your own theme-variant based on others.
Fixes #4460
Fixes #4450
2018-03-01 09:01:25 -05:00
2023-01-04 12:24:36 -05:00
func ( c * simpleCommand ) Commands ( ) [ ] simplecobra . Commander {
return c . commands
}
2022-03-18 03:54:44 -04:00
2023-01-04 12:24:36 -05:00
func ( c * simpleCommand ) Name ( ) string {
return c . name
}
2018-03-18 06:07:24 -04:00
2023-01-04 12:24:36 -05:00
func ( c * simpleCommand ) Run ( ctx context . Context , cd * simplecobra . Commandeer , args [ ] string ) error {
if c . run == nil {
return nil
2018-03-18 06:07:24 -04:00
}
2023-01-04 12:24:36 -05:00
return c . run ( ctx , cd , c . rootCmd , args )
}
2018-03-18 06:07:24 -04:00
2023-05-17 12:45:23 -04:00
func ( c * simpleCommand ) Init ( cd * simplecobra . Commandeer ) error {
2023-05-28 04:44:40 -04:00
c . rootCmd = cd . Root . Command . ( * rootCommand )
2023-05-17 12:45:23 -04:00
cmd := cd . CobraCommand
2023-01-04 12:24:36 -05:00
cmd . Short = c . short
cmd . Long = c . long
if c . use != "" {
cmd . Use = c . use
}
if c . withc != nil {
2023-05-28 04:44:40 -04:00
c . withc ( cmd , c . rootCmd )
2018-03-18 06:07:24 -04:00
}
2023-01-04 12:24:36 -05:00
return nil
}
2018-03-18 06:07:24 -04:00
2023-05-17 12:45:23 -04:00
func ( c * simpleCommand ) PreRun ( cd , runner * simplecobra . Commandeer ) error {
2023-01-04 12:24:36 -05:00
if c . initc != nil {
return c . initc ( cd )
}
2018-03-18 06:07:24 -04:00
return nil
2017-02-04 22:20:06 -05:00
}
2023-01-04 12:24:36 -05:00
func mapLegacyArgs ( args [ ] string ) [ ] string {
if len ( args ) > 1 && args [ 0 ] == "new" && ! hstrings . EqualAny ( args [ 1 ] , "site" , "theme" , "content" ) {
// Insert "content" as the second argument
args = append ( args [ : 1 ] , append ( [ ] string { "content" } , args [ 1 : ] ... ) ... )
}
return args
}