"path/filepath"
"runtime"
"strings"
+ "sync"
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/hugofs/files"
+ "github.com/gohugoio/hugo/identity"
)
var defaultPathParser PathParser
return s
}
+// ParseIdentity parses component c with path s into a StringIdentity.
+func (pp *PathParser) ParseIdentity(c, s string) identity.StringIdentity {
+ s = NormalizePathStringBasic(s)
+ p := getPath()
+ p.component = c
+ defer putPath(p)
+ p, err := pp.doParse(c, s, p)
+ if err != nil {
+ panic(err)
+ }
+ return identity.StringIdentity(p.IdentifierBase())
+}
+
// Parse parses component c with path s into Path using Hugo's content path rules.
-func (parser PathParser) Parse(c, s string) *Path {
- p, err := parser.parse(c, s)
+func (pp *PathParser) Parse(c, s string) *Path {
+ p, err := pp.parse(c, s)
if err != nil {
panic(err)
}
return p
}
+func (pp *PathParser) newPath(component string) *Path {
+ return &Path{
+ component: component,
+ posContainerLow: -1,
+ posContainerHigh: -1,
+ posSectionHigh: -1,
+ posIdentifierLanguage: -1,
+ }
+}
+
func (pp *PathParser) parse(component, s string) (*Path, error) {
ss := NormalizePathStringBasic(s)
- p, err := pp.doParse(component, ss)
+ p, err := pp.doParse(component, ss, pp.newPath(component))
if err != nil {
return nil, err
}
if s != ss {
var err error
// Preserve the original case for titles etc.
- p.unnormalized, err = pp.doParse(component, s)
+ p.unnormalized, err = pp.doParse(component, s, pp.newPath(component))
if err != nil {
return nil, err
return p, nil
}
-func (pp *PathParser) doParse(component, s string) (*Path, error) {
- p := &Path{
- component: component,
- posContainerLow: -1,
- posContainerHigh: -1,
- posSectionHigh: -1,
- posIdentifierLanguage: -1,
- }
-
+func (pp *PathParser) doParse(component, s string, p *Path) (*Path, error) {
hasLang := pp.LanguageIndex != nil
hasLang = hasLang && (component == files.ComponentFolderContent || component == files.ComponentFolderLayouts)
)
type Path struct {
+ // Note: Any additions to this struct should also be added to the pathPool.
s string
posContainerLow int
unnormalized *Path
}
+var pathPool = &sync.Pool{
+ New: func() any {
+ return &Path{}
+ },
+}
+
+func getPath() *Path {
+ return pathPool.Get().(*Path)
+}
+
+func putPath(p *Path) {
+ p.s = ""
+ p.posContainerLow = -1
+ p.posContainerHigh = -1
+ p.posSectionHigh = -1
+ p.component = ""
+ p.bundleType = 0
+ p.identifiers = p.identifiers[:0]
+ p.posIdentifierLanguage = -1
+ p.disabled = false
+ p.trimLeadingSlash = false
+ p.unnormalized = nil
+ pathPool.Put(p)
+}
+
// TrimLeadingSlash returns a copy of the Path with the leading slash removed.
func (p Path) TrimLeadingSlash() *Path {
p.trimLeadingSlash = true
// IdentifierBase satifies identity.Identity.
func (p *Path) IdentifierBase() string {
- return p.Base()[1:]
+ return p.Base()
}
// Component returns the component for this path (e.g. "content").
c.Assert(HasExt("/a/b/c"), qt.IsFalse)
c.Assert(HasExt("/a/b.c/d"), qt.IsFalse)
}
+
+func BenchmarkParseIdentity(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ testParser.ParseIdentity(files.ComponentFolderAssets, "/a/b.css")
+ }
+}
// All below is set in Init.
Languages langs.Languages
LanguagesDefaultFirst langs.Languages
- ContentPathParser paths.PathParser
+ ContentPathParser *paths.PathParser
configLangs []config.AllProvider
}
c.Languages = languages
c.LanguagesDefaultFirst = languagesDefaultFirst
- c.ContentPathParser = paths.PathParser{LanguageIndex: languagesDefaultFirst.AsIndexSet(), IsLangDisabled: c.Base.IsLangDisabled}
+ c.ContentPathParser = &paths.PathParser{LanguageIndex: languagesDefaultFirst.AsIndexSet(), IsLangDisabled: c.Base.IsLangDisabled}
c.configLangs = make([]config.AllProvider, len(c.Languages))
for i, l := range c.LanguagesDefaultFirst {
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/common/urls"
"github.com/gohugoio/hugo/config"
+ "github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/langs"
)
return c.m.LanguagesDefaultFirst
}
-func (c ConfigLanguage) PathParser() paths.PathParser {
+func (c ConfigLanguage) PathParser() *paths.PathParser {
return c.m.ContentPathParser
}
return c.m.Base.Internal.Watch
}
+func (c ConfigLanguage) NewIdentityManager(name string) identity.Manager {
+ if !c.Watching() {
+ return identity.NopManager
+ }
+ return identity.NewManager(name)
+}
+
// GetConfigSection is mostly used in tests. The switch statement isn't complete, but what's in use.
func (c ConfigLanguage) GetConfigSection(s string) any {
switch s {
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/common/types"
"github.com/gohugoio/hugo/common/urls"
+ "github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/langs"
)
LanguagePrefix() string
BaseURL() urls.BaseURL
BaseURLLiveReload() urls.BaseURL
- PathParser() paths.PathParser
+ PathParser() *paths.PathParser
Environment() string
IsMultihost() bool
IsMultiLingual() bool
BuildDrafts() bool
Running() bool
Watching() bool
+ NewIdentityManager(name string) identity.Manager
FastRenderMode() bool
PrintUnusedTemplates() bool
EnableMissingTranslationPlaceholders() bool
DefaultContentLanguage string
// The parser used to parse paths provided by this filesystem.
- PathParser paths.PathParser
+ PathParser *paths.PathParser
}
func (fs *componentFs) Open(name string) (afero.File, error) {
return r.path
}
-func (r *resourceSource) ForEeachIdentity(f func(identity.Identity) bool) {
- f(r.GetIdentity())
+func (r *resourceSource) ForEeachIdentity(f func(identity.Identity) bool) bool {
+ return f(r.GetIdentity())
}
func (r *resourceSource) Path() string {
return nil
}
-func (n resourceSources) ForEeachIdentity(f func(identity.Identity) bool) {
+func (n resourceSources) ForEeachIdentity(f func(identity.Identity) bool) bool {
for _, r := range n {
if r != nil {
if f(r.GetIdentity()) {
- return
+ return true
}
}
}
+ return false
}
func (cfg contentMapConfig) getTaxonomyConfig(s string) (v viewName) {
return n[0].GetIdentity()
}
-func (n contentNodeIs) ForEeachIdentity(f func(identity.Identity) bool) {
+func (n contentNodeIs) ForEeachIdentity(f func(identity.Identity) bool) bool {
for _, nn := range n {
if nn != nil {
- nn.ForEeachIdentity(f)
+ if nn.ForEeachIdentity(f) {
+ return true
+ }
}
}
+ return false
}
func (n contentNodeIs) resetBuildState() {
// First check the top level dependency manager.
for _, id := range changes {
checkedCounter.Add(1)
- if r := depsFinder.Contains(id, p.dependencyManager, 100); r > identity.FinderFoundOneOfManyRepetition {
+ if r := depsFinder.Contains(id, p.dependencyManager, 2); r > identity.FinderFoundOneOfManyRepetition {
for _, po := range p.pageOutputs {
resetPo(po, r)
}
}
for _, id := range changes {
checkedCounter.Add(1)
- if r := depsFinder.Contains(id, po.dependencyManagerOutput, 2); r > identity.FinderFoundOneOfManyRepetition {
+ if r := depsFinder.Contains(id, po.dependencyManagerOutput, 50); r > identity.FinderFoundOneOfManyRepetition {
resetPo(po, r)
continue OUTPUTS
}
return p
}
-func (p *pageState) ForEeachIdentity(f func(identity.Identity) bool) {
- f(p)
+func (p *pageState) ForEeachIdentity(f func(identity.Identity) bool) bool {
+ return f(p)
}
func (p *pageState) GetDependencyManager() identity.Manager {
"sync/atomic"
"github.com/gohugoio/hugo/hugofs/files"
- "github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/resources"
"github.com/gohugoio/hugo/common/maps"
return nil, nil
}
- var dependencyManager identity.Manager = identity.NopManager
-
- if m.s.conf.Internal.Watch {
- dependencyManager = identity.NewManager(m.Path())
- }
-
// Parse the rest of the page content.
m.content, err = m.newCachedContent(h, pi)
if err != nil {
pageOutputTemplateVariationsState: &atomic.Uint32{},
resourcesPublishInit: &sync.Once{},
Staler: m,
- dependencyManager: dependencyManager,
+ dependencyManager: m.s.Conf.NewIdentityManager(m.Path()),
pageCommon: &pageCommon{
FileProvider: m,
AuthorProvider: m,
})
}
- var dependencyManager identity.Manager = identity.NopManager
- if ps.s.conf.Internal.Watch {
- dependencyManager = identity.NewManager(ps.Path() + "/" + f.Name)
- }
-
providers := struct {
page.PaginatorProvider
resource.ResourceLinksProvider
TableOfContentsProvider: page.NopPage,
render: render,
paginator: pag,
- dependencyManagerOutput: dependencyManager,
+ dependencyManagerOutput: ps.s.Conf.NewIdentityManager((ps.Path() + "/" + f.Name)),
}
return po
Running: true,
NeedsOsFS: true,
NeedsNpmInstall: true,
- // LogLevel: logg.LevelTrace,
+ // LogLevel: logg.LevelDebug,
},
).Build()
// fmt.Println(bb.LogString())
}
}
+
+func TestRebuildConcat(t *testing.T) {
+ files := `
+-- hugo.toml --
+baseURL = "https://example.com"
+disableLiveReload = true
+disableKinds = ["taxonomy", "term", "sitemap", "robotsTXT", "404", "rss"]
+-- assets/a.css --
+a
+-- assets/b.css --
+b
+-- assets/c.css --
+c
+-- assets/common/c1.css --
+c1
+-- assets/common/c2.css --
+c2
+-- layouts/index.html --
+{{ $a := resources.Get "a.css" }}
+{{ $b := resources.Get "b.css" }}
+{{ $common := resources.Match "common/*.css" | resources.Concat "common.css" | minify }}
+{{ $ab := slice $a $b $common | resources.Concat "ab.css" }}
+all: {{ $ab.RelPermalink }}
+`
+ b := TestRunning(t, files)
+
+ b.AssertFileContent("public/ab.css", "abc1c2")
+ b.EditFileReplaceAll("assets/common/c2.css", "c2", "c2 edited").Build()
+ b.AssertFileContent("public/ab.css", "abc1c2 edited")
+ b.AddFiles("assets/common/c3.css", "c3").Build()
+ b.AssertFileContent("public/ab.css", "abc1c2 editedc3")
+}
return r
}
- ids := m.getIdentities()
- if len(ids) == 0 {
- r = FinderNotFound
- } else {
- r = f.search(sid, ids, level)
- }
+ r = f.search(sid, m, level)
if r == FinderFoundOneOfMany {
// Don't cache this one.
}
// search searches for id in ids.
-func (f *Finder) search(sid *searchID, ids Identities, depth int) FinderResult {
- if len(ids) == 0 {
- return FinderNotFound
- }
-
+func (f *Finder) search(sid *searchID, m Manager, depth int) FinderResult {
id := sid.id
if id == Anonymous {
return FinderNotFound
}
- for v := range ids {
- r := f.checkOne(sid, v, depth)
- if r > 0 {
- return r
- }
-
- m := GetDependencyManager(v)
- if r := f.checkManager(sid, m, depth+1); r > 0 {
- return r
- }
- }
-
- return FinderNotFound
+ var r FinderResult
+ m.forEeachIdentity(
+ func(v Identity) bool {
+ if r > 0 {
+ panic("should be terminated")
+ }
+ r = f.checkOne(sid, v, depth)
+ if r > 0 {
+ return true
+ }
+ m := GetDependencyManager(v)
+ if r = f.checkManager(sid, m, depth+1); r > 0 {
+ return true
+ }
+ return false
+ },
+ )
+ return r
}
// FinderConfig provides configuration for the Finder.
// CleanString cleans s to be suitable as an identifier.
func CleanString(s string) string {
s = strings.ToLower(s)
- s = strings.TrimPrefix(filepath.ToSlash(s), "/")
- return path.Clean(s)
+ s = strings.Trim(filepath.ToSlash(s), "/")
+ return "/" + path.Clean(s)
}
// CleanStringIdentity cleans s to be suitable as an identifier and wraps it in a StringIdentity.
return nil
}
-// GetDependencyManagerForScope returns the DependencyManager for the given scope from v or nil if none found.
-// Note that it will fall back to an unscoped manager if none found for the given scope.
-func GetDependencyManagerForScope(v any, scope int) Manager {
- switch vv := v.(type) {
- case DependencyManagerScopedProvider:
- return vv.GetDependencyManagerForScope(scope)
- case types.Unwrapper:
- return GetDependencyManagerForScope(vv.Unwrapv(), scope)
- case Manager:
- return vv
- case DependencyManagerProvider:
- return vv.GetDependencyManager()
-
- }
- return nil
-}
-
// FirstIdentity returns the first Identity in v, Anonymous if none found
func FirstIdentity(v any) Identity {
var result Identity = Anonymous
type ForEeachIdentityProvider interface {
// ForEeachIdentityProvider calls cb for each Identity.
// If cb returns true, the iteration is terminated.
- ForEeachIdentity(cb func(id Identity) bool)
+ // The return value is whether the iteration was terminated.
+ ForEeachIdentity(cb func(id Identity) bool) bool
+}
+
+// ForEeachIdentityProviderFunc is a function that implements the ForEeachIdentityProvider interface.
+type ForEeachIdentityProviderFunc func(func(id Identity) bool) bool
+
+func (f ForEeachIdentityProviderFunc) ForEeachIdentity(cb func(id Identity) bool) bool {
+ return f(cb)
}
// ForEeachIdentityByNameProvider provides a way to look up identities by name.
type Manager interface {
Identity
AddIdentity(ids ...Identity)
+ AddIdentityForEach(ids ...ForEeachIdentityProvider)
GetIdentity() Identity
Reset()
- getIdentities() Identities
+ forEeachIdentity(func(id Identity) bool) bool
}
type ManagerOption func(m *identityManager)
// mu protects _changes_ to this manager,
// reads currently assumes no concurrent writes.
- mu sync.RWMutex
- ids Identities
+ mu sync.RWMutex
+ ids Identities
+ forEachIds []ForEeachIdentityProvider
// Hooks used in debugging.
onAddIdentity func(id Identity)
im.mu.Lock()
for _, id := range ids {
- if id == Anonymous {
+ if id == nil || id == Anonymous {
continue
}
if _, found := im.ids[id]; !found {
im.mu.Unlock()
}
+func (im *identityManager) AddIdentityForEach(ids ...ForEeachIdentityProvider) {
+ im.mu.Lock()
+ im.forEachIds = append(im.forEachIds, ids...)
+ im.mu.Unlock()
+}
+
func (im *identityManager) ContainsIdentity(id Identity) FinderResult {
if im.Identity != Anonymous && id == im.Identity {
return FinderFound
return fmt.Sprintf("IdentityManager(%s)", im.name)
}
-// TODO(bep) these identities are currently only read on server reloads
-// so there should be no concurrency issues, but that may change.
-func (im *identityManager) getIdentities() Identities {
- return im.ids
+func (im *identityManager) forEeachIdentity(fn func(id Identity) bool) bool {
+ // The absense of a lock here is debliberate. This is currently opnly used on server reloads
+ // in a single-threaded context.
+ for id := range im.ids {
+ if fn(id) {
+ return true
+ }
+ }
+ for _, fe := range im.forEachIds {
+ if fe.ForEeachIdentity(fn) {
+ return true
+ }
+ }
+ return false
}
type nopManager int
func (m *nopManager) AddIdentity(ids ...Identity) {
}
+func (m *nopManager) AddIdentityForEach(ids ...ForEeachIdentityProvider) {
+}
+
func (m *nopManager) IdentifierBase() string {
return ""
}
func (m *nopManager) Reset() {
}
-func (m *nopManager) getIdentities() Identities {
- return nil
+func (m *nopManager) forEeachIdentity(func(id Identity) bool) bool {
+ return false
}
// returns whether further walking should be terminated.
if deep {
if m := GetDependencyManager(id); m != nil {
- for id2 := range m.getIdentities() {
- if walkIdentitiesShallow(id2, level+1, cbRecursive) {
- return true
- }
- }
+ m.forEeachIdentity(func(id2 Identity) bool {
+ return walkIdentitiesShallow(id2, level+1, cbRecursive)
+ })
}
}
return false
if id == Anonymous {
return false
}
+ if id == nil {
+ return false
+ }
return cb(level, id)
}
fd.MediaType = mediaType
if fd.DependencyManager == nil {
- fd.DependencyManager = identity.NopManager
+ fd.DependencyManager = r.Cfg.NewIdentityManager("resource")
}
return nil
cacheResources: dynacache.GetOrCreatePartition[string, resource.Resources](
memCache,
"/ress",
- dynacache.OptionsPartition{ClearWhen: dynacache.ClearOnChange, Weight: 40},
+ dynacache.OptionsPartition{ClearWhen: dynacache.ClearOnRebuild, Weight: 40},
),
cacheResourceTransformation: dynacache.GetOrCreatePartition[string, *resourceAdapterInner](
memCache,
"path"
"github.com/gohugoio/hugo/common/hugio"
+ "github.com/gohugoio/hugo/identity"
"github.com/gohugoio/hugo/media"
"github.com/gohugoio/hugo/resources"
"github.com/gohugoio/hugo/resources/resource"
// The given set of resources must be of the same Media Type.
// We may improve on that in the future, but then we need to know more.
- for i, r := range r {
- if i > 0 && r.MediaType().Type != resolvedm.Type {
- return nil, fmt.Errorf("resources in Concat must be of the same Media Type, got %q and %q", r.MediaType().Type, resolvedm.Type)
+ for i, rr := range r {
+ if i > 0 && rr.MediaType().Type != resolvedm.Type {
+ return nil, fmt.Errorf("resources in Concat must be of the same Media Type, got %q and %q", rr.MediaType().Type, resolvedm.Type)
}
- resolvedm = r.MediaType()
+ resolvedm = rr.MediaType()
}
+ idm := c.rs.Cfg.NewIdentityManager("concat")
+ // Add the concatenated resources as dependencies to the composite resource
+ // so that we can track changes to the individual resources.
+ idm.AddIdentityForEach(identity.ForEeachIdentityProviderFunc(
+ func(f func(identity.Identity) bool) bool {
+ var terminate bool
+ for _, rr := range r {
+ identity.WalkIdentitiesShallow(rr, func(depth int, id identity.Identity) bool {
+ terminate = f(id)
+ return terminate
+ })
+ if terminate {
+ break
+ }
+ }
+ return terminate
+ },
+ ))
+
concatr := func() (hugio.ReadSeekCloser, error) {
var rcsources []hugio.ReadSeekCloser
for _, s := range r {
LazyPublish: true,
OpenReadSeekCloser: concatr,
TargetPath: targetPath,
+ DependencyManager: idm,
})
if err != nil {
return nil, err
})
}
-func (c *Client) newDependencyManager() identity.Manager {
- if c.rs.Cfg.Running() {
- return identity.NewManager("resources")
- }
- return identity.NopManager
-}
-
// Get creates a new Resource by opening the given pathname in the assets filesystem.
func (c *Client) Get(pathname string) (resource.Resource, error) {
pathname = path.Clean(pathname)
// The resource file will not be read before it gets used (e.g. in .Content),
// so we need to check that the file exists here.
filename := filepath.FromSlash(pathname)
- if _, err := c.rs.BaseFs.Assets.Fs.Stat(filename); err != nil {
+ fi, err := c.rs.BaseFs.Assets.Fs.Stat(filename)
+ if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
+ pi := fi.(hugofs.FileMetaInfo).Meta().PathInfo
+
return c.rs.NewResource(resources.ResourceSourceDescriptor{
LazyPublish: true,
OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {
return c.rs.BaseFs.Assets.Fs.Open(filename)
},
- GroupIdentity: identity.StringIdentity(key),
- DependencyManager: c.newDependencyManager(),
- TargetPath: pathname,
+ Path: pi,
+ GroupIdentity: pi,
+ TargetPath: pathname,
})
})
}