repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/allconfig/configlanguage.go
config/allconfig/configlanguage.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package allconfig import ( "time" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/urls" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/langs" ) type ConfigLanguage struct { config *Config baseConfig config.BaseConfig m *Configs language *langs.Language languageIndex int } func (c ConfigLanguage) Language() any { return c.language } func (c ConfigLanguage) LanguageIndex() int { return c.languageIndex } func (c ConfigLanguage) Languages() any { return c.m.Languages } func (c ConfigLanguage) PathParser() *paths.PathParser { return c.m.ContentPathParser } func (c ConfigLanguage) LanguagePrefix() string { if c.DefaultContentLanguageInSubdir() && c.DefaultContentLanguage() == c.language.Lang { return c.language.Lang } if !c.IsMultilingual() || c.DefaultContentLanguage() == c.language.Lang { return "" } return c.language.Lang } func (c ConfigLanguage) BaseURL() urls.BaseURL { return c.config.C.BaseURL } func (c ConfigLanguage) BaseURLLiveReload() urls.BaseURL { return c.config.C.BaseURLLiveReload } func (c ConfigLanguage) Environment() string { return c.config.Environment } func (c ConfigLanguage) IsMultihost() bool { if len(c.m.Languages)-len(c.config.C.DisabledLanguages) <= 1 { return false } return c.m.IsMultihost } func (c ConfigLanguage) FastRenderMode() bool { return c.config.Internal.FastRenderMode } func (c ConfigLanguage) IsMultilingual() bool { return len(c.m.Languages) > 1 } func (c ConfigLanguage) TemplateMetrics() bool { return c.config.TemplateMetrics } func (c ConfigLanguage) TemplateMetricsHints() bool { return c.config.TemplateMetricsHints } func (c ConfigLanguage) IsLangDisabled(lang string) bool { return c.config.C.DisabledLanguages[lang] } func (c ConfigLanguage) IsKindEnabled(kind string) bool { return !c.config.C.DisabledKinds[kind] } func (c ConfigLanguage) IgnoredLogs() map[string]bool { return c.config.C.IgnoredLogs } func (c ConfigLanguage) NoBuildLock() bool { return c.config.NoBuildLock } func (c ConfigLanguage) NewContentEditor() string { return c.config.NewContentEditor } func (c ConfigLanguage) Timeout() time.Duration { return c.config.C.Timeout } func (c ConfigLanguage) BaseConfig() config.BaseConfig { return c.baseConfig } func (c ConfigLanguage) Dirs() config.CommonDirs { return c.config.CommonDirs } func (c ConfigLanguage) DirsBase() config.CommonDirs { return c.m.Base.CommonDirs } func (c ConfigLanguage) WorkingDir() string { return c.m.Base.WorkingDir } func (c ConfigLanguage) CacheDirMisc() string { return c.config.Caches.CacheDirMisc() } func (c ConfigLanguage) Quiet() bool { return c.m.Base.Internal.Quiet } func (c ConfigLanguage) Watching() bool { return c.m.Base.Internal.Watch } func (c ConfigLanguage) NewIdentityManager(opts ...identity.ManagerOption) identity.Manager { if !c.Watching() { return identity.NopManager } return identity.NewManager(opts...) } func (c ConfigLanguage) ContentTypes() config.ContentTypesProvider { return c.config.ContentTypes.Config } // 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 { case "security": return c.config.Security case "build": return c.config.Build case "cascade": return c.config.Cascade case "frontmatter": return c.config.Frontmatter case "caches": return c.config.Caches case "markup": return c.config.Markup case "module": return c.config.Module case "mediaTypes": return c.config.MediaTypes.Config case "outputFormats": return c.config.OutputFormats.Config case "roles": return c.config.Roles.Config case "versions": return c.config.Versions.Config case "permalinks": return c.config.Permalinks case "minify": return c.config.Minify case "allModules": return c.m.Modules case "deployment": return c.config.Deployment case "httpCacheCompiled": return c.config.C.HTTPCache default: panic("not implemented: " + s) } } func (c ConfigLanguage) GetConfig() any { return c.config } func (c ConfigLanguage) CanonifyURLs() bool { return c.config.CanonifyURLs } func (c ConfigLanguage) IsUglyURLs(section string) bool { return c.config.C.IsUglyURLSection(section) } func (c ConfigLanguage) IgnoreFile(s string) bool { return c.config.C.IgnoreFile(s) } func (c ConfigLanguage) DisablePathToLower() bool { return c.config.DisablePathToLower } func (c ConfigLanguage) RemovePathAccents() bool { return c.config.RemovePathAccents } func (c ConfigLanguage) DefaultContentLanguage() string { return c.config.DefaultContentLanguage } func (c ConfigLanguage) DefaultContentLanguageInSubdir() bool { return c.config.DefaultContentLanguageInSubdir } func (c ConfigLanguage) DefaultContentRoleInSubdir() bool { return c.config.DefaultContentRoleInSubdir } func (c ConfigLanguage) DefaultContentVersionInSubdir() bool { return c.config.DefaultContentVersionInSubdir } func (c ConfigLanguage) SummaryLength() int { return c.config.SummaryLength } func (c ConfigLanguage) BuildExpired() bool { return c.config.BuildExpired } func (c ConfigLanguage) BuildFuture() bool { return c.config.BuildFuture } func (c ConfigLanguage) BuildDrafts() bool { return c.config.BuildDrafts } func (c ConfigLanguage) Running() bool { return c.config.Internal.Running } func (c ConfigLanguage) PrintUnusedTemplates() bool { return c.config.PrintUnusedTemplates } func (c ConfigLanguage) EnableMissingTranslationPlaceholders() bool { return c.config.EnableMissingTranslationPlaceholders } func (c ConfigLanguage) PrintI18nWarnings() bool { return c.config.PrintI18nWarnings } func (c ConfigLanguage) CreateTitle(s string) string { return c.config.C.CreateTitle(s) } func (c ConfigLanguage) Pagination() config.Pagination { return c.config.Pagination } func (c ConfigLanguage) StaticDirs() []string { return c.config.staticDirs() } func (c ConfigLanguage) EnableEmoji() bool { return c.config.EnableEmoji } func (c ConfigLanguage) ConfiguredDimensions() *sitesmatrix.ConfiguredDimensions { return c.m.ConfiguredDimensions } func (c ConfigLanguage) DefaultContentsitesMatrix() *sitesmatrix.IntSets { return c.m.DefaultContentSitesMatrix } func (c ConfigLanguage) AllSitesMatrix() *sitesmatrix.IntSets { return c.m.AllSitesMatrix }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/allconfig/allconfig.go
config/allconfig/allconfig.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package allconfig contains the full configuration for Hugo. // <docsmeta>{ "name": "Configuration", "description": "This section holds all configuration options in Hugo." }</docsmeta> package allconfig import ( "errors" "fmt" "reflect" "regexp" "slices" "sort" "strconv" "strings" "sync" "time" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/cache/httpcache" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/urls" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/privacy" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/config/services" "github.com/gohugoio/hugo/deploy/deployconfig" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugolib/roles" "github.com/gohugoio/hugo/hugolib/segments" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/hugolib/versions" "github.com/gohugoio/hugo/langs" gc "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/minifiers" "github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/navigation" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/related" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/spf13/afero" ) // InternalConfig is the internal configuration for Hugo, not read from any user provided config file. type InternalConfig struct { // Server mode? Running bool Quiet bool Verbose bool Clock string Watch bool FastRenderMode bool LiveReloadPort int } // All non-params config keys for language. var configLanguageKeys map[string]bool func init() { skip := map[string]bool{ "internal": true, "c": true, "rootconfig": true, } configLanguageKeys = make(map[string]bool) addKeys := func(v reflect.Value) { for i := range v.NumField() { name := strings.ToLower(v.Type().Field(i).Name) if skip[name] { continue } configLanguageKeys[name] = true } } addKeys(reflect.ValueOf(Config{})) addKeys(reflect.ValueOf(RootConfig{})) addKeys(reflect.ValueOf(config.CommonDirs{})) addKeys(reflect.ValueOf(langs.LanguageConfig{})) } type Config struct { // For internal use only. Internal InternalConfig `mapstructure:"-" json:"-"` // For internal use only. C *ConfigCompiled `mapstructure:"-" json:"-"` isLanguageClone bool RootConfig // Author information. // Deprecated: Use taxonomies instead. Author map[string]any // Social links. // Deprecated: Use .Site.Params instead. Social map[string]string // The build configuration section contains build-related configuration options. // <docsmeta>{"identifiers": ["build"] }</docsmeta> Build config.BuildConfig `mapstructure:"-"` // The caches configuration section contains cache-related configuration options. // <docsmeta>{"identifiers": ["caches"] }</docsmeta> Caches filecache.Configs `mapstructure:"-"` // The httpcache configuration section contains HTTP-cache-related configuration options. // <docsmeta>{"identifiers": ["httpcache"] }</docsmeta> HTTPCache httpcache.Config `mapstructure:"-"` // The markup configuration section contains markup-related configuration options. // <docsmeta>{"identifiers": ["markup"] }</docsmeta> Markup markup_config.Config `mapstructure:"-"` // ContentTypes are the media types that's considered content in Hugo. ContentTypes *config.ConfigNamespace[map[string]media.ContentTypeConfig, media.ContentTypes] `mapstructure:"-"` // The mediatypes configuration section maps the MIME type (a string) to a configuration object for that type. // <docsmeta>{"identifiers": ["mediatypes"], "refs": ["types:media:type"] }</docsmeta> MediaTypes *config.ConfigNamespace[map[string]media.MediaTypeConfig, media.Types] `mapstructure:"-"` Imaging *config.ConfigNamespace[images.ImagingConfig, images.ImagingConfigInternal] `mapstructure:"-"` // The outputformats configuration sections maps a format name (a string) to a configuration object for that format. OutputFormats *config.ConfigNamespace[map[string]output.OutputFormatConfig, output.Formats] `mapstructure:"-"` // The languages configuration sections maps a language code (a string) to a configuration object for that language. Languages *config.ConfigNamespace[map[string]langs.LanguageConfig, langs.LanguagesInternal] `mapstructure:"-"` // The versions configuration section contains the top level versions configuration options. Versions *config.ConfigNamespace[map[string]versions.VersionConfig, versions.VersionsInternal] `mapstructure:"-"` // The roles configuration section contains the top level roles configuration options. Roles *config.ConfigNamespace[map[string]roles.RoleConfig, roles.RolesInternal] `mapstructure:"-"` // The outputs configuration section maps a Page Kind (a string) to a slice of output formats. // This can be overridden in the front matter. Outputs map[string][]string `mapstructure:"-"` // The cascade configuration section contains the top level front matter cascade configuration options, // a slice of page matcher and params to apply to those pages. Cascade *page.PageMatcherParamsConfigs `mapstructure:"-"` // The segments defines segments for the site. Used for partial/segmented builds. Segments *config.ConfigNamespace[map[string]segments.SegmentConfig, *segments.Segments] `mapstructure:"-"` // Menu configuration. // <docsmeta>{"refs": ["config:languages:menus"] }</docsmeta> Menus *config.ConfigNamespace[map[string]navigation.MenuConfig, navigation.Menus] `mapstructure:"-"` // The deployment configuration section contains for hugo deployconfig. Deployment deployconfig.DeployConfig `mapstructure:"-"` // Module configuration. Module modules.Config `mapstructure:"-"` // Front matter configuration. Frontmatter pagemeta.FrontmatterConfig `mapstructure:"-"` // Minification configuration. Minify minifiers.MinifyConfig `mapstructure:"-"` // Permalink configuration. Permalinks map[string]map[string]string `mapstructure:"-"` // Taxonomy configuration. Taxonomies map[string]string `mapstructure:"-"` // Sitemap configuration. Sitemap config.SitemapConfig `mapstructure:"-"` // Related content configuration. Related related.Config `mapstructure:"-"` // Server configuration. Server config.Server `mapstructure:"-"` // Pagination configuration. Pagination config.Pagination `mapstructure:"-"` // Page configuration. Page config.PageConfig `mapstructure:"-"` // Privacy configuration. Privacy privacy.Config `mapstructure:"-"` // Security configuration. Security security.Config `mapstructure:"-"` // Services configuration. Services services.Config `mapstructure:"-"` // User provided parameters. // <docsmeta>{"refs": ["config:languages:params"] }</docsmeta> Params maps.Params `mapstructure:"-"` // UglyURLs configuration. Either a boolean or a sections map. UglyURLs any `mapstructure:"-"` } // Early initialization of config. type configCompiler interface { CompileConfig(logger loggers.Logger) error } // Late initialization of config. type configInitializer interface { InitConfig(logger loggers.Logger, defaultSitesMatrix sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions) error } func (c Config) cloneForLang() *Config { x := c x.isLanguageClone = true x.C = nil copyStringSlice := func(in []string) []string { if in == nil { return nil } out := make([]string, len(in)) copy(out, in) return out } // Copy all the slices to avoid sharing. x.DisableKinds = copyStringSlice(x.DisableKinds) x.DisableLanguages = copyStringSlice(x.DisableLanguages) x.MainSections = copyStringSlice(x.MainSections) x.IgnoreLogs = copyStringSlice(x.IgnoreLogs) x.IgnoreFiles = copyStringSlice(x.IgnoreFiles) x.Theme = copyStringSlice(x.Theme) // Collapse all static dirs to one. x.StaticDir = x.staticDirs() // These will go away soon ... x.StaticDir0 = nil x.StaticDir1 = nil x.StaticDir2 = nil x.StaticDir3 = nil x.StaticDir4 = nil x.StaticDir5 = nil x.StaticDir6 = nil x.StaticDir7 = nil x.StaticDir8 = nil x.StaticDir9 = nil x.StaticDir10 = nil return &x } func (c *Config) CompileConfig(logger loggers.Logger) error { var transientErr error s := c.Timeout if _, err := strconv.Atoi(s); err == nil { // A number, assume seconds. s = s + "s" } timeout, err := time.ParseDuration(s) if err != nil { return fmt.Errorf("failed to parse timeout: %s", err) } disabledKinds := make(map[string]bool) for _, kind := range c.DisableKinds { kind = strings.ToLower(kind) if newKind := kinds.IsDeprecatedAndReplacedWith(kind); newKind != "" { logger.Deprecatef(false, "Kind %q used in disableKinds is deprecated, use %q instead.", kind, newKind) // Legacy config. kind = newKind } if kinds.GetKindAny(kind) == "" { logger.Warnf("Unknown kind %q in disableKinds configuration.", kind) continue } disabledKinds[kind] = true } kindOutputFormats := make(map[string]output.Formats) isRssDisabled := disabledKinds["rss"] outputFormats := c.OutputFormats.Config for kind, formats := range c.Outputs { if newKind := kinds.IsDeprecatedAndReplacedWith(kind); newKind != "" { logger.Deprecatef(false, "Kind %q used in outputs configuration is deprecated, use %q instead.", kind, newKind) kind = newKind } if disabledKinds[kind] { continue } if kinds.GetKindAny(kind) == "" { logger.Warnf("Unknown kind %q in outputs configuration.", kind) continue } for _, format := range formats { if isRssDisabled && format == "rss" { // Legacy config. continue } f, found := outputFormats.GetByName(format) if !found { transientErr = fmt.Errorf("unknown output format %q for kind %q", format, kind) continue } kindOutputFormats[kind] = append(kindOutputFormats[kind], f) } } defaultOutputFormat := outputFormats[0] c.DefaultOutputFormat = strings.ToLower(c.DefaultOutputFormat) if c.DefaultOutputFormat != "" { f, found := outputFormats.GetByName(c.DefaultOutputFormat) if !found { return fmt.Errorf("unknown default output format %q", c.DefaultOutputFormat) } defaultOutputFormat = f } else { c.DefaultOutputFormat = defaultOutputFormat.Name } disabledLangs := make(map[string]bool) for _, lang := range c.DisableLanguages { disabledLangs[lang] = true } for i, s := range c.IgnoreLogs { c.IgnoreLogs[i] = strings.ToLower(s) } ignoredLogIDs := make(map[string]bool) for _, err := range c.IgnoreLogs { ignoredLogIDs[err] = true } baseURL, err := urls.NewBaseURLFromString(c.BaseURL) if err != nil { return err } isUglyURL := func(section string) bool { switch v := c.UglyURLs.(type) { case bool: return v case map[string]bool: return v[section] default: return false } } ignoreFile := func(s string) bool { return false } if len(c.IgnoreFiles) > 0 { regexps := make([]*regexp.Regexp, len(c.IgnoreFiles)) for i, pattern := range c.IgnoreFiles { var err error regexps[i], err = regexp.Compile(pattern) if err != nil { return fmt.Errorf("failed to compile ignoreFiles pattern %q: %s", pattern, err) } } ignoreFile = func(s string) bool { for _, r := range regexps { if r.MatchString(s) { return true } } return false } } var clock time.Time if c.Internal.Clock != "" { var err error clock, err = time.Parse(time.RFC3339, c.Internal.Clock) if err != nil { return fmt.Errorf("failed to parse clock: %s", err) } } httpCache, err := c.HTTPCache.Compile() if err != nil { return err } // Legacy paginate values. if c.Paginate != 0 { hugo.DeprecateWithLogger("site config key paginate", "Use pagination.pagerSize instead.", "v0.128.0", logger.Logger()) c.Pagination.PagerSize = c.Paginate } if c.PaginatePath != "" { hugo.DeprecateWithLogger("site config key paginatePath", "Use pagination.path instead.", "v0.128.0", logger.Logger()) c.Pagination.Path = c.PaginatePath } // Legacy privacy values. if c.Privacy.Twitter.Disable { hugo.DeprecateWithLogger("site config key privacy.twitter.disable", "Use privacy.x.disable instead.", "v0.141.0", logger.Logger()) c.Privacy.X.Disable = c.Privacy.Twitter.Disable } if c.Privacy.Twitter.EnableDNT { hugo.DeprecateWithLogger("site config key privacy.twitter.enableDNT", "Use privacy.x.enableDNT instead.", "v0.141.0", logger.Logger()) c.Privacy.X.EnableDNT = c.Privacy.Twitter.EnableDNT } if c.Privacy.Twitter.Simple { hugo.DeprecateWithLogger("site config key privacy.twitter.simple", "Use privacy.x.simple instead.", "v0.141.0", logger.Logger()) c.Privacy.X.Simple = c.Privacy.Twitter.Simple } // Legacy services values. if c.Services.Twitter.DisableInlineCSS { hugo.DeprecateWithLogger("site config key services.twitter.disableInlineCSS", "Use services.x.disableInlineCSS instead.", "v0.141.0", logger.Logger()) c.Services.X.DisableInlineCSS = c.Services.Twitter.DisableInlineCSS } // Legacy permalink tokens vs := fmt.Sprintf("%v", c.Permalinks) if strings.Contains(vs, ":filename") { hugo.DeprecateWithLogger("the \":filename\" permalink token", "Use \":contentbasename\" instead.", "0.144.0", logger.Logger()) } if strings.Contains(vs, ":slugorfilename") { hugo.DeprecateWithLogger("the \":slugorfilename\" permalink token", "Use \":slugorcontentbasename\" instead.", "0.144.0", logger.Logger()) } // Legacy render hook values. alternativeDetails := fmt.Sprintf( "Set to %q if previous value was false, or set to %q if previous value was true.", gc.RenderHookUseEmbeddedNever, gc.RenderHookUseEmbeddedFallback, ) if c.Markup.Goldmark.RenderHooks.Image.EnableDefault != nil { alternative := "Use markup.goldmark.renderHooks.image.useEmbedded instead." + " " + alternativeDetails hugo.DeprecateWithLogger("site config key markup.goldmark.renderHooks.image.enableDefault", alternative, "0.148.0", logger.Logger()) if *c.Markup.Goldmark.RenderHooks.Image.EnableDefault { c.Markup.Goldmark.RenderHooks.Image.UseEmbedded = gc.RenderHookUseEmbeddedFallback } else { c.Markup.Goldmark.RenderHooks.Image.UseEmbedded = gc.RenderHookUseEmbeddedNever } } if c.Markup.Goldmark.RenderHooks.Link.EnableDefault != nil { alternative := "Use markup.goldmark.renderHooks.link.useEmbedded instead." + " " + alternativeDetails hugo.DeprecateWithLogger("site config key markup.goldmark.renderHooks.link.enableDefault", alternative, "0.148.0", logger.Logger()) if *c.Markup.Goldmark.RenderHooks.Link.EnableDefault { c.Markup.Goldmark.RenderHooks.Link.UseEmbedded = gc.RenderHookUseEmbeddedFallback } else { c.Markup.Goldmark.RenderHooks.Link.UseEmbedded = gc.RenderHookUseEmbeddedNever } } // Validate render hook configuration. renderHookUseEmbeddedModes := []string{ gc.RenderHookUseEmbeddedAlways, gc.RenderHookUseEmbeddedAuto, gc.RenderHookUseEmbeddedFallback, gc.RenderHookUseEmbeddedNever, } if !slices.Contains(renderHookUseEmbeddedModes, c.Markup.Goldmark.RenderHooks.Image.UseEmbedded) { return fmt.Errorf("site config markup.goldmark.renderHooks.image.useEmbedded must be one of %s", helpers.StringSliceToList(renderHookUseEmbeddedModes, "or")) } if !slices.Contains(renderHookUseEmbeddedModes, c.Markup.Goldmark.RenderHooks.Link.UseEmbedded) { return fmt.Errorf("site config markup.goldmark.renderHooks.link.useEmbedded must be one of %s", helpers.StringSliceToList(renderHookUseEmbeddedModes, "or")) } c.C = &ConfigCompiled{ Timeout: timeout, BaseURL: baseURL, BaseURLLiveReload: baseURL, DisabledKinds: disabledKinds, DisabledLanguages: disabledLangs, IgnoredLogs: ignoredLogIDs, KindOutputFormats: kindOutputFormats, DefaultOutputFormat: defaultOutputFormat, CreateTitle: helpers.GetTitleFunc(c.TitleCaseStyle), IsUglyURLSection: isUglyURL, IgnoreFile: ignoreFile, MainSections: c.MainSections, Clock: clock, HTTPCache: httpCache, transientErr: transientErr, } for _, s := range allDecoderSetups { if getCompiler := s.getCompiler; getCompiler != nil { if err := getCompiler(c).CompileConfig(logger); err != nil { return err } } } return nil } func (c *Config) IsKindEnabled(kind string) bool { return !c.C.DisabledKinds[kind] } func (c *Config) IsLangDisabled(lang string) bool { return c.C.DisabledLanguages[lang] } // ConfigCompiled holds values and functions that are derived from the config. type ConfigCompiled struct { Timeout time.Duration BaseURL urls.BaseURL BaseURLLiveReload urls.BaseURL ServerInterface string KindOutputFormats map[string]output.Formats DefaultOutputFormat output.Format DisabledKinds map[string]bool DisabledLanguages map[string]bool IgnoredLogs map[string]bool CreateTitle func(s string) string IsUglyURLSection func(section string) bool IgnoreFile func(filename string) bool MainSections []string Clock time.Time HTTPCache httpcache.ConfigCompiled // This is set to the last transient error found during config compilation. // With themes/modules we compute the configuration in multiple passes, and // errors with missing output format definitions may resolve itself. transientErr error mu sync.Mutex } // This may be set after the config is compiled. func (c *ConfigCompiled) SetMainSections(sections []string) { c.mu.Lock() defer c.mu.Unlock() c.MainSections = sections } // IsMainSectionsSet returns whether the main sections have been set. func (c *ConfigCompiled) IsMainSectionsSet() bool { c.mu.Lock() defer c.mu.Unlock() return c.MainSections != nil } // This is set after the config is compiled by the server command. func (c *ConfigCompiled) SetServerInfo(baseURL, baseURLLiveReload urls.BaseURL, serverInterface string) { c.BaseURL = baseURL c.BaseURLLiveReload = baseURLLiveReload c.ServerInterface = serverInterface } // RootConfig holds all the top-level configuration options in Hugo type RootConfig struct { // The base URL of the site. // Note that the default value is empty, but Hugo requires a valid URL (e.g. "https://example.com/") to work properly. // <docsmeta>{"identifiers": ["URL"] }</docsmeta> BaseURL string // Whether to build content marked as draft.X // <docsmeta>{"identifiers": ["draft"] }</docsmeta> BuildDrafts bool // Whether to build content with expiryDate in the past. // <docsmeta>{"identifiers": ["expiryDate"] }</docsmeta> BuildExpired bool // Whether to build content with publishDate in the future. // <docsmeta>{"identifiers": ["publishDate"] }</docsmeta> BuildFuture bool // Copyright information. Copyright string // The language to apply to content without any language indicator. DefaultContentLanguage string // By default, we put the default content language in the root and the others below their language ID, e.g. /no/. // Set this to true to put all languages below their language ID. DefaultContentLanguageInSubdir bool // The default content role to use for the site. DefaultContentRole string // Set this to true to put the default role in a subdirectory. DefaultContentRoleInSubdir bool // The default content version to use for the site. DefaultContentVersion string // Set to true to render the default version in a subdirectory. DefaultContentVersionInSubdir bool // The default output format to use for the site. // If not set, we will use the first output format. DefaultOutputFormat string // Disable generation of redirect to the default language when DefaultContentLanguageInSubdir is enabled. DisableDefaultLanguageRedirect bool // Disable creation of alias redirect pages. DisableAliases bool // Disable lower casing of path segments. DisablePathToLower bool // Disable page kinds from build. DisableKinds []string // A list of languages to disable. DisableLanguages []string // The named segments to render. // This needs to match the name of the segment in the segments configuration. RenderSegments []string // Disable the injection of the Hugo generator tag on the home page. DisableHugoGeneratorInject bool // Disable live reloading in server mode. DisableLiveReload bool // Enable replacement in Pages' Content of Emoji shortcodes with their equivalent Unicode characters. // <docsmeta>{"identifiers": ["Content", "Unicode"] }</docsmeta> EnableEmoji bool // THe main section(s) of the site. // If not set, Hugo will try to guess this from the content. MainSections []string // Enable robots.txt generation. EnableRobotsTXT bool // When enabled, Hugo will apply Git version information to each Page if possible, which // can be used to keep lastUpdated in synch and to print version information. // <docsmeta>{"identifiers": ["Page"] }</docsmeta> EnableGitInfo bool // Enable to track, calculate and print metrics. TemplateMetrics bool // Enable to track, print and calculate metric hints. TemplateMetricsHints bool // Enable to disable the build lock file. NoBuildLock bool // A list of log IDs to ignore. IgnoreLogs []string // A list of regexps that match paths to ignore. // Deprecated: Use the settings on module imports. IgnoreFiles []string // Ignore cache. IgnoreCache bool // Enable to print greppable placeholders (on the form "[i18n] TRANSLATIONID") for missing translation strings. EnableMissingTranslationPlaceholders bool // Enable to panic on warning log entries. This may make it easier to detect the source. PanicOnWarning bool // The configured environment. Default is "development" for server and "production" for build. Environment string // The default language code. LanguageCode string // Enable if the site content has CJK language (Chinese, Japanese, or Korean). This affects how Hugo counts words. HasCJKLanguage bool // The default number of pages per page when paginating. // Deprecated: Use the Pagination struct. Paginate int // The path to use when creating pagination URLs, e.g. "page" in /page/2/. // Deprecated: Use the Pagination struct. PaginatePath string // Whether to pluralize default list titles. // Note that this currently only works for English, but you can provide your own title in the content file's front matter. PluralizeListTitles bool // Whether to capitalize automatic page titles, applicable to section, taxonomy, and term pages. CapitalizeListTitles bool // Make all relative URLs absolute using the baseURL. // <docsmeta>{"identifiers": ["baseURL"] }</docsmeta> CanonifyURLs bool // Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs. RelativeURLs bool // Removes non-spacing marks from composite characters in content paths. RemovePathAccents bool // Whether to track and print unused templates during the build. PrintUnusedTemplates bool // Enable to print warnings for missing translation strings. PrintI18nWarnings bool // ENable to print warnings for multiple files published to the same destination. PrintPathWarnings bool // URL to be used as a placeholder when a page reference cannot be found in ref or relref. Is used as-is. RefLinksNotFoundURL string // When using ref or relref to resolve page links and a link cannot be resolved, it will be logged with this log level. // Valid values are ERROR (default) or WARNING. Any ERROR will fail the build (exit -1). RefLinksErrorLevel string // This will create a menu with all the sections as menu items and all the sections’ pages as “shadow-members”. SectionPagesMenu string // The length of text in words to show in a .Summary. SummaryLength int // The site title. Title string // The theme(s) to use. // See Modules for more a more flexible way to load themes. Theme []string // Timeout for generating page contents, specified as a duration or in seconds. Timeout string // The time zone (or location), e.g. Europe/Oslo, used to parse front matter dates without such information and in the time function. TimeZone string // Set titleCaseStyle to specify the title style used by the title template function and the automatic section titles in Hugo. // It defaults to AP Stylebook for title casing, but you can also set it to Chicago or Go (every word starts with a capital letter). TitleCaseStyle string // The editor used for opening up new content. NewContentEditor string // Don't sync modification time of files for the static mounts. NoTimes bool // Don't sync modification time of files for the static mounts. NoChmod bool // Clean the destination folder before a new build. // This currently only handles static files. CleanDestinationDir bool // A Glob pattern of module paths to ignore in the _vendor folder. IgnoreVendorPaths string config.CommonDirs `mapstructure:",squash"` // The odd constructs below are kept for backwards compatibility. // Deprecated: Use module mount config instead. StaticDir []string // Deprecated: Use module mount config instead. StaticDir0 []string // Deprecated: Use module mount config instead. StaticDir1 []string // Deprecated: Use module mount config instead. StaticDir2 []string // Deprecated: Use module mount config instead. StaticDir3 []string // Deprecated: Use module mount config instead. StaticDir4 []string // Deprecated: Use module mount config instead. StaticDir5 []string // Deprecated: Use module mount config instead. StaticDir6 []string // Deprecated: Use module mount config instead. StaticDir7 []string // Deprecated: Use module mount config instead. StaticDir8 []string // Deprecated: Use module mount config instead. StaticDir9 []string // Deprecated: Use module mount config instead. StaticDir10 []string } func (c RootConfig) staticDirs() []string { var dirs []string dirs = append(dirs, c.StaticDir...) dirs = append(dirs, c.StaticDir0...) dirs = append(dirs, c.StaticDir1...) dirs = append(dirs, c.StaticDir2...) dirs = append(dirs, c.StaticDir3...) dirs = append(dirs, c.StaticDir4...) dirs = append(dirs, c.StaticDir5...) dirs = append(dirs, c.StaticDir6...) dirs = append(dirs, c.StaticDir7...) dirs = append(dirs, c.StaticDir8...) dirs = append(dirs, c.StaticDir9...) dirs = append(dirs, c.StaticDir10...) return hstrings.UniqueStringsReuse(dirs) } type Configs struct { Base *Config LoadingInfo config.LoadConfigResult LanguageConfigMap map[string]*Config IsMultihost bool Modules modules.Modules ModulesClient *modules.Client // All below is set in Init. Languages langs.Languages ContentPathParser *paths.PathParser ConfiguredDimensions *sitesmatrix.ConfiguredDimensions DefaultContentSitesMatrix *sitesmatrix.IntSets AllSitesMatrix *sitesmatrix.IntSets configLangs []config.AllProvider } func (c *Configs) Validate(logger loggers.Logger) error { return nil } // transientErr returns the last transient error found during config compilation. func (c *Configs) transientErr() error { for _, l := range c.LanguageConfigMap { if l.C.transientErr != nil { return l.C.transientErr } } return nil } func (c *Configs) IsZero() bool { // A config always has at least one language. return c == nil || len(c.Languages) == 0 } func (c *Configs) Init(logger loggers.Logger) error { var languages langs.Languages for _, f := range c.Base.Languages.Config.Sorted { v, found := c.LanguageConfigMap[f.Name] if !found { return fmt.Errorf("invalid language configuration for %q", f.Name) } language, err := langs.NewLanguage(f.Name, c.Base.DefaultContentLanguage, v.TimeZone, f.LanguageConfig) if err != nil { return err } languages = append(languages, language) } // Filter out disabled languages. var n int for _, l := range languages { if !l.Disabled { languages[n] = l n++ } } languages = languages[:n] c.Languages = languages c.ConfiguredDimensions = &sitesmatrix.ConfiguredDimensions{ ConfiguredLanguages: c.Base.Languages.Config, ConfiguredVersions: c.Base.Versions.Config, ConfiguredRoles: c.Base.Roles.Config, } if err := c.ConfiguredDimensions.Init(); err != nil { return err } intSetsCfg := sitesmatrix.IntSetsConfig{ ApplyDefaults: sitesmatrix.IntSetsConfigApplyDefaultsIfNotSet, } matrix := sitesmatrix.NewIntSetsBuilder(c.ConfiguredDimensions).WithConfig(intSetsCfg) c.DefaultContentSitesMatrix = matrix.Build() c.AllSitesMatrix = sitesmatrix.NewIntSetsBuilder(c.ConfiguredDimensions).WithAllIfNotSet().Build() c.ContentPathParser = &paths.PathParser{ ConfiguredDimensions: c.ConfiguredDimensions, LanguageIndex: languages.AsIndexSet(), IsLangDisabled: c.Base.IsLangDisabled, IsContentExt: c.Base.ContentTypes.Config.IsContentSuffix, IsOutputFormat: func(name, ext string) bool { if name == "" { return false } if of, ok := c.Base.OutputFormats.Config.GetByName(name); ok { if ext != "" && !of.MediaType.HasSuffix(ext) { return false } return true } return false }, } c.configLangs = make([]config.AllProvider, len(c.Languages)) // Config can be shared between languages, // avoid initializing the same config more than once. for i, l := range c.Languages { langConfig := c.LanguageConfigMap[l.Lang] for _, s := range allDecoderSetups { if getInitializer := s.getInitializer; getInitializer != nil { if err := getInitializer(langConfig).InitConfig(logger, nil, c.ConfiguredDimensions); err != nil { return err } } } c.configLangs[i] = ConfigLanguage{ m: c, config: langConfig, baseConfig: c.LoadingInfo.BaseConfig, language: l, languageIndex: i, } } if len(c.Modules) == 0 { return errors.New("no modules loaded (need at least the main module)") } // Apply default project mounts. if err := modules.ApplyProjectConfigDefaults(logger.Logger(), c.Modules[0], c.configLangs...); err != nil { return err } // We should consolidate this, but to get a full view of the mounts in e.g. "hugo config" we need to // transfer any default mounts added above to the config used to print the config. for _, m := range c.Modules[0].Mounts() { var found bool for _, cm := range c.Base.Module.Mounts { if cm.Equal(m) { found = true break } } if !found { c.Base.Module.Mounts = append(c.Base.Module.Mounts, m) } } // Transfer the changed mounts to the language versions (all share the same mount set, but can be displayed in different languages). for _, l := range c.LanguageConfigMap { l.Module.Mounts = c.Base.Module.Mounts } return nil } func (c Configs) ConfigLangs() []config.AllProvider { return c.configLangs } func (c Configs) GetFirstLanguageConfig() config.AllProvider { return c.configLangs[0] } func (c Configs) GetByLang(lang string) config.AllProvider { for _, l := range c.configLangs { if l.Language().(*langs.Language).Lang == lang { return l } } return nil } func newDefaultConfig() *Config { return &Config{ Taxonomies: map[string]string{"tag": "tags", "category": "categories"}, Sitemap: config.SitemapConfig{Priority: -1, Filename: "sitemap.xml"}, RootConfig: RootConfig{ Environment: hugo.EnvironmentProduction, TitleCaseStyle: "AP", PluralizeListTitles: true, CapitalizeListTitles: true, StaticDir: []string{"static"}, SummaryLength: 70, Timeout: "60s", CommonDirs: config.CommonDirs{ ArcheTypeDir: "archetypes", ContentDir: "content", ResourceDir: "resources", PublishDir: "public",
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/allconfig/load_test.go
config/allconfig/load_test.go
package allconfig import ( "os" "path/filepath" "testing" "github.com/spf13/afero" ) func BenchmarkLoad(b *testing.B) { tempDir := b.TempDir() configFilename := filepath.Join(tempDir, "hugo.toml") config := ` baseURL = "https://example.com" defaultContentLanguage = 'en' [module] [[module.mounts]] source = 'content/en' target = 'content/en' lang = 'en' [[module.mounts]] source = 'content/nn' target = 'content/nn' lang = 'nn' [[module.mounts]] source = 'content/no' target = 'content/no' lang = 'no' [[module.mounts]] source = 'content/sv' target = 'content/sv' lang = 'sv' [[module.mounts]] source = 'layouts' target = 'layouts' [languages] [languages.en] title = "English" weight = 1 [languages.nn] title = "Nynorsk" weight = 2 [languages.no] title = "Norsk" weight = 3 [languages.sv] title = "Svenska" weight = 4 ` if err := os.WriteFile(configFilename, []byte(config), 0o666); err != nil { b.Fatal(err) } d := ConfigSourceDescriptor{ Fs: afero.NewOsFs(), Filename: configFilename, } for b.Loop() { _, err := LoadConfig(d) if err != nil { b.Fatal(err) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/allconfig/docshelper.go
config/allconfig/docshelper.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package allconfig import ( "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/docshelper" ) // This is is just some helpers used to create some JSON used in the Hugo docs. func init() { docsProvider := func() docshelper.DocProvider { cfg := config.New() for configRoot, v := range allDecoderSetups { if v.internalOrDeprecated { continue } cfg.Set(configRoot, make(maps.Params)) } lang := maps.Params{ "en": maps.Params{ "menus": maps.Params{}, "params": maps.Params{}, }, } cfg.Set("languages", lang) cfg.SetDefaultMergeStrategy() configHelpers := map[string]any{ "mergeStrategy": cfg.Get(""), } return docshelper.DocProvider{"config_helpers": configHelpers} } docshelper.AddDocProviderFunc(docsProvider) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/security/securityConfig.go
config/security/securityConfig.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package security import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/mitchellh/mapstructure" ) const securityConfigKey = "security" // DefaultConfig holds the default security policy. var DefaultConfig = Config{ Exec: Exec{ Allow: MustNewWhitelist( "^(dart-)?sass(-embedded)?$", // sass, dart-sass, dart-sass-embedded. "^go$", // for Go Modules "^git$", // For Git info "^npx$", // used by all Node tools (Babel, PostCSS). "^postcss$", "^tailwindcss$", ), // These have been tested to work with Hugo's external programs // on Windows, Linux and MacOS. OsEnv: MustNewWhitelist(`(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|SYSTEMDRIVE|PROGRAMDATA)$`), }, Funcs: Funcs{ Getenv: MustNewWhitelist("^HUGO_", "^CI$"), }, HTTP: HTTP{ URLs: MustNewWhitelist(".*"), Methods: MustNewWhitelist("(?i)GET|POST"), }, } // Config is the top level security config. // <docsmeta>{"name": "security", "description": "This section holds the top level security config.", "newIn": "0.91.0" }</docsmeta> type Config struct { // Restricts access to os.Exec.... // <docsmeta>{ "newIn": "0.91.0" }</docsmeta> Exec Exec `json:"exec"` // Restricts access to certain template funcs. Funcs Funcs `json:"funcs"` // Restricts access to resources.GetRemote, getJSON, getCSV. HTTP HTTP `json:"http"` // Allow inline shortcodes EnableInlineShortcodes bool `json:"enableInlineShortcodes"` } // Exec holds os/exec policies. type Exec struct { Allow Whitelist `json:"allow"` OsEnv Whitelist `json:"osEnv"` } // Funcs holds template funcs policies. type Funcs struct { // OS env keys allowed to query in os.Getenv. Getenv Whitelist `json:"getenv"` } type HTTP struct { // URLs to allow in remote HTTP (resources.Get, getJSON, getCSV). URLs Whitelist `json:"urls"` // HTTP methods to allow. Methods Whitelist `json:"methods"` // Media types where the Content-Type in the response is used instead of resolving from the file content. MediaTypes Whitelist `json:"mediaTypes"` } // ToTOML converts c to TOML with [security] as the root. func (c Config) ToTOML() string { sec := c.ToSecurityMap() var b bytes.Buffer if err := parser.InterfaceToConfig(sec, metadecoders.TOML, &b); err != nil { panic(err) } return strings.TrimSpace(b.String()) } func (c Config) CheckAllowedExec(name string) error { if !c.Exec.Allow.Accept(name) { return &AccessDeniedError{ name: name, path: "security.exec.allow", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedGetEnv(name string) error { if !c.Funcs.Getenv.Accept(name) { return &AccessDeniedError{ name: name, path: "security.funcs.getenv", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPURL(url string) error { if !c.HTTP.URLs.Accept(url) { return &AccessDeniedError{ name: url, path: "security.http.urls", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPMethod(method string) error { if !c.HTTP.Methods.Accept(method) { return &AccessDeniedError{ name: method, path: "security.http.method", policies: c.ToTOML(), } } return nil } // ToSecurityMap converts c to a map with 'security' as the root key. func (c Config) ToSecurityMap() map[string]any { // Take it to JSON and back to get proper casing etc. asJson, err := json.Marshal(c) herrors.Must(err) m := make(map[string]any) herrors.Must(json.Unmarshal(asJson, &m)) // Add the root sec := map[string]any{ "security": m, } return sec } // DecodeConfig creates a privacy Config from a given Hugo configuration. func DecodeConfig(cfg config.Provider) (Config, error) { sc := DefaultConfig if cfg.IsSet(securityConfigKey) { m := cfg.GetStringMap(securityConfigKey) dec, err := mapstructure.NewDecoder( &mapstructure.DecoderConfig{ WeaklyTypedInput: true, Result: &sc, DecodeHook: stringSliceToWhitelistHook(), }, ) if err != nil { return sc, err } if err = dec.Decode(m); err != nil { return sc, err } } if !sc.EnableInlineShortcodes { // Legacy sc.EnableInlineShortcodes = cfg.GetBool("enableInlineShortcodes") } return sc, nil } func stringSliceToWhitelistHook() mapstructure.DecodeHookFuncType { return func( f reflect.Type, t reflect.Type, data any, ) (any, error) { if t != reflect.TypeOf(Whitelist{}) { return data, nil } wl := types.ToStringSlicePreserveString(data) return NewWhitelist(wl...) } } // AccessDeniedError represents a security policy conflict. type AccessDeniedError struct { path string name string policies string } func (e *AccessDeniedError) Error() string { return fmt.Sprintf("access denied: %q is not whitelisted in policy %q; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.policies) } // IsAccessDenied reports whether err is an AccessDeniedError func IsAccessDenied(err error) bool { var notFoundErr *AccessDeniedError return errors.As(err, &notFoundErr) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/security/whitelist.go
config/security/whitelist.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package security import ( "encoding/json" "fmt" "regexp" "strings" ) const ( acceptNoneKeyword = "none" ) // Whitelist holds a whitelist. type Whitelist struct { acceptNone bool patterns []*regexp.Regexp // Store this for debugging/error reporting patternsStrings []string } // MarshalJSON is for internal use only. func (w Whitelist) MarshalJSON() ([]byte, error) { if w.acceptNone { return json.Marshal(acceptNoneKeyword) } return json.Marshal(w.patternsStrings) } // NewWhitelist creates a new Whitelist from zero or more patterns. // An empty patterns list or a pattern with the value 'none' will create // a whitelist that will Accept none. func NewWhitelist(patterns ...string) (Whitelist, error) { if len(patterns) == 0 { return Whitelist{acceptNone: true}, nil } var acceptSome bool var patternsStrings []string for _, p := range patterns { if p == acceptNoneKeyword { acceptSome = false break } if ps := strings.TrimSpace(p); ps != "" { acceptSome = true patternsStrings = append(patternsStrings, ps) } } if !acceptSome { return Whitelist{ acceptNone: true, }, nil } var patternsr []*regexp.Regexp for i := range patterns { p := strings.TrimSpace(patterns[i]) if p == "" { continue } re, err := regexp.Compile(p) if err != nil { return Whitelist{}, fmt.Errorf("failed to compile whitelist pattern %q: %w", p, err) } patternsr = append(patternsr, re) } return Whitelist{patterns: patternsr, patternsStrings: patternsStrings}, nil } // MustNewWhitelist creates a new Whitelist from zero or more patterns and panics on error. func MustNewWhitelist(patterns ...string) Whitelist { w, err := NewWhitelist(patterns...) if err != nil { panic(err) } return w } // Accept reports whether name is whitelisted. func (w Whitelist) Accept(name string) bool { if w.acceptNone { return false } for _, p := range w.patterns { if p.MatchString(name) { return true } } return false } func (w Whitelist) String() string { return fmt.Sprint(w.patternsStrings) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/security/securityConfig_test.go
config/security/securityConfig_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package security import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" ) func TestDecodeConfigFromTOML(t *testing.T) { c := qt.New(t) c.Run("Slice whitelist", func(c *qt.C) { c.Parallel() tomlConfig := ` someOtherValue = "bar" [security] enableInlineShortcodes=true [security.exec] allow=["a", "b"] osEnv=["a", "b", "c"] [security.funcs] getEnv=["a", "b"] ` cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) pc, err := DecodeConfig(cfg) c.Assert(err, qt.IsNil) c.Assert(pc, qt.Not(qt.IsNil)) c.Assert(pc.EnableInlineShortcodes, qt.IsTrue) c.Assert(pc.Exec.Allow.Accept("a"), qt.IsTrue) c.Assert(pc.Exec.Allow.Accept("d"), qt.IsFalse) c.Assert(pc.Exec.OsEnv.Accept("a"), qt.IsTrue) c.Assert(pc.Exec.OsEnv.Accept("e"), qt.IsFalse) c.Assert(pc.Funcs.Getenv.Accept("a"), qt.IsTrue) c.Assert(pc.Funcs.Getenv.Accept("c"), qt.IsFalse) }) c.Run("String whitelist", func(c *qt.C) { c.Parallel() tomlConfig := ` someOtherValue = "bar" [security] [security.exec] allow="a" osEnv="b" ` cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) pc, err := DecodeConfig(cfg) c.Assert(err, qt.IsNil) c.Assert(pc, qt.Not(qt.IsNil)) c.Assert(pc.Exec.Allow.Accept("a"), qt.IsTrue) c.Assert(pc.Exec.Allow.Accept("d"), qt.IsFalse) c.Assert(pc.Exec.OsEnv.Accept("b"), qt.IsTrue) c.Assert(pc.Exec.OsEnv.Accept("e"), qt.IsFalse) }) c.Run("Default exec.osEnv", func(c *qt.C) { c.Parallel() tomlConfig := ` someOtherValue = "bar" [security] [security.exec] allow="a" ` cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) pc, err := DecodeConfig(cfg) c.Assert(err, qt.IsNil) c.Assert(pc, qt.Not(qt.IsNil)) c.Assert(pc.Exec.Allow.Accept("a"), qt.IsTrue) c.Assert(pc.Exec.OsEnv.Accept("PATH"), qt.IsTrue) c.Assert(pc.Exec.OsEnv.Accept("e"), qt.IsFalse) }) c.Run("Enable inline shortcodes, legacy", func(c *qt.C) { c.Parallel() tomlConfig := ` someOtherValue = "bar" enableInlineShortcodes=true [security] [security.exec] allow="a" osEnv="b" ` cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) pc, err := DecodeConfig(cfg) c.Assert(err, qt.IsNil) c.Assert(pc.EnableInlineShortcodes, qt.IsTrue) }) } func TestToTOML(t *testing.T) { c := qt.New(t) got := DefaultConfig.ToTOML() c.Assert(got, qt.Equals, "[security]\n enableInlineShortcodes = false\n\n [security.exec]\n allow = ['^(dart-)?sass(-embedded)?$', '^go$', '^git$', '^npx$', '^postcss$', '^tailwindcss$']\n osEnv = ['(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|SYSTEMDRIVE|PROGRAMDATA)$']\n\n [security.funcs]\n getenv = ['^HUGO_', '^CI$']\n\n [security.http]\n methods = ['(?i)GET|POST']\n urls = ['.*']", ) } func TestDecodeConfigDefault(t *testing.T) { t.Parallel() c := qt.New(t) pc, err := DecodeConfig(config.New()) c.Assert(err, qt.IsNil) c.Assert(pc, qt.Not(qt.IsNil)) c.Assert(pc.Exec.Allow.Accept("a"), qt.IsFalse) c.Assert(pc.Exec.Allow.Accept("npx"), qt.IsTrue) c.Assert(pc.Exec.Allow.Accept("Npx"), qt.IsFalse) c.Assert(pc.HTTP.URLs.Accept("https://example.org"), qt.IsTrue) c.Assert(pc.HTTP.Methods.Accept("POST"), qt.IsTrue) c.Assert(pc.HTTP.Methods.Accept("GET"), qt.IsTrue) c.Assert(pc.HTTP.Methods.Accept("get"), qt.IsTrue) c.Assert(pc.HTTP.Methods.Accept("DELETE"), qt.IsFalse) c.Assert(pc.HTTP.MediaTypes.Accept("application/msword"), qt.IsFalse) c.Assert(pc.Exec.OsEnv.Accept("PATH"), qt.IsTrue) c.Assert(pc.Exec.OsEnv.Accept("GOROOT"), qt.IsTrue) c.Assert(pc.Exec.OsEnv.Accept("HOME"), qt.IsTrue) c.Assert(pc.Exec.OsEnv.Accept("SSH_AUTH_SOCK"), qt.IsTrue) c.Assert(pc.Exec.OsEnv.Accept("a"), qt.IsFalse) c.Assert(pc.Exec.OsEnv.Accept("e"), qt.IsFalse) c.Assert(pc.Exec.OsEnv.Accept("MYSECRET"), qt.IsFalse) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/security/whitelist_test.go
config/security/whitelist_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package security import ( "testing" qt "github.com/frankban/quicktest" ) func TestWhitelist(t *testing.T) { t.Parallel() c := qt.New(t) c.Run("none", func(c *qt.C) { c.Assert(MustNewWhitelist("none", "foo").Accept("foo"), qt.IsFalse) c.Assert(MustNewWhitelist().Accept("foo"), qt.IsFalse) c.Assert(MustNewWhitelist("").Accept("foo"), qt.IsFalse) c.Assert(MustNewWhitelist(" ", " ").Accept("foo"), qt.IsFalse) c.Assert(Whitelist{}.Accept("foo"), qt.IsFalse) }) c.Run("One", func(c *qt.C) { w := MustNewWhitelist("^foo.*") c.Assert(w.Accept("foo"), qt.IsTrue) c.Assert(w.Accept("mfoo"), qt.IsFalse) }) c.Run("Multiple", func(c *qt.C) { w := MustNewWhitelist("^foo.*", "^bar.*") c.Assert(w.Accept("foo"), qt.IsTrue) c.Assert(w.Accept("bar"), qt.IsTrue) c.Assert(w.Accept("mbar"), qt.IsFalse) }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/create/content_test.go
create/content_test.go
// Copyright 2016 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package create_test import ( "fmt" "os" "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/allconfig" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/hugofs" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/spf13/afero" ) // TODO(bep) clean this up. Export the test site builder in Hugolib or something. func TestNewContentFromFile(t *testing.T) { cases := []struct { name string kind string path string expected any }{ {"Post", "post", "post/sample-1.md", []string{`title = "Post Arch title"`, `test = "test1"`, "date = \"2015-01-12T19:20:04-07:00\""}}, {"Post org-mode", "post", "post/org-1.org", []string{`#+title: ORG-1`}}, {"Post, unknown content filetype", "post", "post/sample-1.pdoc", false}, {"Empty date", "emptydate", "post/sample-ed.md", []string{`title = "Empty Date Arch title"`, `test = "test1"`}}, {"Archetype file not found", "stump", "stump/sample-2.md", []string{`title: "Sample 2"`}}, // no archetype file {"No archetype", "", "sample-3.md", []string{`title: "Sample 3"`}}, // no archetype {"Empty archetype", "product", "product/sample-4.md", []string{`title = "SAMPLE-4"`}}, // empty archetype front matter {"Filenames", "filenames", "content/mypage/index.md", []string{"title = \"INDEX\"\n+++\n\n\nContentBaseName: mypage"}}, {"Branch Name", "name", "content/tags/tag-a/_index.md", []string{"+++\ntitle = 'Tag A'\n+++"}}, {"Lang 1", "lang", "post/lang-1.md", []string{`Site Lang: en|Name: Lang 1|i18n: Hugo Rocks!`}}, {"Lang 2", "lang", "post/lang-2.en.md", []string{`Site Lang: en|Name: Lang 2|i18n: Hugo Rocks!`}}, {"Lang nn file", "lang", "content/post/lang-3.nn.md", []string{`Site Lang: nn|Name: Lang 3|i18n: Hugo Rokkar!`}}, {"Lang nn dir", "lang", "content_nn/post/lang-4.md", []string{`Site Lang: nn|Name: Lang 4|i18n: Hugo Rokkar!`}}, {"Lang en in nn dir", "lang", "content_nn/post/lang-5.en.md", []string{`Site Lang: en|Name: Lang 5|i18n: Hugo Rocks!`}}, {"Lang en default", "lang", "post/my-bundle/index.md", []string{`Site Lang: en|Name: My Bundle|i18n: Hugo Rocks!`}}, {"Lang en file", "lang", "post/my-bundle/index.en.md", []string{`Site Lang: en|Name: My Bundle|i18n: Hugo Rocks!`}}, {"Lang nn bundle", "lang", "content/post/my-bundle/index.nn.md", []string{`Site Lang: nn|Name: My Bundle|i18n: Hugo Rokkar!`}}, {"Site", "site", "content/mypage/index.md", []string{"RegularPages .Site: 10", "RegularPages site: 10"}}, {"Shortcodes", "shortcodes", "shortcodes/go.md", []string{ `title = "GO"`, "{{< myshortcode >}}", "{{% myshortcode %}}", "{{</* comment */>}}\n{{%/* comment */%}}", }}, // shortcodes } c := qt.New(t) for i, cas := range cases { c.Run(cas.name, func(c *qt.C) { c.Parallel() mm := afero.NewMemMapFs() c.Assert(initFs(mm), qt.IsNil) cfg, fs := newTestCfg(c, mm) conf := testconfig.GetTestConfigs(fs.Source, cfg) h, err := hugolib.NewHugoSites(deps.DepsCfg{Configs: conf, Fs: fs}) c.Assert(err, qt.IsNil) err = create.NewContent(h, cas.kind, cas.path, false) if b, ok := cas.expected.(bool); ok && !b { if !b { c.Assert(err, qt.Not(qt.IsNil)) } return } c.Assert(err, qt.IsNil) fname := filepath.FromSlash(cas.path) if !strings.HasPrefix(fname, "content") { fname = filepath.Join("content", fname) } content := readFileFromFs(c, fs.Source, fname) for _, v := range cas.expected.([]string) { found := strings.Contains(content, v) if !found { c.Fatalf("[%d] %q missing from output:\n%q", i, v, content) } } }) } } func TestNewContentFromDirSiteFunction(t *testing.T) { mm := afero.NewMemMapFs() c := qt.New(t) archetypeDir := filepath.Join("archetypes", "my-bundle") defaultArchetypeDir := filepath.Join("archetypes", "default") c.Assert(mm.MkdirAll(archetypeDir, 0o755), qt.IsNil) c.Assert(mm.MkdirAll(defaultArchetypeDir, 0o755), qt.IsNil) contentFile := ` File: %s site RegularPages: {{ len site.RegularPages }} ` c.Assert(afero.WriteFile(mm, filepath.Join(archetypeDir, "index.md"), fmt.Appendf(nil, contentFile, "index.md"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(mm, filepath.Join(defaultArchetypeDir, "index.md"), []byte("default archetype index.md"), 0o755), qt.IsNil) c.Assert(initFs(mm), qt.IsNil) cfg, fs := newTestCfg(c, mm) conf := testconfig.GetTestConfigs(fs.Source, cfg) h := func() *hugolib.HugoSites { h, err := hugolib.NewHugoSites(deps.DepsCfg{Configs: conf, Fs: fs}) c.Assert(err, qt.IsNil) c.Assert(len(h.Sites), qt.Equals, 2) return h } c.Assert(create.NewContent(h(), "my-bundle", "post/my-post", false), qt.IsNil) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/index.md")), `site RegularPages: 10`) // Default bundle archetype c.Assert(create.NewContent(h(), "", "post/my-post2", false), qt.IsNil) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post2/index.md")), `default archetype index.md`) // Regular file with bundle kind. c.Assert(create.NewContent(h(), "my-bundle", "post/foo.md", false), qt.IsNil) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/foo.md")), `draft: true`) // Regular files should fall back to the default archetype (we have no regular file archetype). c.Assert(create.NewContent(h(), "my-bundle", "mypage.md", false), qt.IsNil) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "mypage.md")), `draft: true`) } func initFs(fs afero.Fs) error { perm := os.FileMode(0o755) var err error // create directories dirs := []string{ "archetypes", "content", filepath.Join("themes", "sample", "archetypes"), } for _, dir := range dirs { err = fs.Mkdir(dir, perm) if err != nil && !os.IsExist(err) { return err } } // create some dummy content for i := 1; i <= 10; i++ { filename := filepath.Join("content", fmt.Sprintf("page%d.md", i)) afero.WriteFile(fs, filename, []byte(`--- title: Test --- `), 0o666) } // create archetype files for _, v := range []struct { path string content string }{ { path: filepath.Join("archetypes", "post.md"), content: "+++\ndate = \"2015-01-12T19:20:04-07:00\"\ntitle = \"Post Arch title\"\ntest = \"test1\"\n+++\n", }, { path: filepath.Join("archetypes", "post.org"), content: "#+title: {{ .BaseFileName | upper }}", }, { path: filepath.Join("archetypes", "name.md"), content: `+++ title = '{{ replace .Name "-" " " | title }}' +++`, }, { path: filepath.Join("archetypes", "product.md"), content: `+++ title = "{{ .BaseFileName | upper }}" +++`, }, { path: filepath.Join("archetypes", "filenames.md"), content: `... title = "{{ .BaseFileName | upper }}" +++ ContentBaseName: {{ .File.ContentBaseName }} `, }, { path: filepath.Join("archetypes", "site.md"), content: `... title = "{{ .BaseFileName | upper }}" +++ Len RegularPages .Site: {{ len .Site.RegularPages }} Len RegularPages site: {{ len site.RegularPages }} `, }, { path: filepath.Join("archetypes", "emptydate.md"), content: "+++\ndate =\"\"\ntitle = \"Empty Date Arch title\"\ntest = \"test1\"\n+++\n", }, { path: filepath.Join("archetypes", "lang.md"), content: `Site Lang: {{ site.Language.Lang }}|Name: {{ replace .Name "-" " " | title }}|i18n: {{ T "hugo" }}`, }, // #3623x { path: filepath.Join("archetypes", "shortcodes.md"), content: `+++ title = "{{ .BaseFileName | upper }}" +++ {{< myshortcode >}} Some text. {{% myshortcode %}} {{</* comment */>}} {{%/* comment */%}} `, }, } { f, err := fs.Create(v.path) if err != nil { return err } defer f.Close() _, err = f.Write([]byte(v.content)) if err != nil { return err } } return nil } func cContains(c *qt.C, v any, matches ...string) { for _, m := range matches { c.Assert(v, qt.Contains, m) } } // TODO(bep) extract common testing package with this and some others func readFileFromFs(t testing.TB, fs afero.Fs, filename string) string { t.Helper() filename = filepath.FromSlash(filename) b, err := afero.ReadFile(fs, filename) if err != nil { // Print some debug info root := strings.Split(filename, helpers.FilePathSeparator)[0] afero.Walk(fs, root, func(path string, info os.FileInfo, err error) error { if info != nil && !info.IsDir() { fmt.Println(" ", path) } return nil }) t.Fatalf("Failed to read file: %s", err) } return string(b) } func newTestCfg(c *qt.C, mm afero.Fs) (config.Provider, *hugofs.Fs) { cfg := ` theme = "mytheme" [languages] [languages.en] weight = 1 languageName = "English" [languages.nn] weight = 2 languageName = "Nynorsk" [module] [[module.mounts]] source = 'archetypes' target = 'archetypes' [[module.mounts]] source = 'content' target = 'content' lang = 'en' [[module.mounts]] source = 'content_nn' target = 'content' lang = 'nn' ` if mm == nil { mm = afero.NewMemMapFs() } mm.MkdirAll(filepath.FromSlash("content_nn"), 0o777) mm.MkdirAll(filepath.FromSlash("themes/mytheme"), 0o777) c.Assert(afero.WriteFile(mm, filepath.Join("i18n", "en.toml"), []byte(`[hugo] other = "Hugo Rocks!"`), 0o755), qt.IsNil) c.Assert(afero.WriteFile(mm, filepath.Join("i18n", "nn.toml"), []byte(`[hugo] other = "Hugo Rokkar!"`), 0o755), qt.IsNil) c.Assert(afero.WriteFile(mm, "config.toml", []byte(cfg), 0o755), qt.IsNil) res, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Fs: mm, Filename: "config.toml"}) c.Assert(err, qt.IsNil) return res.LoadingInfo.Cfg, hugofs.NewFrom(mm, res.LoadingInfo.BaseConfig) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/create/content.go
create/content.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package create provides functions to create new content. package create import ( "bytes" "context" "errors" "fmt" "io" "os" "path/filepath" "strings" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugolib" "github.com/spf13/afero" ) const ( // DefaultArchetypeTemplateTemplate is the template used in 'hugo new site' // and the template we use as a fall back. DefaultArchetypeTemplateTemplate = `--- title: "{{ replace .File.ContentBaseName "-" " " | title }}" date: {{ .Date }} draft: true --- ` ) // NewContent creates a new content file in h (or a full bundle if the archetype is a directory) // in targetPath. func NewContent(h *hugolib.HugoSites, kind, targetPath string, force bool) error { if _, err := h.BaseFs.Content.Fs.Stat(""); err != nil { return errors.New("no existing content directory configured for this project") } cf := hugolib.NewContentFactory(h) if kind == "" { var err error kind, err = cf.SectionFromFilename(targetPath) if err != nil { return err } } b := &contentBuilder{ archeTypeFs: h.PathSpec.BaseFs.Archetypes.Fs, sourceFs: h.PathSpec.Fs.Source, ps: h.PathSpec, h: h, cf: cf, kind: kind, targetPath: targetPath, force: force, } ext := paths.Ext(targetPath) b.setArcheTypeFilenameToUse(ext) withBuildLock := func() (string, error) { if !h.Configs.Base.NoBuildLock { unlock, err := h.BaseFs.LockBuild() if err != nil { return "", fmt.Errorf("failed to acquire a build lock: %s", err) } defer unlock() } if b.isDir { return "", b.buildDir() } if ext == "" { return "", fmt.Errorf("failed to resolve %q to an archetype template", targetPath) } if !h.Conf.ContentTypes().IsContentFile(b.targetPath) { return "", fmt.Errorf("target path %q is not a known content format", b.targetPath) } return b.buildFile() } filename, err := withBuildLock() if err != nil { return err } if filename != "" { return b.openInEditorIfConfigured(filename) } return nil } type contentBuilder struct { archeTypeFs afero.Fs sourceFs afero.Fs ps *helpers.PathSpec h *hugolib.HugoSites cf hugolib.ContentFactory // Builder state archetypeFi hugofs.FileMetaInfo targetPath string kind string isDir bool dirMap archetypeMap force bool } func (b *contentBuilder) buildDir() error { // Split the dir into content files and the rest. if err := b.mapArcheTypeDir(); err != nil { return err } var contentTargetFilenames []string var baseDir string for _, fi := range b.dirMap.contentFiles { targetFilename := filepath.Join(b.targetPath, strings.TrimPrefix(fi.Meta().PathInfo.Path(), b.archetypeFi.Meta().PathInfo.Path())) // ===> post/my-post/pages/bio.md abs, err := b.cf.CreateContentPlaceHolder(targetFilename, b.force) if err != nil { return err } if baseDir == "" { baseDir = strings.TrimSuffix(abs, targetFilename) } contentTargetFilenames = append(contentTargetFilenames, abs) } var contentInclusionFilter *hglob.FilenameFilter if !b.dirMap.siteUsed { // We don't need to build everything. contentInclusionFilter = hglob.NewFilenameFilterForInclusionFunc(func(filename string) bool { filename = strings.TrimPrefix(filename, string(os.PathSeparator)) for _, cn := range contentTargetFilenames { if strings.Contains(cn, filename) { return true } } return false }) } if err := b.h.Build(hugolib.BuildCfg{NoBuildLock: true, SkipRender: true, ContentInclusionFilter: contentInclusionFilter}); err != nil { return err } for i, filename := range contentTargetFilenames { if err := b.applyArcheType(filename, b.dirMap.contentFiles[i]); err != nil { return err } } // Copy the rest as is. for _, fi := range b.dirMap.otherFiles { meta := fi.Meta() in, err := meta.Open() if err != nil { return fmt.Errorf("failed to open non-content file: %w", err) } targetFilename := filepath.Join(baseDir, b.targetPath, strings.TrimPrefix(fi.Meta().Filename, b.archetypeFi.Meta().Filename)) targetDir := filepath.Dir(targetFilename) if err := b.sourceFs.MkdirAll(targetDir, 0o777); err != nil && !os.IsExist(err) { return fmt.Errorf("failed to create target directory for %q: %w", targetDir, err) } out, err := b.sourceFs.Create(targetFilename) if err != nil { return err } _, err = io.Copy(out, in) if err != nil { return err } in.Close() out.Close() } b.h.Log.Printf("Content dir %q created", filepath.Join(baseDir, b.targetPath)) return nil } func (b *contentBuilder) buildFile() (string, error) { contentPlaceholderAbsFilename, err := b.cf.CreateContentPlaceHolder(b.targetPath, b.force) if err != nil { return "", err } usesSite, err := b.usesSiteVar(b.archetypeFi) if err != nil { return "", err } var contentInclusionFilter *hglob.FilenameFilter if !usesSite { // We don't need to build everything. contentInclusionFilter = hglob.NewFilenameFilterForInclusionFunc(func(filename string) bool { filename = strings.TrimPrefix(filename, string(os.PathSeparator)) return strings.Contains(contentPlaceholderAbsFilename, filename) }) } if err := b.h.Build(hugolib.BuildCfg{NoBuildLock: true, SkipRender: true, ContentInclusionFilter: contentInclusionFilter}); err != nil { return "", err } if err := b.applyArcheType(contentPlaceholderAbsFilename, b.archetypeFi); err != nil { return "", err } b.h.Log.Printf("Content %q created", contentPlaceholderAbsFilename) return contentPlaceholderAbsFilename, nil } func (b *contentBuilder) setArcheTypeFilenameToUse(ext string) { var pathsToCheck []string if b.kind != "" { pathsToCheck = append(pathsToCheck, b.kind+ext) } pathsToCheck = append(pathsToCheck, "default"+ext) for _, p := range pathsToCheck { fi, err := b.archeTypeFs.Stat(p) if err == nil { b.archetypeFi = fi.(hugofs.FileMetaInfo) b.isDir = fi.IsDir() return } } } func (b *contentBuilder) applyArcheType(contentFilename string, archetypeFi hugofs.FileMetaInfo) error { p := b.h.GetContentPage(contentFilename) if p == nil { panic(fmt.Sprintf("[BUG] no Page found for %q", contentFilename)) } f, err := b.sourceFs.Create(contentFilename) if err != nil { return err } defer f.Close() if archetypeFi == nil { return b.cf.ApplyArchetypeTemplate(f, p, b.kind, DefaultArchetypeTemplateTemplate) } return b.cf.ApplyArchetypeFi(f, p, b.kind, archetypeFi) } func (b *contentBuilder) mapArcheTypeDir() error { var m archetypeMap walkFn := func(ctx context.Context, path string, fim hugofs.FileMetaInfo) error { if fim.IsDir() { return nil } pi := fim.Meta().PathInfo if pi.IsContent() { m.contentFiles = append(m.contentFiles, fim) if !m.siteUsed { var err error m.siteUsed, err = b.usesSiteVar(fim) if err != nil { return err } } return nil } m.otherFiles = append(m.otherFiles, fim) return nil } walkCfg := hugofs.WalkwayConfig{ WalkFn: walkFn, Fs: b.archeTypeFs, Root: filepath.FromSlash(b.archetypeFi.Meta().PathInfo.Path()), } w := hugofs.NewWalkway(walkCfg) if err := w.Walk(); err != nil { return fmt.Errorf("failed to walk archetype dir %q: %w", b.archetypeFi.Meta().Filename, err) } b.dirMap = m return nil } func (b *contentBuilder) openInEditorIfConfigured(filename string) error { editor := b.h.Conf.NewContentEditor() if editor == "" { return nil } editorExec := strings.Fields(editor)[0] editorFlags := strings.Fields(editor)[1:] var args []any for _, editorFlag := range editorFlags { args = append(args, editorFlag) } args = append( args, filename, hexec.WithStdin(os.Stdin), hexec.WithStderr(os.Stderr), hexec.WithStdout(os.Stdout), ) b.h.Log.Printf("Editing %q with %q ...\n", filename, editorExec) cmd, err := b.h.Deps.ExecHelper.New(editorExec, args...) if err != nil { return err } return cmd.Run() } func (b *contentBuilder) usesSiteVar(fi hugofs.FileMetaInfo) (bool, error) { if fi == nil { return false, nil } f, err := fi.Meta().Open() if err != nil { return false, err } defer f.Close() bb, err := io.ReadAll(f) if err != nil { return false, fmt.Errorf("failed to read archetype file: %w", err) } return bytes.Contains(bb, []byte(".Site")) || bytes.Contains(bb, []byte("site.")), nil } type archetypeMap struct { // These needs to be parsed and executed as Go templates. contentFiles []hugofs.FileMetaInfo // These are just copied to destination. otherFiles []hugofs.FileMetaInfo // If the templates needs a fully built site. This can potentially be // expensive, so only do when needed. siteUsed bool }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/create/skeletons/skeletons.go
create/skeletons/skeletons.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package skeletons import ( "bytes" "embed" "errors" "io/fs" "path/filepath" "strings" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/afero" ) //go:embed all:site/* var siteFs embed.FS //go:embed all:theme/* var themeFs embed.FS // CreateTheme creates a theme skeleton. func CreateTheme(createpath string, sourceFs afero.Fs, format string) error { if exists, _ := helpers.Exists(createpath, sourceFs); exists { return errors.New(createpath + " already exists") } format = strings.ToLower(format) siteConfig := map[string]any{ "baseURL": "https://example.org/", "languageCode": "en-US", "title": "My New Hugo Site", "menus": map[string]any{ "main": []any{ map[string]any{ "name": "Home", "pageRef": "/", "weight": 10, }, map[string]any{ "name": "Posts", "pageRef": "/posts", "weight": 20, }, map[string]any{ "name": "Tags", "pageRef": "/tags", "weight": 30, }, }, }, "module": map[string]any{ "hugoVersion": map[string]any{ "extended": false, "min": "0.146.0", }, }, } err := createSiteConfig(sourceFs, createpath, siteConfig, format) if err != nil { return err } defaultArchetype := map[string]any{ "title": "{{ replace .File.ContentBaseName \"-\" \" \" | title }}", "date": "{{ .Date }}", "draft": true, } err = createDefaultArchetype(sourceFs, createpath, defaultArchetype, format) if err != nil { return err } return copyFiles(createpath, sourceFs, themeFs) } // CreateSite creates a site skeleton. func CreateSite(createpath string, sourceFs afero.Fs, force bool, format string) error { format = strings.ToLower(format) if exists, _ := helpers.Exists(createpath, sourceFs); exists { if isDir, _ := helpers.IsDir(createpath, sourceFs); !isDir { return errors.New(createpath + " already exists but not a directory") } isEmpty, _ := helpers.IsEmpty(createpath, sourceFs) switch { case !isEmpty && !force: return errors.New(createpath + " already exists and is not empty. See --force.") case !isEmpty && force: var all []string fs.WalkDir(siteFs, ".", func(path string, d fs.DirEntry, err error) error { if d.IsDir() && path != "." { all = append(all, path) } return nil }) all = append(all, filepath.Join(createpath, "hugo."+format)) for _, path := range all { if exists, _ := helpers.Exists(path, sourceFs); exists { return errors.New(path + " already exists") } } } } siteConfig := map[string]any{ "baseURL": "https://example.org/", "title": "My New Hugo Site", "languageCode": "en-us", } err := createSiteConfig(sourceFs, createpath, siteConfig, format) if err != nil { return err } defaultArchetype := map[string]any{ "title": "{{ replace .File.ContentBaseName \"-\" \" \" | title }}", "date": "{{ .Date }}", "draft": true, } err = createDefaultArchetype(sourceFs, createpath, defaultArchetype, format) if err != nil { return err } return copyFiles(createpath, sourceFs, siteFs) } func copyFiles(createpath string, sourceFs afero.Fs, skeleton embed.FS) error { return fs.WalkDir(skeleton, ".", func(path string, d fs.DirEntry, err error) error { _, slug, _ := strings.Cut(path, "/") if d.IsDir() { return sourceFs.MkdirAll(filepath.Join(createpath, slug), 0o777) } else { if filepath.Base(path) != ".gitkeep" { data, _ := fs.ReadFile(skeleton, path) return helpers.WriteToDisk(filepath.Join(createpath, slug), bytes.NewReader(data), sourceFs) } return nil } }) } func createSiteConfig(fs afero.Fs, createpath string, in map[string]any, format string) (err error) { var buf bytes.Buffer err = parser.InterfaceToConfig(in, metadecoders.FormatFromString(format), &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(createpath, "hugo."+format), &buf, fs) } func createDefaultArchetype(fs afero.Fs, createpath string, in map[string]any, format string) (err error) { var buf bytes.Buffer err = parser.InterfaceToFrontMatter(in, metadecoders.FormatFromString(format), &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(createpath, "archetypes", "default.md"), &buf, fs) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/identity/finder.go
identity/finder.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package identity import ( "fmt" "sync" "github.com/gohugoio/hugo/compare" ) // NewFinder creates a new Finder. // This is a thread safe implementation with a cache. func NewFinder(cfg FinderConfig) *Finder { return &Finder{cfg: cfg, answers: make(map[ManagerIdentity]FinderResult), seenFindOnce: make(map[Identity]bool)} } var searchIDPool = sync.Pool{ New: func() any { return &searchID{seen: make(map[Manager]bool)} }, } func getSearchID() *searchID { return searchIDPool.Get().(*searchID) } func putSearchID(sid *searchID) { sid.id = nil sid.isDp = false sid.isPeq = false sid.hasEqer = false sid.maxDepth = 0 sid.dp = nil sid.peq = nil sid.eqer = nil clear(sid.seen) searchIDPool.Put(sid) } // GetSearchID returns a searchID from the pool. // Finder finds identities inside another. type Finder struct { cfg FinderConfig answers map[ManagerIdentity]FinderResult muAnswers sync.RWMutex seenFindOnce map[Identity]bool muSeenFindOnce sync.RWMutex } type FinderResult int const ( FinderNotFound FinderResult = iota FinderFoundOneOfManyRepetition FinderFoundOneOfMany FinderFound ) // Contains returns whether in contains id. func (f *Finder) Contains(id, in Identity, maxDepth int) FinderResult { if id == Anonymous || in == Anonymous { return FinderNotFound } if id == GenghisKhan && in == GenghisKhan { return FinderNotFound } if id == GenghisKhan { return FinderFound } if id == in { return FinderFound } if id == nil || in == nil { return FinderNotFound } var ( isDp bool isPeq bool dp IsProbablyDependentProvider peq compare.ProbablyEqer ) if !f.cfg.Exact { dp, isDp = id.(IsProbablyDependentProvider) peq, isPeq = id.(compare.ProbablyEqer) } eqer, hasEqer := id.(compare.Eqer) sid := getSearchID() sid.id = id sid.isDp = isDp sid.isPeq = isPeq sid.hasEqer = hasEqer sid.dp = dp sid.peq = peq sid.eqer = eqer sid.maxDepth = maxDepth defer putSearchID(sid) r := FinderNotFound if i := f.checkOne(sid, in, 0); i > r { r = i } if r == FinderFound { return r } m := GetDependencyManager(in) if m != nil { if i := f.checkManager(sid, m, 0); i > r { r = i } } return r } func (f *Finder) checkMaxDepth(sid *searchID, level int) FinderResult { if sid.maxDepth >= 0 && level > sid.maxDepth { return FinderNotFound } if level > 100 { // This should never happen, but some false positives are probably better than a panic. if !f.cfg.Exact { return FinderFound } panic("too many levels") } return -1 } func (f *Finder) checkManager(sid *searchID, m Manager, level int) FinderResult { if r := f.checkMaxDepth(sid, level); r >= 0 { return r } if m == nil { return FinderNotFound } if sid.seen[m] { return FinderNotFound } sid.seen[m] = true f.muAnswers.RLock() r, ok := f.answers[ManagerIdentity{Manager: m, Identity: sid.id}] f.muAnswers.RUnlock() if ok { return r } r = f.search(sid, m, level) if r == FinderFoundOneOfMany { // Don't cache this one. return r } f.muAnswers.Lock() f.answers[ManagerIdentity{Manager: m, Identity: sid.id}] = r f.muAnswers.Unlock() return r } func (f *Finder) checkOne(sid *searchID, v Identity, depth int) (r FinderResult) { if ff, ok := v.(FindFirstManagerIdentityProvider); ok { f.muSeenFindOnce.RLock() mi := ff.FindFirstManagerIdentity() seen := f.seenFindOnce[mi.Identity] f.muSeenFindOnce.RUnlock() if seen { return FinderFoundOneOfManyRepetition } r = f.doCheckOne(sid, mi.Identity, depth) if r == 0 { r = f.checkManager(sid, mi.Manager, depth) } if r > FinderFoundOneOfManyRepetition { f.muSeenFindOnce.Lock() // Double check. if f.seenFindOnce[mi.Identity] { f.muSeenFindOnce.Unlock() return FinderFoundOneOfManyRepetition } f.seenFindOnce[mi.Identity] = true f.muSeenFindOnce.Unlock() r = FinderFoundOneOfMany } return r } else { return f.doCheckOne(sid, v, depth) } } func (f *Finder) doCheckOne(sid *searchID, v Identity, depth int) FinderResult { id2 := Unwrap(v) if id2 == Anonymous { return FinderNotFound } id := sid.id if sid.hasEqer { if sid.eqer.Eq(id2) { return FinderFound } } else if id == id2 { return FinderFound } if f.cfg.Exact { return FinderNotFound } if id2 == nil { return FinderNotFound } if id2 == GenghisKhan { return FinderFound } if id.IdentifierBase() == id2.IdentifierBase() { return FinderFound } if sid.isDp && sid.dp.IsProbablyDependent(id2) { return FinderFound } if sid.isPeq && sid.peq.ProbablyEq(id2) { return FinderFound } if pdep, ok := id2.(IsProbablyDependencyProvider); ok && pdep.IsProbablyDependency(id) { return FinderFound } if peq, ok := id2.(compare.ProbablyEqer); ok && peq.ProbablyEq(id) { return FinderFound } return FinderNotFound } // search searches for id in ids. func (f *Finder) search(sid *searchID, m Manager, depth int) FinderResult { id := sid.id if id == Anonymous { return FinderNotFound } if !f.cfg.Exact && id == GenghisKhan { return FinderNotFound } var r FinderResult m.forEeachIdentity( func(v Identity) bool { i := f.checkOne(sid, v, depth) if i > r { r = i } if r == FinderFound { return true } m := GetDependencyManager(v) if i := f.checkManager(sid, m, depth+1); i > r { r = i } if r == FinderFound { return true } return false }, ) return r } // FinderConfig provides configuration for the Finder. // Note that we by default will use a strategy where probable matches are // good enough. The primary use case for this is to identity the change set // for a given changed identity (e.g. a template), and we don't want to // have any false negatives there, but some false positives are OK. Also, speed is important. type FinderConfig struct { // Match exact matches only. Exact bool } // ManagerIdentity wraps a pair of Identity and Manager. type ManagerIdentity struct { Identity Manager } func (p ManagerIdentity) String() string { return fmt.Sprintf("%s:%s", p.Identity.IdentifierBase(), p.Manager.IdentifierBase()) } type searchID struct { id Identity isDp bool isPeq bool hasEqer bool maxDepth int seen map[Manager]bool dp IsProbablyDependentProvider peq compare.ProbablyEqer eqer compare.Eqer }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/identity/identity_test.go
identity/identity_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package identity_test import ( "fmt" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/identity/identitytesting" ) func BenchmarkIdentityManager(b *testing.B) { createIds := func(num int) []identity.Identity { ids := make([]identity.Identity, num) for i := range num { name := fmt.Sprintf("id%d", i) ids[i] = &testIdentity{base: name, name: name} } return ids } b.Run("identity.NewManager", func(b *testing.B) { for b.Loop() { m := identity.NewManager() if m == nil { b.Fatal("manager is nil") } } }) b.Run("Add many", func(b *testing.B) { const size = 1000 ids := createIds(size) im := identity.NewManager() b.ResetTimer() for i := 0; b.Loop(); i++ { im.AddIdentity(ids[i%size]) } b.StopTimer() }) b.Run("Nop StringIdentity const", func(b *testing.B) { const id = identity.StringIdentity("test") for b.Loop() { identity.NopManager.AddIdentity(id) } }) b.Run("Nop StringIdentity const other package", func(b *testing.B) { for b.Loop() { identity.NopManager.AddIdentity(identitytesting.TestIdentity) } }) b.Run("Nop StringIdentity var", func(b *testing.B) { id := identity.StringIdentity("test") for b.Loop() { identity.NopManager.AddIdentity(id) } }) b.Run("Nop pointer identity", func(b *testing.B) { id := &testIdentity{base: "a", name: "b"} for b.Loop() { identity.NopManager.AddIdentity(id) } }) b.Run("Nop Anonymous", func(b *testing.B) { for b.Loop() { identity.NopManager.AddIdentity(identity.Anonymous) } }) } func BenchmarkIsNotDependent(b *testing.B) { runBench := func(b *testing.B, id1, id2 identity.Identity) { for b.Loop() { isNotDependent(id1, id2) } } newNestedManager := func(depth, count int) identity.Manager { m1 := identity.NewManager() for range depth { m2 := identity.NewManager() m1.AddIdentity(m2) for j := range count { id := fmt.Sprintf("id%d", j) m2.AddIdentity(&testIdentity{id, id, "", ""}) } m1 = m2 } return m1 } type depthCount struct { depth int count int } for _, dc := range []depthCount{{10, 5}} { b.Run(fmt.Sprintf("Nested not found %d %d", dc.depth, dc.count), func(b *testing.B) { im := newNestedManager(dc.depth, dc.count) id1 := identity.StringIdentity("idnotfound") b.ResetTimer() runBench(b, im, id1) }) } } func TestIdentityManager(t *testing.T) { c := qt.New(t) newNestedManager := func() identity.Manager { m1 := identity.NewManager() m2 := identity.NewManager() m3 := identity.NewManager() m1.AddIdentity( testIdentity{"base", "id1", "", "pe1"}, testIdentity{"base2", "id2", "eq1", ""}, m2, m3, ) m2.AddIdentity(testIdentity{"base4", "id4", "", ""}) return m1 } c.Run("Anonymous", func(c *qt.C) { im := newNestedManager() c.Assert(im.GetIdentity(), qt.Equals, identity.Anonymous) im.AddIdentity(identity.Anonymous) c.Assert(isNotDependent(identity.Anonymous, identity.Anonymous), qt.IsTrue) }) c.Run("GenghisKhan", func(c *qt.C) { c.Assert(isNotDependent(identity.GenghisKhan, identity.GenghisKhan), qt.IsTrue) }) } type testIdentity struct { base string name string idEq string idProbablyEq string } func (id testIdentity) Eq(other any) bool { ot, ok := other.(testIdentity) if !ok { return false } if ot.idEq == "" || id.idEq == "" { return false } return ot.idEq == id.idEq } func (id testIdentity) IdentifierBase() string { return id.base } func (id testIdentity) Name() string { return id.name } func (id testIdentity) ProbablyEq(other any) bool { ot, ok := other.(testIdentity) if !ok { return false } if ot.idProbablyEq == "" || id.idProbablyEq == "" { return false } return ot.idProbablyEq == id.idProbablyEq } func isNotDependent(a, b identity.Identity) bool { f := identity.NewFinder(identity.FinderConfig{}) r := f.Contains(b, a, -1) return r == 0 }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/identity/finder_test.go
identity/finder_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package provides ways to identify values in Hugo. Used for dependency tracking etc. package identity_test import ( "testing" "github.com/gohugoio/hugo/identity" ) func BenchmarkFinder(b *testing.B) { m1 := identity.NewManager() m2 := identity.NewManager() m3 := identity.NewManager() m1.AddIdentity( testIdentity{"base", "id1", "", "pe1"}, testIdentity{"base2", "id2", "eq1", ""}, m2, m3, ) b4 := testIdentity{"base4", "id4", "", ""} b5 := testIdentity{"base5", "id5", "", ""} m2.AddIdentity(b4) f := identity.NewFinder(identity.FinderConfig{}) b.Run("Find one", func(b *testing.B) { for b.Loop() { r := f.Contains(b4, m1, -1) if r == 0 { b.Fatal("not found") } } }) b.Run("Find none", func(b *testing.B) { for b.Loop() { r := f.Contains(b5, m1, -1) if r > 0 { b.Fatal("found") } } }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/identity/predicate_identity.go
identity/predicate_identity.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package provides ways to identify values in Hugo. Used for dependency tracking etc. package identity import ( "fmt" "sync/atomic" ) var predicateIdentityCounter = &atomic.Uint32{} type predicateIdentity struct { id string probablyDependent func(Identity) bool probablyDependency func(Identity) bool } var ( _ IsProbablyDependencyProvider = &predicateIdentity{} _ IsProbablyDependentProvider = &predicateIdentity{} ) // NewPredicateIdentity creates a new Identity that implements both IsProbablyDependencyProvider and IsProbablyDependentProvider // using the provided functions, both of which are optional. func NewPredicateIdentity( probablyDependent func(Identity) bool, probablyDependency func(Identity) bool, ) *predicateIdentity { if probablyDependent == nil { probablyDependent = func(Identity) bool { return false } } if probablyDependency == nil { probablyDependency = func(Identity) bool { return false } } return &predicateIdentity{probablyDependent: probablyDependent, probablyDependency: probablyDependency, id: fmt.Sprintf("predicate%d", predicateIdentityCounter.Add(1))} } func (id *predicateIdentity) IdentifierBase() string { return id.id } func (id *predicateIdentity) IsProbablyDependent(other Identity) bool { return id.probablyDependent(other) } func (id *predicateIdentity) IsProbablyDependency(other Identity) bool { return id.probablyDependency(other) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/identity/question.go
identity/question.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package identity import "sync" // NewQuestion creates a new question with the given identity. func NewQuestion[T any](id Identity) *Question[T] { return &Question[T]{ Identity: id, } } // Answer takes a func that knows the answer. // Note that this is a one-time operation, // fn will not be invoked again it the question is already answered. // Use Result to check if the question is answered. func (q *Question[T]) Answer(fn func() T) { q.mu.Lock() defer q.mu.Unlock() if q.answered { return } q.fasit = fn() q.answered = true } // Result returns the fasit of the question (if answered), // and a bool indicating if the question has been answered. func (q *Question[T]) Result() (any, bool) { q.mu.RLock() defer q.mu.RUnlock() return q.fasit, q.answered } // A Question is defined by its Identity and can be answered once. type Question[T any] struct { Identity fasit T mu sync.RWMutex answered bool }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/identity/question_test.go
identity/question_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package identity import ( "testing" qt "github.com/frankban/quicktest" ) func TestQuestion(t *testing.T) { c := qt.New(t) q := NewQuestion[int](StringIdentity("2+2?")) v, ok := q.Result() c.Assert(ok, qt.Equals, false) c.Assert(v, qt.Equals, 0) q.Answer(func() int { return 4 }) v, ok = q.Result() c.Assert(ok, qt.Equals, true) c.Assert(v, qt.Equals, 4) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/identity/predicate_identity_test.go
identity/predicate_identity_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package provides ways to identify values in Hugo. Used for dependency tracking etc. package identity import ( "testing" qt "github.com/frankban/quicktest" ) func TestPredicateIdentity(t *testing.T) { c := qt.New(t) isDependent := func(id Identity) bool { return id.IdentifierBase() == "foo" } isDependency := func(id Identity) bool { return id.IdentifierBase() == "baz" } id := NewPredicateIdentity(isDependent, isDependency) c.Assert(id.IsProbablyDependent(StringIdentity("foo")), qt.IsTrue) c.Assert(id.IsProbablyDependent(StringIdentity("bar")), qt.IsFalse) c.Assert(id.IsProbablyDependent(id), qt.IsFalse) c.Assert(id.IsProbablyDependent(NewPredicateIdentity(isDependent, nil)), qt.IsFalse) c.Assert(id.IsProbablyDependency(StringIdentity("baz")), qt.IsTrue) c.Assert(id.IsProbablyDependency(StringIdentity("foo")), qt.IsFalse) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/identity/identity.go
identity/identity.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package provides ways to identify values in Hugo. Used for dependency tracking etc. package identity import ( "fmt" "path" "path/filepath" "sort" "strings" "sync" "sync/atomic" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/compare" ) const ( // Anonymous is an Identity that can be used when identity doesn't matter. Anonymous = StringIdentity("__anonymous") // GenghisKhan is an Identity everyone relates to. GenghisKhan = StringIdentity("__genghiskhan") StructuralChangeAdd = StringIdentity("__structural_change_add") StructuralChangeRemove = StringIdentity("__structural_change_remove") ) var NopManager = new(nopManager) // NewIdentityManager creates a new Manager. func NewManager(opts ...ManagerOption) Manager { idm := &identityManager{ Identity: Anonymous, ids: Identities{}, } for _, o := range opts { o(idm) } return idm } // CleanString cleans s to be suitable as an identifier. func CleanString(s string) string { s = strings.ToLower(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. func CleanStringIdentity(s string) StringIdentity { return StringIdentity(CleanString(s)) } // GetDependencyManager returns the DependencyManager from v or nil if none found. func GetDependencyManager(v any) Manager { switch vv := v.(type) { case Manager: return vv case types.Unwrapper: return GetDependencyManager(vv.Unwrapv()) 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 WalkIdentitiesShallow(v, func(level int, id Identity) bool { result = id return result != Anonymous }) return result } // PrintIdentityInfo is used for debugging/tests only. func PrintIdentityInfo(v any) { WalkIdentitiesDeep(v, func(level int, id Identity) bool { var s string fmt.Printf("%s%s (%T)%s\n", strings.Repeat(" ", level), id.IdentifierBase(), id, s) return false }) } func Unwrap(id Identity) Identity { switch t := id.(type) { case IdentityProvider: return t.GetIdentity() default: return id } } // WalkIdentitiesDeep walks identities in v and applies cb to every identity found. // Return true from cb to terminate. // If deep is true, it will also walk nested Identities in any Manager found. func WalkIdentitiesDeep(v any, cb func(level int, id Identity) bool) { seen := make(map[Identity]bool) walkIdentities(v, 0, true, seen, cb) } // WalkIdentitiesShallow will not walk into a Manager's Identities. // See WalkIdentitiesDeep. // cb is called for every Identity found and returns whether to terminate the walk. func WalkIdentitiesShallow(v any, cb func(level int, id Identity) bool) { walkIdentitiesShallow(v, 0, cb) } // WithOnAddIdentity sets a callback that will be invoked when an identity is added to the manager. func WithOnAddIdentity(f func(id Identity)) ManagerOption { return func(m *identityManager) { m.onAddIdentity = f } } // DependencyManagerProvider provides a manager for dependencies. type DependencyManagerProvider interface { GetDependencyManager() Manager } // DependencyManagerProviderFunc is a function that implements the DependencyManagerProvider interface. type DependencyManagerProviderFunc func() Manager func (d DependencyManagerProviderFunc) GetDependencyManager() Manager { return d() } // DependencyManagerScopedProvider provides a manager for dependencies with a given scope. type DependencyManagerScopedProvider interface { GetDependencyManagerForScope(scope int) Manager GetDependencyManagerForScopesAll() []Manager } // ForEeachIdentityProvider provides a way iterate over identities. type ForEeachIdentityProvider interface { // ForEeachIdentityProvider calls cb for each Identity. // If cb returns false, the iteration is terminated. // It returns false if the iteration was terminated early. 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 ForEeachIdentityByNameProvider interface { // ForEeachIdentityByName calls cb for each Identity that relates to name. // If cb returns true, the iteration is terminated. ForEeachIdentityByName(name string, cb func(id Identity) bool) } type FindFirstManagerIdentityProvider interface { Identity FindFirstManagerIdentity() ManagerIdentity } func NewFindFirstManagerIdentityProvider(m Manager, id Identity) FindFirstManagerIdentityProvider { return findFirstManagerIdentity{ Identity: Anonymous, ManagerIdentity: ManagerIdentity{ Manager: m, Identity: id, }, } } type findFirstManagerIdentity struct { Identity ManagerIdentity } func (f findFirstManagerIdentity) FindFirstManagerIdentity() ManagerIdentity { return f.ManagerIdentity } // Identities stores identity providers. type Identities map[Identity]bool func (ids Identities) AsSlice() []Identity { s := make([]Identity, len(ids)) i := 0 for v := range ids { s[i] = v i++ } sort.Slice(s, func(i, j int) bool { return s[i].IdentifierBase() < s[j].IdentifierBase() }) return s } func (ids Identities) String() string { var sb strings.Builder i := 0 for id := range ids { sb.WriteString(fmt.Sprintf("[%s]", id.IdentifierBase())) if i < len(ids)-1 { sb.WriteString(", ") } i++ } return sb.String() } // Identity represents a thing in Hugo (a Page, a template etc.) // Any implementation must be comparable/hashable. type Identity interface { IdentifierBase() string } // IdentityGroupProvider can be implemented by tightly connected types. // Current use case is Resource transformation via Hugo Pipes. type IdentityGroupProvider interface { GetIdentityGroup() Identity } // IdentityProvider can be implemented by types that isn't itself and Identity, // usually because they're not comparable/hashable. type IdentityProvider interface { GetIdentity() Identity } // SignalRebuilder is an optional interface for types that can signal a rebuild. type SignalRebuilder interface { SignalRebuild(ids ...Identity) } // IncrementByOne implements Incrementer adding 1 every time Incr is called. type IncrementByOne struct { counter uint64 } func (c *IncrementByOne) Incr() int { return int(atomic.AddUint64(&c.counter, uint64(1))) } // Incrementer increments and returns the value. // Typically used for IDs. type Incrementer interface { Incr() int } // IsProbablyDependentProvider is an optional interface for Identity. type IsProbablyDependentProvider interface { IsProbablyDependent(other Identity) bool } // IsProbablyDependencyProvider is an optional interface for Identity. type IsProbablyDependencyProvider interface { IsProbablyDependency(other Identity) bool } // Manager is an Identity that also manages identities, typically dependencies. type Manager interface { Identity AddIdentity(ids ...Identity) AddIdentityForEach(ids ...ForEeachIdentityProvider) GetIdentity() Identity Reset() forEeachIdentity(func(id Identity) bool) bool } type ManagerOption func(m *identityManager) // StringIdentity is an Identity that wraps a string. type StringIdentity string func (s StringIdentity) IdentifierBase() string { return string(s) } type identityManager struct { Identity // mu protects _changes_ to this manager, // reads currently assumes no concurrent writes. mu sync.RWMutex ids Identities forEachIds []ForEeachIdentityProvider // Hooks used in debugging. onAddIdentity func(id Identity) } func (im *identityManager) AddIdentity(ids ...Identity) { im.mu.Lock() defer im.mu.Unlock() for _, id := range ids { if id == nil || id == Anonymous { continue } if _, found := im.ids[id]; !found { if im.onAddIdentity != nil { im.onAddIdentity(id) } im.ids[id] = true } } } 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 } f := NewFinder(FinderConfig{Exact: true}) r := f.Contains(id, im, -1) return r } // Managers are always anonymous. func (im *identityManager) GetIdentity() Identity { return im.Identity } func (im *identityManager) Reset() { im.mu.Lock() im.ids = Identities{} im.mu.Unlock() } func (im *identityManager) GetDependencyManagerForScope(int) Manager { return im } func (im *identityManager) GetDependencyManagerForScopesAll() []Manager { return []Manager{im} } func (im *identityManager) forEeachIdentity(fn func(id Identity) bool) bool { // The absence of a lock here is deliberate. This is currently only 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 false } } return true } type nopManager int func (m *nopManager) AddIdentity(ids ...Identity) { } func (m *nopManager) AddIdentityForEach(ids ...ForEeachIdentityProvider) { } func (m *nopManager) IdentifierBase() string { return "" } func (m *nopManager) GetIdentity() Identity { return Anonymous } func (m *nopManager) Reset() { } func (m *nopManager) forEeachIdentity(func(id Identity) bool) bool { return false } // returns whether further walking should be terminated. func walkIdentities(v any, level int, deep bool, seen map[Identity]bool, cb func(level int, id Identity) bool) { if level > 20 { panic("too deep") } var cbRecursive func(level int, id Identity) bool cbRecursive = func(level int, id Identity) bool { if id == nil { return false } if deep && seen[id] { return false } seen[id] = true if cb(level, id) { return true } if deep { if m := GetDependencyManager(id); m != nil { m.forEeachIdentity(func(id2 Identity) bool { return walkIdentitiesShallow(id2, level+1, cbRecursive) }) } } return false } walkIdentitiesShallow(v, level, cbRecursive) } // returns whether further walking should be terminated. // Anonymous identities are skipped. func walkIdentitiesShallow(v any, level int, cb func(level int, id Identity) bool) bool { cb2 := func(level int, id Identity) bool { if id == Anonymous { return false } if id == nil { return false } return cb(level, id) } if id, ok := v.(Identity); ok { if cb2(level, id) { return true } } if ipd, ok := v.(IdentityProvider); ok { if cb2(level, ipd.GetIdentity()) { return true } } if ipdgp, ok := v.(IdentityGroupProvider); ok { if cb2(level, ipdgp.GetIdentityGroup()) { return true } } return false } var ( _ Identity = (*orIdentity)(nil) _ compare.ProbablyEqer = (*orIdentity)(nil) ) func Or(a, b Identity) Identity { return orIdentity{a: a, b: b} } type orIdentity struct { a, b Identity } func (o orIdentity) IdentifierBase() string { return o.a.IdentifierBase() } func (o orIdentity) ProbablyEq(other any) bool { otherID, ok := other.(Identity) if !ok { return false } return probablyEq(o.a, otherID) || probablyEq(o.b, otherID) } func probablyEq(a, b Identity) bool { if a == b { return true } if a == Anonymous || b == Anonymous { return false } if a.IdentifierBase() == b.IdentifierBase() { return true } if a2, ok := a.(compare.ProbablyEqer); ok && a2.ProbablyEq(b) { return true } if a2, ok := a.(IsProbablyDependentProvider); ok { return a2.IsProbablyDependent(b) } return false }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/identity/identitytesting/identitytesting.go
identity/identitytesting/identitytesting.go
package identitytesting import "github.com/gohugoio/hugo/identity" const TestIdentity = identity.StringIdentity("__testIdentity")
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/htesting/test_helpers_test.go
htesting/test_helpers_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package htesting import ( "testing" qt "github.com/frankban/quicktest" ) func TestExtractMinorVersionFromGoTag(t *testing.T) { c := qt.New(t) c.Assert(extractMinorVersionFromGoTag("go1.17"), qt.Equals, 17) c.Assert(extractMinorVersionFromGoTag("go1.16.7"), qt.Equals, 16) c.Assert(extractMinorVersionFromGoTag("go1.17beta1"), qt.Equals, 17) c.Assert(extractMinorVersionFromGoTag("asdfadf"), qt.Equals, -1) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/htesting/test_helpers.go
htesting/test_helpers.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package htesting import ( "math/rand" "os" "regexp" "runtime" "strconv" "strings" "testing" "time" qt "github.com/frankban/quicktest" "github.com/spf13/afero" ) // IsTest reports whether we're running as a test. var IsTest bool func init() { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test.") { IsTest = true break } } } // CreateTempDir creates a temp dir in the given filesystem and // returns the dirname and a func that removes it when done. func CreateTempDir(fs afero.Fs, prefix string) (string, func(), error) { tempDir, err := afero.TempDir(fs, "", prefix) if err != nil { return "", nil, err } _, isOsFs := fs.(*afero.OsFs) if isOsFs && runtime.GOOS == "darwin" && !strings.HasPrefix(tempDir, "/private") { // To get the entry folder in line with the rest. This its a little bit // mysterious, but so be it. tempDir = "/private" + tempDir } return tempDir, func() { fs.RemoveAll(tempDir) }, nil } // BailOut panics with a stack trace after the given duration. Useful for // hanging tests. func BailOut(after time.Duration) { time.AfterFunc(after, func() { buf := make([]byte, 1<<16) runtime.Stack(buf, true) panic(string(buf)) }) } // Rnd is used only for testing. var Rnd = rand.New(rand.NewSource(time.Now().UnixNano())) func RandBool() bool { return Rnd.Intn(2) != 0 } // DiffStringSlices returns the difference between two string slices. // Useful in tests. // See: // http://stackoverflow.com/questions/19374219/how-to-find-the-difference-between-two-slices-of-strings-in-golang func DiffStringSlices(slice1 []string, slice2 []string) []string { diffStr := []string{} m := map[string]int{} for _, s1Val := range slice1 { m[s1Val] = 1 } for _, s2Val := range slice2 { m[s2Val] = m[s2Val] + 1 } for mKey, mVal := range m { if mVal == 1 { diffStr = append(diffStr, mKey) } } return diffStr } // DiffStrings splits the strings into fields and runs it into DiffStringSlices. // Useful for tests. func DiffStrings(s1, s2 string) []string { return DiffStringSlices(strings.Fields(s1), strings.Fields(s2)) } // IsCI reports whether we're running in a CI server. func IsCI() bool { return (os.Getenv("CI") != "" || os.Getenv("CI_LOCAL") != "") && os.Getenv("CIRCLE_BRANCH") == "" } // IsRealCI reports whether we're running in a CI server, but not in a local CI setup. func IsRealCI() bool { return IsCI() && os.Getenv("CI_LOCAL") == "" } // IsGitHubAction reports whether we're running in a GitHub Action. func IsGitHubAction() bool { return os.Getenv("GITHUB_ACTION") != "" } // SupportsAll reports whether the running system supports all Hugo features, // e.g. AsciiDoc, Pandoc etc. func SupportsAll() bool { return IsGitHubAction() || os.Getenv("CI_LOCAL") != "" } // GoMinorVersion returns the minor version of the current Go version, // e.g. 16 for Go 1.16. func GoMinorVersion() int { return extractMinorVersionFromGoTag(runtime.Version()) } // IsWindows reports whether this runs on Windows. func IsWindows() bool { return runtime.GOOS == "windows" } var goMinorVersionRe = regexp.MustCompile(`go1.(\d*)`) func extractMinorVersionFromGoTag(tag string) int { // The tag may be on the form go1.17, go1.17.5 go1.17rc2 -- or just a commit hash. match := goMinorVersionRe.FindStringSubmatch(tag) if len(match) == 2 { i, err := strconv.Atoi(match[1]) if err != nil { return -1 } return i } // a commit hash, not useful. return -1 } // NewPinnedRunner creates a new runner that will only Run tests matching the given regexp. // This is added mostly to use in combination with https://marketplace.visualstudio.com/items?itemName=windmilleng.vscode-go-autotest func NewPinnedRunner(t testing.TB, pinnedTestRe string) *PinnedRunner { if pinnedTestRe == "" { pinnedTestRe = ".*" } pinnedTestRe = strings.ReplaceAll(pinnedTestRe, "_", " ") re := regexp.MustCompile("(?i)" + pinnedTestRe) return &PinnedRunner{ c: qt.New(t), re: re, } } type PinnedRunner struct { c *qt.C re *regexp.Regexp } func (r *PinnedRunner) Run(name string, f func(c *qt.C)) bool { if !r.re.MatchString(name) { if IsGitHubAction() { r.c.Fatal("found pinned test when running in CI") } return true } return r.c.Run(name, f) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/htesting/hqt/checkers.go
htesting/hqt/checkers.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hqt import ( "errors" "fmt" "math" "reflect" "strings" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/htesting" "github.com/google/go-cmp/cmp" "github.com/spf13/cast" ) // IsSameString asserts that two strings are equal. The two strings // are normalized (whitespace removed) before doing a ==. // Also note that two strings can be the same even if they're of different // types. var IsSameString qt.Checker = &stringChecker{ argNames: []string{"got", "want"}, } // IsSameType asserts that got is the same type as want. var IsSameType qt.Checker = &typeChecker{ argNames: []string{"got", "want"}, } // IsSameFloat64 asserts that two float64 values are equal within a small delta. var IsSameFloat64 = qt.CmpEquals(cmp.Comparer(func(a, b float64) bool { return math.Abs(a-b) < 0.0001 })) // IsSameNumber asserts that two number values are equal within a small delta. var IsSameNumber = qt.CmpEquals( cmp.Comparer(func(a, b float64) bool { return math.Abs(a-b) < 0.0001 }), cmp.Comparer(func(a, b float32) bool { return math.Abs(float64(a)-float64(b)) < 0.0001 }), cmp.Comparer(func(a, b int) bool { return a == b }), cmp.Comparer(func(a, b int8) bool { return a == b }), cmp.Comparer(func(a, b int16) bool { return a == b }), cmp.Comparer(func(a, b int32) bool { return a == b }), cmp.Comparer(func(a, b int64) bool { return a == b }), cmp.Comparer(func(a, b uint) bool { return a == b }), cmp.Comparer(func(a, b uint8) bool { return a == b }), cmp.Comparer(func(a, b uint16) bool { return a == b }), cmp.Comparer(func(a, b uint32) bool { return a == b }), cmp.Comparer(func(a, b uint64) bool { return a == b }), ) type argNames []string func (a argNames) ArgNames() []string { return a } type typeChecker struct { argNames } // Check implements Checker.Check by checking that got and args[0] is of the same type. func (c *typeChecker) Check(got any, args []any, note func(key string, value any)) (err error) { if want := args[0]; reflect.TypeOf(got) != reflect.TypeOf(want) { if _, ok := got.(error); ok && want == nil { return errors.New("got non-nil error") } return errors.New("values are not of same type") } return nil } type stringChecker struct { argNames } // Check implements Checker.Check by checking that got and args[0] represents the same normalized text (whitespace etc. removed). func (c *stringChecker) Check(got any, args []any, note func(key string, value any)) (err error) { s1, s2 := cast.ToString(got), cast.ToString(args[0]) if s1 == s2 { return nil } s1, s2 = normalizeString(s1), normalizeString(s2) if s1 == s2 { return nil } return fmt.Errorf("values are not the same text: %s", strings.Join(htesting.DiffStrings(s1, s2), " | ")) } func normalizeString(s string) string { s = strings.ReplaceAll(s, "\r\n", "\n") lines := strings.Split(strings.TrimSpace(s), "\n") for i, line := range lines { lines[i] = strings.Join(strings.Fields(strings.TrimSpace(line)), "") } return strings.Join(lines, "\n") } // IsAllElementsEqual asserts that all elements in the slice are equal. var IsAllElementsEqual qt.Checker = &sliceAllElementsEqualChecker{ argNames: []string{"got"}, } type sliceAllElementsEqualChecker struct { argNames } func (c *sliceAllElementsEqualChecker) Check(got any, args []any, note func(key string, value any)) (err error) { gotSlice := reflect.ValueOf(got) numElements := gotSlice.Len() if numElements < 2 { return nil } first := gotSlice.Index(0).Interface() // Check that the others are equal to the first. for i := 1; i < numElements; i++ { if diff := cmp.Diff(first, gotSlice.Index(i).Interface()); diff != "" { return fmt.Errorf("element %d is not equal to the first element:\n%s", i, diff) } } return nil } // DeepAllowUnexported creates an option to allow compare of unexported types // in the given list of types. // see https://github.com/google/go-cmp/issues/40#issuecomment-328615283 func DeepAllowUnexported(vs ...any) cmp.Option { m := make(map[reflect.Type]struct{}) for _, v := range vs { structTypes(reflect.ValueOf(v), m) } var typs []any for t := range m { typs = append(typs, reflect.New(t).Elem().Interface()) } return cmp.AllowUnexported(typs...) } func structTypes(v reflect.Value, m map[reflect.Type]struct{}) { if !v.IsValid() { return } switch v.Kind() { case reflect.Ptr: if !v.IsNil() { structTypes(v.Elem(), m) } case reflect.Interface: if !v.IsNil() { structTypes(v.Elem(), m) } case reflect.Slice, reflect.Array: for i := range v.Len() { structTypes(v.Index(i), m) } case reflect.Map: for _, k := range v.MapKeys() { structTypes(v.MapIndex(k), m) } case reflect.Struct: m[v.Type()] = struct{}{} for i := range v.NumField() { structTypes(v.Field(i), m) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resources_integration_test.go
resources/resources_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 8931 func TestImageCache(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true baseURL = "https://example.org" -- content/mybundle/index.md -- --- title: "My Bundle" --- -- content/mybundle/pixel.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- content/mybundle/giphy.gif -- sourcefilename: testdata/giphy.gif -- layouts/foo.html -- -- layouts/home.html -- {{ $p := site.GetPage "mybundle"}} {{ $img := $p.Resources.Get "pixel.png" }} {{ $giphy := $p.Resources.Get "giphy.gif" }} {{ $gif := $img.Resize "1x2 gif" }} {{ $bmp := $img.Resize "2x3 bmp" }} {{ $anigif := $giphy.Resize "4x5" }} gif: {{ $gif.RelPermalink }}|}|{{ $gif.Width }}|{{ $gif.Height }}|{{ $gif.MediaType }}| bmp: {{ $bmp.RelPermalink }}|}|{{ $bmp.Width }}|{{ $bmp.Height }}|{{ $bmp.MediaType }}| anigif: {{ $anigif.RelPermalink }}|{{ $anigif.Width }}|{{ $anigif.Height }}|{{ $anigif.MediaType }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, Running: true, }).Build() assertImages := func() { b.AssertFileContent("public/index.html", ` gif: /mybundle/pixel_hu_d6bad5e71f783c98.gif|}|1|2|image/gif| bmp: /mybundle/pixel_hu_a8812c9bf8812b53.bmp|}|2|3|image/bmp| anigif: /mybundle/giphy_hu_7f64f85f904209d4.gif|4|5|image/gif| `) } assertImages() b.EditFileReplaceFunc("content/mybundle/index.md", func(s string) string { return strings.ReplaceAll(s, "Bundle", "BUNDLE") }) b.Build() assertImages() } func TestSVGError(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- assets/circle.svg -- <svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg> -- layouts/home.html -- {{ $svg := resources.Get "circle.svg" }} Width: {{ $svg.Width }} ` b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, Running: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `error calling Width: this method is only available for raster images. To determine if an image is SVG, you can do {{ if eq .MediaType.SubType "svg" }}{{ end }}`) } // Issue 10255. func TestNoPublishOfUnusedProcessedImage(t *testing.T) { t.Parallel() workingDir := t.TempDir() files := ` -- assets/images/pixel.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- layouts/home.html -- {{ $image := resources.Get "images/pixel.png" }} {{ $image = $image.Resize "400x" }} {{ $image = $image.Resize "300x" }} {{ $image = $image.Resize "200x" }} {{ $image = $image.Resize "100x" }} {{ $image = $image.Crop "50x50" }} {{ $image = $image.Filter (images.GaussianBlur 6) }} {{ ($image | fingerprint).Permalink }} ` for range 3 { b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, WorkingDir: workingDir, }).Build() b.AssertFileCount("resources/_gen/images", 6) b.AssertFileCount("public/images", 1) } } func TestProcessFilter(t *testing.T) { t.Parallel() files := ` -- assets/images/pixel.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- layouts/home.html -- {{ $pixel := resources.Get "images/pixel.png" }} {{ $filters := slice (images.GaussianBlur 6) (images.Pixelate 8) (images.Process "jpg") }} {{ $image := $pixel.Filter $filters }} jpg|RelPermalink: {{ $image.RelPermalink }}|MediaType: {{ $image.MediaType }}|Width: {{ $image.Width }}|Height: {{ $image.Height }}| {{ $filters := slice (images.GaussianBlur 6) (images.Pixelate 8) (images.Process "jpg resize 20x30") }} {{ $image := $pixel.Filter $filters }} resize 1|RelPermalink: {{ $image.RelPermalink }}|MediaType: {{ $image.MediaType }}|Width: {{ $image.Width }}|Height: {{ $image.Height }}| {{ $image := $pixel.Filter $filters }} resize 2|RelPermalink: {{ $image.RelPermalink }}|MediaType: {{ $image.MediaType }}|Width: {{ $image.Width }}|Height: {{ $image.Height }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "jpg|RelPermalink: /images/pixel_hu_38c3f257174fc757.jpg|MediaType: image/jpeg|Width: 1|Height: 1|", "resize 1|RelPermalink: /images/pixel_hu_b5c2a3d88991f65a.jpg|MediaType: image/jpeg|Width: 20|Height: 30|", "resize 2|RelPermalink: /images/pixel_hu_b5c2a3d88991f65a.jpg|MediaType: image/jpeg|Width: 20|Height: 30|", ) } // Issue #11563 func TestGroupByParamDate(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['section','rss','sitemap','taxonomy','term'] -- layouts/home.html -- {{- range site.RegularPages.GroupByParamDate "eventDate" "2006-01" }} {{- .Key }}|{{ range .Pages }}{{ .Title }}|{{ end }} {{- end }} -- content/p1.md -- +++ title = 'p1' eventDate = 2023-09-01 +++ -- content/p2.md -- +++ title = 'p2' eventDate = '2023-09-01' +++ -- content/p3.md -- --- title: p3 eventDate: 2023-09-01 --- -- content/p4.md -- +++ title = 'p4' eventDate = 2023-10-01T08:00:00 +++ -- content/p5.md -- +++ title = 'p5' eventDate = '2023-10-01T08:00:00' +++ -- content/p6.md -- --- title: p6 eventDate: 2023-10-01T08:00:00 --- -- content/p7.md -- +++ title = 'p7' eventDate = 2023-11-01T07:00:00-08:00 +++ -- content/p8.md -- +++ title = 'p8' eventDate = '2023-11-01T07:00:00-08:00' +++ -- content/p9.md -- --- title: p9 eventDate: 2023-11-01T07:00:00-08:00 --- ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "2023-11|p9|p8|p7|2023-10|p6|p5|p4|2023-09|p3|p2|p1|") } // Issue 10412 func TestImageTransformThenCopy(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- assets/pixel.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- layouts/home.html -- {{- with resources.Get "pixel.png" }} {{- with .Resize "200x" | resources.Copy "pixel.png" }} <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">|{{ .Key }} {{- end }} {{- end }} ` b := hugolib.Test(t, files) b.AssertFileExists("public/pixel.png", true) b.AssertFileContent("public/index.html", `<img src="/pixel.png" width="200" height="200">|/pixel.png`, ) } // Issue 12310 func TestUseDifferentCacheKeyForResourceCopy(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','section','rss','sitemap','taxonomy','term'] -- assets/a.txt -- This was assets/a.txt -- layouts/home.html -- {{ $nilResource := resources.Get "/p1/b.txt" }} {{ $r := resources.Get "a.txt" }} {{ $r = resources.Copy "/p1/b.txt" $r }} {{ $r.RelPermalink }} ` b, err := hugolib.TestE(t, files) b.Assert(err, qt.IsNil) b.AssertFileContent("public/p1/b.txt", "This was assets/a.txt") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/post_publish.go
resources/post_publish.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources import ( "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/resources/resource" ) type transformationKeyer interface { TransformationKey() string } // PostProcess wraps the given Resource for later processing. func (spec *Spec) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { key := r.(transformationKeyer).TransformationKey() spec.postProcessMu.RLock() result, found := spec.PostProcessResources[key] spec.postProcessMu.RUnlock() if found { return result, nil } spec.postProcessMu.Lock() defer spec.postProcessMu.Unlock() // Double check result, found = spec.PostProcessResources[key] if found { return result, nil } result = postpub.NewPostPublishResource(spec.incr.Incr(), r) if result == nil { panic("got nil result") } spec.PostProcessResources[key] = result return result, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_spec.go
resources/resource_spec.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources import ( "fmt" "path" "sync" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/allconfig" "github.com/gohugoio/hugo/internal/warpc" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/jsconfig" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/hsync" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) func NewSpec( s *helpers.PathSpec, common *SpecCommon, // may be nil wasmDispatchers *warpc.Dispatchers, fileCaches filecache.Caches, memCache *dynacache.Cache, incr identity.Incrementer, logger loggers.Logger, errorHandler herrors.ErrorSender, execHelper *hexec.Exec, buildClosers types.CloseAdder, rebuilder identity.SignalRebuilder, ) (*Spec, error) { conf := s.Cfg.GetConfig().(*allconfig.Config) imgConfig := conf.Imaging imagesWarnl := logger.WarnCommand("images") imaging, err := images.NewImageProcessor(imagesWarnl, wasmDispatchers, imgConfig) if err != nil { return nil, err } if incr == nil { incr = &identity.IncrementByOne{} } if logger == nil { logger = loggers.NewDefault() } permalinks, err := page.NewPermalinkExpander(s.URLize, conf.Permalinks) if err != nil { return nil, err } if common == nil { common = &SpecCommon{ incr: incr, FileCaches: fileCaches, PostBuildAssets: &PostBuildAssets{ PostProcessResources: make(map[string]postpub.PostPublishedResource), JSConfigBuilder: jsconfig.NewBuilder(), }, } } rs := &Spec{ PathSpec: s, Logger: logger, ErrorSender: errorHandler, BuildClosers: buildClosers, Rebuilder: rebuilder, Imaging: imaging, ImageCache: newImageCache( fileCaches.ImageCache(), memCache, s, ), ExecHelper: execHelper, Permalinks: permalinks, SpecCommon: common, } rs.ResourceCache = newResourceCache(rs, memCache) return rs, nil } type Spec struct { *helpers.PathSpec Logger loggers.Logger ErrorSender herrors.ErrorSender BuildClosers types.CloseAdder Rebuilder identity.SignalRebuilder Permalinks page.PermalinkExpander ImageCache *ImageCache // Holds default filter settings etc. Imaging *images.ImageProcessor ExecHelper *hexec.Exec *SpecCommon } // The parts of Spec that's common for all sites. type SpecCommon struct { incr identity.Incrementer ResourceCache *ResourceCache FileCaches filecache.Caches // Assets used after the build is done. // This is shared between all sites. *PostBuildAssets } type PostBuildAssets struct { postProcessMu sync.RWMutex PostProcessResources map[string]postpub.PostPublishedResource JSConfigBuilder *jsconfig.Builder } func (r *Spec) NewResourceWrapperFromResourceConfig(rc *pagemeta.ResourceConfig) (resource.Resource, error) { content := rc.Content switch r := content.Value.(type) { case resource.Resource: return cloneWithMetadataFromResourceConfigIfNeeded(rc, r), nil default: return nil, fmt.Errorf("failed to create resource for path %q, expected a resource.Resource, got %T", rc.PathInfo.Path(), content.Value) } } // NewResource creates a new Resource from the given ResourceSourceDescriptor. func (r *Spec) NewResource(rd ResourceSourceDescriptor) (resource.Resource, error) { if err := rd.init(r); err != nil { return nil, err } dir, name := path.Split(rd.TargetPath) dir = paths.ToSlashPreserveLeading(dir) if dir == "/" { dir = "" } rp := internal.ResourcePaths{ File: name, Dir: dir, BaseDirTarget: rd.BasePathTargetPath, BaseDirLink: rd.BasePathRelPermalink, TargetBasePaths: rd.TargetBasePaths, } isImage := rd.MediaType.MainType == "image" var imgFormat images.Format if isImage { imgFormat, isImage = images.ImageFormatFromMediaSubType(rd.MediaType.SubType) } gr := &genericResource{ Staler: &AtomicStaler{}, h: &resourceHash{}, publishInit: &hsync.OnceMore{}, keyInit: &sync.Once{}, includeHashInKey: isImage, paths: rp, spec: r, sd: rd, params: rd.Params, name: rd.NameOriginal, title: rd.Title, } if isImage { ir := &imageResource{ Image: images.NewImage(imgFormat, r.Imaging, nil, gr), baseResource: gr, } ir.root = ir return newResourceAdapter(gr.spec, rd.LazyPublish, ir), nil } return newResourceAdapter(gr.spec, rd.LazyPublish, gr), nil } func (r *Spec) MediaTypes() media.Types { return r.Cfg.GetConfigSection("mediaTypes").(media.Types) } func (r *Spec) OutputFormats() output.Formats { return r.Cfg.GetConfigSection("outputFormats").(output.Formats) } func (r *Spec) BuildConfig() config.BuildConfig { return r.Cfg.GetConfigSection("build").(config.BuildConfig) } func (s *Spec) String() string { return "spec" }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_cache.go
resources/resource_cache.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources import ( "context" "encoding/json" "io" "path" "path/filepath" "strings" "sync" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/cache/filecache" ) func newResourceCache(rs *Spec, memCache *dynacache.Cache) *ResourceCache { return &ResourceCache{ fileCache: rs.FileCaches.AssetsCache(), cacheResource: dynacache.GetOrCreatePartition[string, resource.Resource]( memCache, "/res1", dynacache.OptionsPartition{ClearWhen: dynacache.ClearOnChange, Weight: 40}, ), cacheResourceFile: dynacache.GetOrCreatePartition[string, resource.Resource]( memCache, "/res2", dynacache.OptionsPartition{ClearWhen: dynacache.ClearOnChange, Weight: 40}, ), CacheResourceRemote: dynacache.GetOrCreatePartition[string, resource.Resource]( memCache, "/resr", dynacache.OptionsPartition{ClearWhen: dynacache.ClearOnChange, Weight: 40}, ), cacheResources: dynacache.GetOrCreatePartition[string, resource.Resources]( memCache, "/ress", dynacache.OptionsPartition{ClearWhen: dynacache.ClearOnRebuild, Weight: 40}, ), cacheResourceTransformation: dynacache.GetOrCreatePartition[string, *resourceAdapterInner]( memCache, "/res1/tra", dynacache.OptionsPartition{ClearWhen: dynacache.ClearOnChange, Weight: 40}, ), } } type ResourceCache struct { sync.RWMutex cacheResource *dynacache.Partition[string, resource.Resource] cacheResourceFile *dynacache.Partition[string, resource.Resource] CacheResourceRemote *dynacache.Partition[string, resource.Resource] cacheResources *dynacache.Partition[string, resource.Resources] cacheResourceTransformation *dynacache.Partition[string, *resourceAdapterInner] fileCache *filecache.Cache } func (c *ResourceCache) cleanKey(key string) string { return strings.TrimPrefix(path.Clean(strings.ToLower(filepath.ToSlash(key))), "/") } func (c *ResourceCache) Get(ctx context.Context, key string) (resource.Resource, bool) { return c.cacheResource.Get(ctx, key) } func (c *ResourceCache) GetOrCreate(key string, f func() (resource.Resource, error)) (resource.Resource, error) { return c.cacheResource.GetOrCreate(key, func(key string) (resource.Resource, error) { return f() }) } func (c *ResourceCache) GetOrCreateFile(key string, f func() (resource.Resource, error)) (resource.Resource, error) { return c.cacheResourceFile.GetOrCreate(key, func(key string) (resource.Resource, error) { return f() }) } func (c *ResourceCache) GetOrCreateResources(key string, f func() (resource.Resources, error)) (resource.Resources, error) { return c.cacheResources.GetOrCreate(key, func(key string) (resource.Resources, error) { return f() }) } func (c *ResourceCache) getFilenames(key string) (string, string) { filenameMeta := key + ".json" filenameContent := key + ".content" return filenameMeta, filenameContent } func (c *ResourceCache) getFromFile(key string) (filecache.ItemInfo, io.ReadCloser, transformedResourceMetadata, bool) { c.RLock() defer c.RUnlock() var meta transformedResourceMetadata filenameMeta, filenameContent := c.getFilenames(key) _, jsonContent, _ := c.fileCache.GetBytes(filenameMeta) if jsonContent == nil { return filecache.ItemInfo{}, nil, meta, false } if err := json.Unmarshal(jsonContent, &meta); err != nil { return filecache.ItemInfo{}, nil, meta, false } fi, rc, _ := c.fileCache.Get(filenameContent) return fi, rc, meta, rc != nil } // writeMeta writes the metadata to file and returns a writer for the content part. func (c *ResourceCache) writeMeta(key string, meta transformedResourceMetadata) (filecache.ItemInfo, io.WriteCloser, error) { filenameMeta, filenameContent := c.getFilenames(key) raw, err := json.Marshal(meta) if err != nil { return filecache.ItemInfo{}, nil, err } _, fm, err := c.fileCache.WriteCloser(filenameMeta) if err != nil { return filecache.ItemInfo{}, nil, err } defer fm.Close() if _, err := fm.Write(raw); err != nil { return filecache.ItemInfo{}, nil, err } fi, fc, err := c.fileCache.WriteCloser(filenameContent) return fi, fc, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/image_cache.go
resources/image_cache.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources import ( "image" "io" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/helpers" ) // ImageCache is a cache for image resources. The backing caches are shared between all sites. type ImageCache struct { pathSpec *helpers.PathSpec fcache *filecache.Cache mcache *dynacache.Partition[string, *resourceAdapter] } func (c *ImageCache) getOrCreate( parent *imageResource, conf images.ImageConfig, createImage func() (*imageResource, image.Image, error), ) (*resourceAdapter, error) { relTarget := parent.relTargetPathFromConfig(conf, parent.getSpec().Imaging.Cfg.SourceHash) relTargetPath := relTarget.TargetPath() memKey := relTargetPath // For multihost sites, we duplicate language versions of the same resource, // so we need to include the language in the key. // Note that we don't need to include the language in the file cache key, // as the hash will take care of any different content. if c.pathSpec.Cfg.IsMultihost() { memKey = c.pathSpec.Lang() + memKey } memKey = dynacache.CleanKey(memKey) v, err := c.mcache.GetOrCreate(memKey, func(key string) (*resourceAdapter, error) { var img *imageResource // These funcs are protected by a named lock. // read clones the parent to its new name and copies // the content to the destinations. read := func(info filecache.ItemInfo, r io.ReadSeeker) error { img = parent.clone(nil) targetPath := img.getResourcePaths() targetPath.File = relTarget.File img.setTargetPath(targetPath) img.setOpenSource(func() (hugio.ReadSeekCloser, error) { return c.fcache.Fs.Open(info.Name) }) img.setSourceFilenameIsHash(true) img.setMediaType(conf.TargetFormat.MediaType()) if err := img.InitConfig(r); err != nil { return err } return nil } // create creates the image and encodes it to the cache (w). create := func(info filecache.ItemInfo, w io.WriteCloser) (err error) { defer w.Close() var conv image.Image img, conv, err = createImage() if err != nil { return } targetPath := img.getResourcePaths() targetPath.File = relTarget.File img.setTargetPath(targetPath) img.setOpenSource(func() (hugio.ReadSeekCloser, error) { return c.fcache.Fs.Open(info.Name) }) return img.EncodeTo(conf, conv, w) } // Now look in the file cache. // The definition of this counter is not that we have processed that amount // (e.g. resized etc.), it can be fetched from file cache, // but the count of processed image variations for this site. c.pathSpec.ProcessingStats.Incr(&c.pathSpec.ProcessingStats.ProcessedImages) _, err := c.fcache.ReadOrCreate(relTargetPath, read, create) if err != nil { return nil, err } imgAdapter := newResourceAdapter(parent.getSpec(), true, img) return imgAdapter, nil }) return v, err } func newImageCache(fileCache *filecache.Cache, memCache *dynacache.Cache, ps *helpers.PathSpec) *ImageCache { return &ImageCache{ fcache: fileCache, mcache: dynacache.GetOrCreatePartition[string, *resourceAdapter]( memCache, "/imgs", dynacache.OptionsPartition{ClearWhen: dynacache.ClearOnChange, Weight: 70}, ), pathSpec: ps, } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/image.go
resources/image.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources import ( "encoding/json" "fmt" "image" "image/color" "image/draw" "io" "os" "strings" "sync" color_extractor "github.com/marekm4/color-extractor" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/paths" "github.com/disintegration/gift" "github.com/gohugoio/hugo/resources/images/exif" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/images" ) var ( _ images.ImageResource = (*imageResource)(nil) _ resource.Source = (*imageResource)(nil) _ resource.Cloner = (*imageResource)(nil) _ resource.NameNormalizedProvider = (*imageResource)(nil) _ targetPathProvider = (*imageResource)(nil) ) // imageResource represents an image resource. type imageResource struct { *images.Image // When a image is processed in a chain, this holds the reference to the // original (first). root *imageResource metaInit sync.Once metaInitErr error meta *imageMeta dominantColorInit sync.Once dominantColors []images.Color baseResource } type imageMeta struct { Exif *exif.ExifInfo } func (i *imageResource) Exif() *exif.ExifInfo { return i.root.getExif() } func (i *imageResource) getExif() *exif.ExifInfo { i.metaInit.Do(func() { mf := i.Format.ToImageMetaImageFormatFormat() if mf == -1 { // No Exif support for this format. return } key := i.getImageMetaCacheTargetPath() read := func(info filecache.ItemInfo, r io.ReadSeeker) error { meta := &imageMeta{} data, err := io.ReadAll(r) if err != nil { return err } if err = json.Unmarshal(data, &meta); err != nil { return err } i.meta = meta return nil } create := func(info filecache.ItemInfo, w io.WriteCloser) (err error) { defer w.Close() f, err := i.root.ReadSeekCloser() if err != nil { i.metaInitErr = err return } defer f.Close() filename := i.getResourcePaths().Path() x, err := i.getSpec().Imaging.DecodeExif(filename, mf, f) if err != nil { i.getSpec().Logger.Warnf("Unable to decode Exif metadata from image: %s", i.Key()) return nil } i.meta = &imageMeta{Exif: x} // Also write it to cache enc := json.NewEncoder(w) return enc.Encode(i.meta) } _, i.metaInitErr = i.getSpec().ImageCache.fcache.ReadOrCreate(key, read, create) }) if i.metaInitErr != nil { panic(fmt.Sprintf("metadata init failed: %s", i.metaInitErr)) } if i.meta == nil { return nil } return i.meta.Exif } // Colors returns a slice of the most dominant colors in an image // using a simple histogram method. func (i *imageResource) Colors() ([]images.Color, error) { var err error i.dominantColorInit.Do(func() { var img image.Image img, err = i.DecodeImage() if err != nil { return } colors := color_extractor.ExtractColors(img) for _, c := range colors { i.dominantColors = append(i.dominantColors, images.ColorGoToColor(c)) } }) return i.dominantColors, nil } func (i *imageResource) targetPath() string { return i.TargetPath() } // Clone is for internal use. func (i *imageResource) Clone() resource.Resource { gr := i.baseResource.Clone().(baseResource) return &imageResource{ root: i.root, Image: i.WithSpec(gr), baseResource: gr, } } func (i *imageResource) cloneTo(targetPath string) resource.Resource { gr := i.baseResource.cloneTo(targetPath).(baseResource) return &imageResource{ root: i.root, Image: i.WithSpec(gr), baseResource: gr, } } func (i *imageResource) cloneWithUpdates(u *transformationUpdate) (baseResource, error) { base, err := i.baseResource.cloneWithUpdates(u) if err != nil { return nil, err } var img *images.Image if u.isContentChanged() { img = i.WithSpec(base) } else { img = i.Image } return &imageResource{ root: i.root, Image: img, baseResource: base, }, nil } // Process processes the image with the given spec. // The spec can contain an optional action, one of "resize", "crop", "fit" or "fill". // This makes this method a more flexible version that covers all of Resize, Crop, Fit and Fill, // but it also supports e.g. format conversions without any resize action. func (i *imageResource) Process(spec string) (images.ImageResource, error) { return i.processActionSpec("", spec) } // Resize resizes the image to the specified width and height using the specified resampling // filter and returns the transformed image. If one of width or height is 0, the image aspect // ratio is preserved. func (i *imageResource) Resize(spec string) (images.ImageResource, error) { return i.processActionSpec(images.ActionResize, spec) } // Crop the image to the specified dimensions without resizing using the given anchor point. // Space delimited config, e.g. `200x300 TopLeft`. func (i *imageResource) Crop(spec string) (images.ImageResource, error) { return i.processActionSpec(images.ActionCrop, spec) } // Fit scales down the image using the specified resample filter to fit the specified // maximum width and height. func (i *imageResource) Fit(spec string) (images.ImageResource, error) { return i.processActionSpec(images.ActionFit, spec) } // Fill scales the image to the smallest possible size that will cover the specified dimensions, // crops the resized image to the specified dimensions using the given anchor point. // Space delimited config, e.g. `200x300 TopLeft`. func (i *imageResource) Fill(spec string) (images.ImageResource, error) { return i.processActionSpec(images.ActionFill, spec) } func (i *imageResource) Filter(filters ...any) (images.ImageResource, error) { var confMain images.ImageConfig var gfilters []gift.Filter for _, f := range filters { gfilters = append(gfilters, images.ToFilters(f)...) } var options []string for _, f := range gfilters { f = images.UnwrapFilter(f) if specProvider, ok := f.(images.ImageProcessSpecProvider); ok { options = append(options, strings.Fields(specProvider.ImageProcessSpec())...) } } confMain, err := images.DecodeImageConfig(options, i.Proc.Cfg, i.Format) if err != nil { return nil, err } confMain.Action = "filter" confMain.Key = hashing.HashString(gfilters) return i.doWithImageConfig(confMain, func(src image.Image) (image.Image, error) { var filters []gift.Filter for _, f := range gfilters { f = images.UnwrapFilter(f) if specProvider, ok := f.(images.ImageProcessSpecProvider); ok { options := strings.Fields(specProvider.ImageProcessSpec()) conf, err := images.DecodeImageConfig(options, i.Proc.Cfg, i.Format) if err != nil { return nil, err } pFilters, err := i.Proc.FiltersFromConfig(src, conf) if err != nil { return nil, err } filters = append(filters, pFilters...) } else if orientationProvider, ok := f.(images.ImageFilterFromOrientationProvider); ok { tf := orientationProvider.AutoOrient(i.Exif()) if tf != nil { filters = append(filters, tf) } } else { filters = append(filters, f) } } return i.Proc.Filter(src, filters...) }) } func (i *imageResource) processActionSpec(action, spec string) (images.ImageResource, error) { options := append([]string{action}, strings.Fields(strings.ToLower(spec))...) ir, err := i.processOptions(options) if err != nil { if sourcePath := i.sourcePath(); sourcePath != "" { err = fmt.Errorf("failed to %s image %q: %w", action, sourcePath, err) } return nil, err } return ir, nil } func (i *imageResource) processOptions(options []string) (images.ImageResource, error) { conf, err := images.DecodeImageConfig(options, i.Proc.Cfg, i.Format) if err != nil { return nil, err } img, err := i.doWithImageConfig(conf, func(src image.Image) (image.Image, error) { return i.Proc.ApplyFiltersFromConfig(src, conf) }) if err != nil { return nil, err } if conf.Action == images.ActionFill { if conf.Anchor == images.SmartCropAnchor && img.Width() == 0 || img.Height() == 0 { // See https://github.com/gohugoio/hugo/issues/7955 // Smartcrop fails silently in some rare cases. // Fall back to a center fill. conf = conf.Reanchor(gift.CenterAnchor) return i.doWithImageConfig(conf, func(src image.Image) (image.Image, error) { return i.Proc.ApplyFiltersFromConfig(src, conf) }) } } return img, nil } // Serialize image processing. The imaging library spins up its own set of Go routines, // so there is not much to gain from adding more load to the mix. That // can even have negative effect in low resource scenarios. // Note that this only effects the non-cached scenario. Once the processed // image is written to disk, everything is fast, fast fast. const imageProcWorkers = 1 var imageProcSem = make(chan bool, imageProcWorkers) func (i *imageResource) doWithImageConfig(conf images.ImageConfig, f func(src image.Image) (image.Image, error)) (images.ImageResource, error) { img, err := i.getSpec().ImageCache.getOrCreate(i, conf, func() (*imageResource, image.Image, error) { imageProcSem <- true defer func() { <-imageProcSem }() src, err := i.DecodeImage() if err != nil { return nil, nil, &os.PathError{Op: conf.Action, Path: i.TargetPath(), Err: err} } converted, err := f(src) if err != nil { return nil, nil, &os.PathError{Op: conf.Action, Path: i.TargetPath(), Err: err} } hasAlpha := !images.IsOpaque(converted) shouldFill := conf.BgColor != nil && hasAlpha shouldFill = shouldFill || (!conf.TargetFormat.SupportsTransparency() && hasAlpha) var bgColor color.Color if shouldFill { bgColor = conf.BgColor if bgColor == nil { bgColor = i.Proc.Cfg.Config.BgColor } tmp := image.NewRGBA(converted.Bounds()) draw.Draw(tmp, tmp.Bounds(), image.NewUniform(bgColor), image.Point{}, draw.Src) draw.Draw(tmp, tmp.Bounds(), converted, converted.Bounds().Min, draw.Over) converted = tmp } if conf.TargetFormat == images.PNG { // Apply the colour palette from the source if paletted, ok := src.(*image.Paletted); ok { palette := paletted.Palette if bgColor != nil && len(palette) < 256 { palette = images.AddColorToPalette(bgColor, palette) } else if bgColor != nil { images.ReplaceColorInPalette(bgColor, palette) } tmp := image.NewPaletted(converted.Bounds(), palette) draw.FloydSteinberg.Draw(tmp, tmp.Bounds(), converted, converted.Bounds().Min) converted = tmp } } ci := i.clone(converted) targetPath := i.relTargetPathFromConfig(conf, i.getSpec().Imaging.Cfg.SourceHash) ci.setTargetPath(targetPath) ci.Format = conf.TargetFormat ci.setMediaType(conf.TargetFormat.MediaType()) return ci, converted, nil }) if err != nil { return nil, err } return img, nil } // DecodeImage decodes the image source into an Image. // This for internal use only. func (i *imageResource) DecodeImage() (image.Image, error) { f, err := i.ReadSeekCloser() if err != nil { return nil, fmt.Errorf("failed to open image for decode: %w", err) } defer f.Close() return i.getSpec().Imaging.Codec.DecodeFormat(i.Format, f) } func (i *imageResource) clone(img image.Image) *imageResource { spec := i.baseResource.Clone().(baseResource) var image *images.Image if img != nil { image = i.WithImage(img) } else { image = i.WithSpec(spec) } return &imageResource{ Image: image, root: i.root, baseResource: spec, } } func (i *imageResource) getImageMetaCacheTargetPath() string { // Increment to invalidate the meta cache // Last increment: v0.130.0 when change to the new imagemeta library for Exif. const imageMetaVersionNumber = 2 cfgHash := i.getSpec().Imaging.Cfg.SourceHash df := i.getResourcePaths() p1, _ := paths.FileAndExt(df.File) h := i.hash() idStr := hashing.HashStringHex(h, i.size(), imageMetaVersionNumber, cfgHash) df.File = fmt.Sprintf("%s_%s.json", p1, idStr) return df.TargetPath() } func (i *imageResource) relTargetPathFromConfig(conf images.ImageConfig, imagingConfigSourceHash string) internal.ResourcePaths { p1, p2 := paths.FileAndExt(i.getResourcePaths().File) if conf.TargetFormat != i.Format { p2 = conf.TargetFormat.DefaultExtension() } // Do not change. const imageHashPrefix = "_hu_" huIdx := strings.LastIndex(p1, imageHashPrefix) incomingID := "" if huIdx > -1 { incomingID = p1[huIdx+len(imageHashPrefix):] p1 = p1[:huIdx] } hash := hashing.HashStringHex(incomingID, i.hash(), conf.Key, imagingConfigSourceHash) rp := i.getResourcePaths() rp.File = fmt.Sprintf("%s%s%s%s", p1, imageHashPrefix, hash, p2) return rp }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/image_test.go
resources/image_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources_test import ( "context" "fmt" "io/fs" "math/rand" "os" "strconv" "sync" "testing" "time" "github.com/bep/imagemeta" "github.com/gohugoio/hugo/common/paths" "github.com/spf13/afero" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/images" "github.com/google/go-cmp/cmp" "github.com/gohugoio/hugo/htesting/hqt" qt "github.com/frankban/quicktest" ) var eq = qt.CmpEquals( cmp.Comparer(func(p1, p2 os.FileInfo) bool { return p1.Name() == p2.Name() && p1.Size() == p2.Size() && p1.IsDir() == p2.IsDir() }), cmp.Comparer(func(d1, d2 fs.DirEntry) bool { p1, err1 := d1.Info() p2, err2 := d2.Info() if err1 != nil || err2 != nil { return false } return p1.Name() == p2.Name() && p1.Size() == p2.Size() && p1.IsDir() == p2.IsDir() }), // cmp.Comparer(func(p1, p2 *genericResource) bool { return p1 == p2 }), cmp.Comparer(func(m1, m2 media.Type) bool { return m1.Type == m2.Type }), cmp.Comparer( func(v1, v2 imagemeta.Rat[uint32]) bool { return v1.String() == v2.String() }, ), cmp.Comparer( func(v1, v2 imagemeta.Rat[int32]) bool { return v1.String() == v2.String() }, ), cmp.Comparer(func(v1, v2 time.Time) bool { return v1.Unix() == v2.Unix() }), ) func TestImageTransformBasic(t *testing.T) { c := qt.New(t) _, image := fetchSunset(c) assertWidthHeight := func(img images.ImageResource, w, h int) { assertWidthHeight(c, img, w, h) } gotColors, err := image.Colors() c.Assert(err, qt.IsNil) expectedColors := images.HexStringsToColors("#2d2f33", "#a49e93", "#d39e59", "#a76936", "#737a84", "#7c838b") c.Assert(len(gotColors), qt.Equals, len(expectedColors)) for i := range gotColors { c1, c2 := gotColors[i], expectedColors[i] c.Assert(c1.ColorHex(), qt.Equals, c2.ColorHex()) c.Assert(c1.ColorGo(), qt.DeepEquals, c2.ColorGo()) c.Assert(c1.Luminance(), qt.Equals, c2.Luminance()) } c.Assert(image.RelPermalink(), qt.Equals, "/a/sunset.jpg") c.Assert(image.ResourceType(), qt.Equals, "image") assertWidthHeight(image, 900, 562) resized, err := image.Resize("300x200") c.Assert(err, qt.IsNil) c.Assert(image != resized, qt.Equals, true) assertWidthHeight(resized, 300, 200) assertWidthHeight(image, 900, 562) resized0x, err := image.Resize("x200") c.Assert(err, qt.IsNil) assertWidthHeight(resized0x, 320, 200) resizedx0, err := image.Resize("200x") c.Assert(err, qt.IsNil) assertWidthHeight(resizedx0, 200, 125) resizedAndRotated, err := image.Resize("x200 r90") c.Assert(err, qt.IsNil) assertWidthHeight(resizedAndRotated, 125, 200) assertWidthHeight(resized, 300, 200) c.Assert(resized.RelPermalink(), qt.Equals, "/a/sunset_hu_f4f15cdbaaca3b2d.jpg") fitted, err := resized.Fit("50x50") c.Assert(err, qt.IsNil) c.Assert(fitted.RelPermalink(), qt.Equals, "/a/sunset_hu_c9781e950a09210.jpg") assertWidthHeight(fitted, 50, 33) // Check the MD5 key threshold fittedAgain, _ := fitted.Fit("10x20") fittedAgain, err = fittedAgain.Fit("10x20") c.Assert(err, qt.IsNil) c.Assert(fittedAgain.RelPermalink(), qt.Equals, "/a/sunset_hu_78c1665fdce5ec4d.jpg") assertWidthHeight(fittedAgain, 10, 7) filled, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled.RelPermalink(), qt.Equals, "/a/sunset_hu_b3e01daae854e587.jpg") assertWidthHeight(filled, 200, 100) smart, err := image.Fill("200x100 smart") c.Assert(err, qt.IsNil) c.Assert(smart.RelPermalink(), qt.Equals, "/a/sunset_hu_622a1375d91d9312.jpg") assertWidthHeight(smart, 200, 100) // Check cache filledAgain, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled, qt.Equals, filledAgain) cropped, err := image.Crop("300x300 topRight") c.Assert(err, qt.IsNil) c.Assert(cropped.RelPermalink(), qt.Equals, "/a/sunset_hu_9016246670a22728.jpg") assertWidthHeight(cropped, 300, 300) smartcropped, err := image.Crop("200x200 smart") c.Assert(err, qt.IsNil) c.Assert(smartcropped.RelPermalink(), qt.Equals, "/a/sunset_hu_78e9677f68b821ed.jpg") assertWidthHeight(smartcropped, 200, 200) // Check cache croppedAgain, err := image.Crop("300x300 topRight") c.Assert(err, qt.IsNil) c.Assert(cropped, qt.Equals, croppedAgain) } func TestImageProcess(t *testing.T) { c := qt.New(t) _, img := fetchSunset(c) resized, err := img.Process("resiZe 300x200") c.Assert(err, qt.IsNil) assertWidthHeight(c, resized, 300, 200) rotated, err := resized.Process("R90") c.Assert(err, qt.IsNil) assertWidthHeight(c, rotated, 200, 300) converted, err := img.Process("png") c.Assert(err, qt.IsNil) c.Assert(converted.MediaType().Type, qt.Equals, "image/png") checkProcessVsMethod := func(action, spec string) { var expect images.ImageResource var err error switch action { case images.ActionCrop: expect, err = img.Crop(spec) case images.ActionFill: expect, err = img.Fill(spec) case images.ActionFit: expect, err = img.Fit(spec) case images.ActionResize: expect, err = img.Resize(spec) } c.Assert(err, qt.IsNil) got, err := img.Process(spec + " " + action) c.Assert(err, qt.IsNil) assertWidthHeight(c, got, expect.Width(), expect.Height()) c.Assert(got.MediaType(), qt.Equals, expect.MediaType()) } checkProcessVsMethod(images.ActionCrop, "300x200 topleFt") checkProcessVsMethod(images.ActionFill, "300x200 topleft") checkProcessVsMethod(images.ActionFit, "300x200 png") checkProcessVsMethod(images.ActionResize, "300x R90") } func TestImageTransformFormat(t *testing.T) { c := qt.New(t) _, image := fetchSunset(c) assertExtWidthHeight := func(img images.ImageResource, ext string, w, h int) { c.Helper() c.Assert(img, qt.Not(qt.IsNil)) c.Assert(paths.Ext(img.RelPermalink()), qt.Equals, ext) c.Assert(img.Width(), qt.Equals, w) c.Assert(img.Height(), qt.Equals, h) } c.Assert(image.RelPermalink(), qt.Equals, "/a/sunset.jpg") c.Assert(image.ResourceType(), qt.Equals, "image") assertExtWidthHeight(image, ".jpg", 900, 562) imagePng, err := image.Resize("450x png") c.Assert(err, qt.IsNil) c.Assert(imagePng.RelPermalink(), qt.Equals, "/a/sunset_hu_63ccccb11ff4e285.png") c.Assert(imagePng.ResourceType(), qt.Equals, "image") assertExtWidthHeight(imagePng, ".png", 450, 281) c.Assert(imagePng.Name(), qt.Equals, "sunset.jpg") c.Assert(imagePng.MediaType().String(), qt.Equals, "image/png") imageGif, err := image.Resize("225x gif") c.Assert(err, qt.IsNil) c.Assert(imageGif.RelPermalink(), qt.Equals, "/a/sunset_hu_6d1f23c09eddc748.gif") c.Assert(imageGif.ResourceType(), qt.Equals, "image") assertExtWidthHeight(imageGif, ".gif", 225, 141) c.Assert(imageGif.Name(), qt.Equals, "sunset.jpg") c.Assert(imageGif.MediaType().String(), qt.Equals, "image/gif") } // https://github.com/gohugoio/hugo/issues/5730 func TestImagePermalinkPublishOrder(t *testing.T) { for _, checkOriginalFirst := range []bool{true, false} { name := "OriginalFirst" if !checkOriginalFirst { name = "ResizedFirst" } t.Run(name, func(t *testing.T) { c := qt.New(t) spec, workDir := newTestResourceOsFs(c) defer func() { os.Remove(workDir) }() check1 := func(img images.ImageResource) { resizedLink := "/a/sunset_hu_3a097ae28aebc166.jpg" c.Assert(img.RelPermalink(), qt.Equals, resizedLink) assertImageFile(c, spec.PublishFs, resizedLink, 100, 50) } check2 := func(img images.ImageResource) { c.Assert(img.RelPermalink(), qt.Equals, "/a/sunset.jpg") assertImageFile(c, spec.PublishFs, "a/sunset.jpg", 900, 562) } original := fetchImageForSpec(spec, c, "sunset.jpg") c.Assert(original, qt.Not(qt.IsNil)) if checkOriginalFirst { check2(original) } resized, err := original.Resize("100x50") c.Assert(err, qt.IsNil) check1(resized) if !checkOriginalFirst { check2(original) } }) } } func TestImageBugs(t *testing.T) { c := qt.New(t) // Issue #4261 c.Run("Transform long filename", func(c *qt.C) { _, image := fetchImage(c, "1234567890qwertyuiopasdfghjklzxcvbnm5to6eeeeee7via8eleph.jpg") c.Assert(image, qt.Not(qt.IsNil)) resized, err := image.Resize("200x") c.Assert(err, qt.IsNil) c.Assert(resized, qt.Not(qt.IsNil)) c.Assert(resized.Width(), qt.Equals, 200) c.Assert(resized.RelPermalink(), qt.Equals, "/a/1234567890qwertyuiopasdfghjklzxcvbnm5to6eeeeee7via8eleph_hu_a6f31c42e1afef07.jpg") resized, err = resized.Resize("100x") c.Assert(err, qt.IsNil) c.Assert(resized, qt.Not(qt.IsNil)) c.Assert(resized.Width(), qt.Equals, 100) c.Assert(resized.RelPermalink(), qt.Equals, "/a/1234567890qwertyuiopasdfghjklzxcvbnm5to6eeeeee7via8eleph_hu_14e106419fe28039.jpg") }) // Issue #6137 c.Run("Transform upper case extension", func(c *qt.C) { _, image := fetchImage(c, "sunrise.JPG") resized, err := image.Resize("200x") c.Assert(err, qt.IsNil) c.Assert(resized, qt.Not(qt.IsNil)) c.Assert(resized.Width(), qt.Equals, 200) }) // Issue #7955 c.Run("Fill with smartcrop", func(c *qt.C) { _, sunset := fetchImage(c, "sunset.jpg") for _, test := range []struct { originalDimensions string targetWH int }{ {"408x403", 400}, {"425x403", 400}, {"459x429", 400}, {"476x442", 400}, {"544x403", 400}, {"476x468", 400}, {"578x585", 550}, {"578x598", 550}, } { c.Run(test.originalDimensions, func(c *qt.C) { image, err := sunset.Resize(test.originalDimensions) c.Assert(err, qt.IsNil) resized, err := image.Fill(fmt.Sprintf("%dx%d smart", test.targetWH, test.targetWH)) c.Assert(err, qt.IsNil) c.Assert(resized, qt.Not(qt.IsNil)) c.Assert(resized.Width(), qt.Equals, test.targetWH) c.Assert(resized.Height(), qt.Equals, test.targetWH) }) } }) } func TestImageTransformConcurrent(t *testing.T) { var wg sync.WaitGroup c := qt.New(t) spec, workDir := newTestResourceOsFs(c) defer func() { os.Remove(workDir) }() image := fetchImageForSpec(spec, c, "sunset.jpg") for i := range 4 { wg.Add(1) go func(id int) { defer wg.Done() for j := range 5 { img := image for k := range 2 { r1, err := img.Resize(fmt.Sprintf("%dx", id-k)) if err != nil { t.Error(err) } if r1.Width() != id-k { t.Errorf("Width: %d:%d", r1.Width(), j) } r2, err := r1.Resize(fmt.Sprintf("%dx", id-k-1)) if err != nil { t.Error(err) } img = r2 } } }(i + 20) } wg.Wait() } func TestImageResize8BitPNG(t *testing.T) { c := qt.New(t) _, image := fetchImage(c, "gohugoio.png") c.Assert(image.MediaType().Type, qt.Equals, "image/png") c.Assert(image.RelPermalink(), qt.Equals, "/a/gohugoio.png") c.Assert(image.ResourceType(), qt.Equals, "image") c.Assert(image.Exif(), qt.IsNotNil) resized, err := image.Resize("800x") c.Assert(err, qt.IsNil) c.Assert(resized.MediaType().Type, qt.Equals, "image/png") c.Assert(resized.RelPermalink(), qt.Equals, "/a/gohugoio_hu_626cfc4db4222bfe.png") c.Assert(resized.Width(), qt.Equals, 800) } func TestSVGImage(t *testing.T) { c := qt.New(t) spec := newTestResourceSpec(specDescriptor{c: c}) svg := fetchResourceForSpec(spec, c, "circle.svg") c.Assert(svg, qt.Not(qt.IsNil)) } func TestSVGImageContent(t *testing.T) { c := qt.New(t) spec := newTestResourceSpec(specDescriptor{c: c}) svg := fetchResourceForSpec(spec, c, "circle.svg") c.Assert(svg, qt.Not(qt.IsNil)) content, err := svg.Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, hqt.IsSameType, "") c.Assert(content.(string), qt.Contains, `<svg height="100" width="100">`) } func TestImageExif(t *testing.T) { c := qt.New(t) fs := afero.NewMemMapFs() spec := newTestResourceSpec(specDescriptor{fs: fs, c: c}) image := fetchResourceForSpec(spec, c, "sunset.jpg").(images.ImageResource) getAndCheckExif := func(c *qt.C, image images.ImageResource) { x := image.Exif() c.Assert(x, qt.Not(qt.IsNil)) c.Assert(x.Date.Format("2006-01-02"), qt.Equals, "2017-10-27") // Malaga: https://goo.gl/taazZy c.Assert(x.Lat, qt.Equals, float64(36.59744166666667)) c.Assert(x.Long, qt.Equals, float64(-4.50846)) v, found := x.Tags["LensModel"] c.Assert(found, qt.Equals, true) lensModel, ok := v.(string) c.Assert(ok, qt.Equals, true) c.Assert(lensModel, qt.Equals, "smc PENTAX-DA* 16-50mm F2.8 ED AL [IF] SDM") resized, _ := image.Resize("300x200") x2 := resized.Exif() c.Assert(x2, eq, x) } getAndCheckExif(c, image) image = fetchResourceForSpec(spec, c, "sunset.jpg").(images.ImageResource) // This will read from file cache. getAndCheckExif(c, image) } func TestImageColorsLuminance(t *testing.T) { c := qt.New(t) _, image := fetchSunset(c) c.Assert(image, qt.Not(qt.IsNil)) colors, err := image.Colors() c.Assert(err, qt.IsNil) c.Assert(len(colors), qt.Equals, 6) var prevLuminance float64 for i, color := range colors { luminance := color.Luminance() c.Assert(err, qt.IsNil) c.Assert(luminance > 0, qt.IsTrue) c.Assert(luminance, qt.Not(qt.Equals), prevLuminance, qt.Commentf("i=%d", i)) prevLuminance = luminance } } func BenchmarkImageExif(b *testing.B) { getImage := func(i int, c *qt.C, b *testing.B, fs afero.Fs) images.ImageResource { spec := newTestResourceSpec(specDescriptor{fs: fs, c: c}) return fetchResourceForSpec(spec, c, "sunset.jpg", strconv.Itoa(i)).(images.ImageResource) } getAndCheckExif := func(c *qt.C, image images.ImageResource) { x := image.Exif() c.Assert(x, qt.Not(qt.IsNil)) c.Assert(x.Long, qt.Equals, float64(-4.50846)) } b.Run("Cold cache", func(b *testing.B) { c := qt.New(b) fs := afero.NewMemMapFs() for i := 0; b.Loop(); i++ { b.StopTimer() image := getImage(i, c, b, fs) b.StartTimer() getAndCheckExif(c, image) } }) b.Run("Cold cache, 10", func(b *testing.B) { c := qt.New(b) fs := afero.NewMemMapFs() for i := 0; b.Loop(); i++ { b.StopTimer() image := getImage(i, c, b, fs) b.StartTimer() for range 10 { getAndCheckExif(c, image) } } }) b.Run("Warm cache", func(b *testing.B) { c := qt.New(b) fs := afero.NewMemMapFs() // Prime the cache for i := 0; i < b.N; i++ { image := getImage(i, c, b, fs) getAndCheckExif(c, image) } // Start the real benchmark, b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() image := getImage(i, c, b, fs) b.StartTimer() getAndCheckExif(c, image) } }) } func BenchmarkResizeParallel(b *testing.B) { c := qt.New(b) _, img := fetchSunset(c) b.RunParallel(func(pb *testing.PB) { for pb.Next() { w := rand.Intn(10) + 10 resized, err := img.Resize(strconv.Itoa(w) + "x") if err != nil { b.Fatal(err) } _, err = resized.Resize(strconv.Itoa(w-1) + "x") if err != nil { b.Fatal(err) } } }) } func assertWidthHeight(c *qt.C, img images.ImageResource, w, h int) { c.Helper() c.Assert(img, qt.Not(qt.IsNil)) c.Assert(img.Width(), qt.Equals, w) c.Assert(img.Height(), qt.Equals, h) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_spec_test.go
resources/resource_spec_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources" ) func TestNewResource(t *testing.T) { c := qt.New(t) spec := newTestResourceSpec(specDescriptor{c: c}) open := hugio.NewOpenReadSeekCloser(hugio.NewReadSeekerNoOpCloserFromString("content")) rd := resources.ResourceSourceDescriptor{ OpenReadSeekCloser: open, TargetPath: "a/b.txt", BasePathRelPermalink: "c/d", BasePathTargetPath: "e/f", GroupIdentity: identity.Anonymous, } r, err := spec.NewResource(rd) c.Assert(err, qt.IsNil) c.Assert(r, qt.Not(qt.IsNil)) c.Assert(r.RelPermalink(), qt.Equals, "/c/d/a/b.txt") info := resources.GetTestInfoForResource(r) c.Assert(info.Paths.TargetLink(), qt.Equals, "/c/d/a/b.txt") c.Assert(info.Paths.TargetPath(), qt.Equals, "/e/f/a/b.txt") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/transform_test.go
resources/transform_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources_test import ( "context" "encoding/base64" "fmt" "io" "path/filepath" "strconv" "strings" "sync" "testing" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/resource" "github.com/spf13/afero" qt "github.com/frankban/quicktest" ) const gopher = `iVBORw0KGgoAAAANSUhEUgAAAEsAAAA8CAAAAAALAhhPAAAFfUlEQVRYw62XeWwUVRzHf2+OPbo9d7tsWyiyaZti6eWGAhISoIGKECEKCAiJJkYTiUgTMYSIosYYBBIUIxoSPIINEBDi2VhwkQrVsj1ESgu9doHWdrul7ba73WNm3vOPtsseM9MdwvvrzTs+8/t95ze/33sI5BqiabU6m9En8oNjduLnAEDLUsQXFF8tQ5oxK3vmnNmDSMtrncks9Hhtt/qeWZapHb1ha3UqYSWVl2ZmpWgaXMXGohQAvmeop3bjTRtv6SgaK/Pb9/bFzUrYslbFAmHPp+3WhAYdr+7GN/YnpN46Opv55VDsJkoEpMrY/vO2BIYQ6LLvm0ThY3MzDzzeSJeeWNyTkgnIE5ePKsvKlcg/0T9QMzXalwXMlj54z4c0rh/mzEfr+FgWEz2w6uk8dkzFAgcARAgNp1ZYef8bH2AgvuStbc2/i6CiWGj98y2tw2l4FAXKkQBIf+exyRnteY83LfEwDQAYCoK+P6bxkZm/0966LxcAAILHB56kgD95PPxltuYcMtFTWw/FKkY/6Opf3GGd9ZF+Qp6mzJxzuRSractOmJrH1u8XTvWFHINNkLQLMR+XHXvfPPHw967raE1xxwtA36IMRfkAAG29/7mLuQcb2WOnsJReZGfpiHsSBX81cvMKywYZHhX5hFPtOqPGWZCXnhWGAu6lX91ElKXSalcLXu3UaOXVay57ZSe5f6Gpx7J2MXAsi7EqSp09b/MirKSyJfnfEEgeDjl8FgDAfvewP03zZ+AJ0m9aFRM8eEHBDRKjfcreDXnZdQuAxXpT2NRJ7xl3UkLBhuVGU16gZiGOgZmrSbRdqkILuL/yYoSXHHkl9KXgqNu3PB8oRg0geC5vFmLjad6mUyTKLmF3OtraWDIfACyXqmephaDABawfpi6tqqBZytfQMqOz6S09iWXhktrRaB8Xz4Yi/8gyABDm5NVe6qq/3VzPrcjELWrebVuyY2T7ar4zQyybUCtsQ5Es1FGaZVrRVQwAgHGW2ZCRZshI5bGQi7HesyE972pOSeMM0dSktlzxRdrlqb3Osa6CCS8IJoQQQgBAbTAa5l5epO34rJszibJI8rxLfGzcp1dRosutGeb2VDNgqYrwTiPNsLxXiPi3dz7LiS1WBRBDBOnqEjyy3aQb+/bLiJzz9dIkscVBBLxMfSEac7kO4Fpkngi0ruNBeSOal+u8jgOuqPz12nryMLCniEjtOOOmpt+KEIqsEdocJjYXwrh9OZqWJQyPCTo67LNS/TdxLAv6R5ZNK9npEjbYdT33gRo4o5oTqR34R+OmaSzDBWsAIPhuRcgyoteNi9gF0KzNYWVItPf2TLoXEg+7isNC7uJkgo1iQWOfRSP9NR11RtbZZ3OMG/VhL6jvx+J1m87+RCfJChAtEBQkSBX2PnSiihc/Twh3j0h7qdYQAoRVsRGmq7HU2QRbaxVGa1D6nIOqaIWRjyRZpHMQKWKpZM5feA+lzC4ZFultV8S6T0mzQGhQohi5I8iw+CsqBSxhFMuwyLgSwbghGb0AiIKkSDmGZVmJSiKihsiyOAUs70UkywooYP0bii9GdH4sfr1UNysd3fUyLLMQN+rsmo3grHl9VNJHbbwxoa47Vw5gupIqrZcjPh9R4Nye3nRDk199V+aetmvVtDRE8/+cbgAAgMIWGb3UA0MGLE9SCbWX670TDy1y98c3D27eppUjsZ6fql3jcd5rUe7+ZIlLNQny3Rd+E5Tct3WVhTM5RBCEdiEK0b6B+/ca2gYU393nFj/n1AygRQxPIUA043M42u85+z2SnssKrPl8Mx76NL3E6eXc3be7OD+H4WHbJkKI8AU8irbITQjZ+0hQcPEgId/Fn/pl9crKH02+5o2b9T/eMx7pKoskYgAAAABJRU5ErkJggg==` func gopherPNG() io.Reader { return base64.NewDecoder(base64.StdEncoding, strings.NewReader(gopher)) } func TestTransform(t *testing.T) { createTransformer := func(c *qt.C, spec *resources.Spec, filename, content string) resources.Transformer { targetPath := identity.CleanString(filename) r, err := spec.NewResource(resources.ResourceSourceDescriptor{ TargetPath: targetPath, OpenReadSeekCloser: hugio.NewOpenReadSeekCloser(hugio.NewReadSeekerNoOpCloserFromString(content)), GroupIdentity: identity.StringIdentity(targetPath), }) c.Assert(err, qt.IsNil) c.Assert(r, qt.Not(qt.IsNil), qt.Commentf(filename)) return r.(resources.Transformer) } createContentReplacer := func(name, old, new string) resources.ResourceTransformation { return &testTransformation{ name: name, transform: func(ctx *resources.ResourceTransformationCtx) error { in := helpers.ReaderToString(ctx.From) in = strings.Replace(in, old, new, 1) ctx.AddOutPathIdentifier("." + name) fmt.Fprint(ctx.To, in) return nil }, } } // Verify that we publish the same file once only. assertNoDuplicateWrites := func(c *qt.C, spec *resources.Spec) { c.Helper() hugofs.WalkFilesystems(spec.Fs.PublishDir, func(fs afero.Fs) bool { if dfs, ok := fs.(hugofs.DuplicatesReporter); ok { c.Assert(dfs.ReportDuplicates(), qt.Equals, "") } return false }) } assertShouldExist := func(c *qt.C, spec *resources.Spec, filename string, should bool) { c.Helper() exists, _ := helpers.Exists(filepath.FromSlash(filename), spec.Fs.WorkingDirReadOnly) c.Assert(exists, qt.Equals, should) } c := qt.New(t) c.Run("All values", func(c *qt.C) { c.Parallel() spec := newTestResourceSpec(specDescriptor{c: c}) transformation := &testTransformation{ name: "test", transform: func(ctx *resources.ResourceTransformationCtx) error { // Content in := helpers.ReaderToString(ctx.From) in = strings.Replace(in, "blue", "green", 1) fmt.Fprint(ctx.To, in) // Media type ctx.OutMediaType = media.Builtin.CSVType // Change target ctx.ReplaceOutPathExtension(".csv") // Add some data to context ctx.Data["mydata"] = "Hugo Rocks!" return nil }, } r := createTransformer(c, spec, "f1.txt", "color is blue") tr, err := r.Transform(transformation) c.Assert(err, qt.IsNil) content, err := tr.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "color is green") c.Assert(tr.MediaType(), eq, media.Builtin.CSVType) c.Assert(tr.RelPermalink(), qt.Equals, "/f1.csv") assertShouldExist(c, spec, "public/f1.csv", true) data := tr.Data().(map[string]any) c.Assert(data["mydata"], qt.Equals, "Hugo Rocks!") assertNoDuplicateWrites(c, spec) }) c.Run("Meta only", func(c *qt.C) { c.Parallel() spec := newTestResourceSpec(specDescriptor{c: c}) transformation := &testTransformation{ name: "test", transform: func(ctx *resources.ResourceTransformationCtx) error { // Change media type only ctx.OutMediaType = media.Builtin.CSVType ctx.ReplaceOutPathExtension(".csv") return nil }, } r := createTransformer(c, spec, "f1.txt", "color is blue") tr, err := r.Transform(transformation) c.Assert(err, qt.IsNil) content, err := tr.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "color is blue") c.Assert(tr.MediaType(), eq, media.Builtin.CSVType) // The transformed file should only be published if RelPermalink // or Permalink is called. n := htesting.Rnd.Intn(3) shouldExist := true switch n { case 0: tr.RelPermalink() case 1: tr.Permalink() default: shouldExist = false } assertShouldExist(c, spec, "public/f1.csv", shouldExist) assertNoDuplicateWrites(c, spec) }) c.Run("Memory-cached transformation", func(c *qt.C) { c.Parallel() spec := newTestResourceSpec(specDescriptor{c: c}) // Two transformations with same id, different behavior. t1 := createContentReplacer("t1", "blue", "green") t2 := createContentReplacer("t1", "color", "car") for i, transformation := range []resources.ResourceTransformation{t1, t2} { r := createTransformer(c, spec, "f1.txt", "color is blue") tr, _ := r.Transform(transformation) content, err := tr.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "color is green", qt.Commentf("i=%d", i)) assertShouldExist(c, spec, "public/f1.t1.txt", false) } assertNoDuplicateWrites(c, spec) }) c.Run("File-cached transformation", func(c *qt.C) { c.Parallel() fs := afero.NewMemMapFs() for i := range 2 { spec := newTestResourceSpec(specDescriptor{c: c, fs: fs}) r := createTransformer(c, spec, "f1.txt", "color is blue") var transformation resources.ResourceTransformation if i == 0 { // There is currently a hardcoded list of transformations that we // persist to disk (tocss, postcss). transformation = &testTransformation{ name: "tocss", transform: func(ctx *resources.ResourceTransformationCtx) error { in := helpers.ReaderToString(ctx.From) in = strings.Replace(in, "blue", "green", 1) ctx.AddOutPathIdentifier("." + "cached") ctx.OutMediaType = media.Builtin.CSVType ctx.Data = map[string]any{ "Hugo": "Rocks!", } fmt.Fprint(ctx.To, in) return nil }, } } else { // Force read from file cache. transformation = &testTransformation{ name: "tocss", transform: func(ctx *resources.ResourceTransformationCtx) error { return herrors.ErrFeatureNotAvailable }, } } msg := qt.Commentf("i=%d", i) tr, _ := r.Transform(transformation) c.Assert(tr.RelPermalink(), qt.Equals, "/f1.cached.txt", msg) content, err := tr.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "color is green", msg) c.Assert(tr.MediaType(), eq, media.Builtin.CSVType) c.Assert(tr.Data(), qt.DeepEquals, map[string]any{ "Hugo": "Rocks!", }) assertNoDuplicateWrites(c, spec) assertShouldExist(c, spec, "public/f1.cached.txt", true) } }) c.Run("Access RelPermalink first", func(c *qt.C) { c.Parallel() spec := newTestResourceSpec(specDescriptor{c: c}) t1 := createContentReplacer("t1", "blue", "green") r := createTransformer(c, spec, "f1.txt", "color is blue") tr, _ := r.Transform(t1) relPermalink := tr.RelPermalink() content, err := tr.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(relPermalink, qt.Equals, "/f1.t1.txt") c.Assert(content, qt.Equals, "color is green") c.Assert(tr.MediaType(), eq, media.Builtin.TextType) assertNoDuplicateWrites(c, spec) assertShouldExist(c, spec, "public/f1.t1.txt", true) }) c.Run("Content two", func(c *qt.C) { c.Parallel() spec := newTestResourceSpec(specDescriptor{c: c}) t1 := createContentReplacer("t1", "blue", "green") t2 := createContentReplacer("t1", "color", "car") r := createTransformer(c, spec, "f1.txt", "color is blue") tr, _ := r.Transform(t1, t2) content, err := tr.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "car is green") c.Assert(tr.MediaType(), eq, media.Builtin.TextType) assertNoDuplicateWrites(c, spec) }) c.Run("Content two chained", func(c *qt.C) { c.Parallel() spec := newTestResourceSpec(specDescriptor{c: c}) t1 := createContentReplacer("t1", "blue", "green") t2 := createContentReplacer("t2", "color", "car") r := createTransformer(c, spec, "f1.txt", "color is blue") tr1, err := r.Transform(t1) c.Assert(err, qt.IsNil) tr2, err := tr1.Transform(t2) c.Assert(err, qt.IsNil) content1, err := tr1.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) content2, err := tr2.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content1, qt.Equals, "color is green") c.Assert(content2, qt.Equals, "car is green") assertNoDuplicateWrites(c, spec) }) c.Run("Content many", func(c *qt.C) { c.Parallel() spec := newTestResourceSpec(specDescriptor{c: c}) const count = 26 // A-Z transformations := make([]resources.ResourceTransformation, count) for i := range count { transformations[i] = createContentReplacer(fmt.Sprintf("t%d", i), fmt.Sprint(i), string(rune(i+65))) } var countstr strings.Builder for i := range count { countstr.WriteString(fmt.Sprint(i)) } r := createTransformer(c, spec, "f1.txt", countstr.String()) tr, _ := r.Transform(transformations...) content, err := tr.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") assertNoDuplicateWrites(c, spec) }) c.Run("Image", func(c *qt.C) { c.Parallel() spec := newTestResourceSpec(specDescriptor{c: c}) transformation := &testTransformation{ name: "test", transform: func(ctx *resources.ResourceTransformationCtx) error { ctx.AddOutPathIdentifier(".changed") return nil }, } r := createTransformer(c, spec, "gopher.png", helpers.ReaderToString(gopherPNG())) tr, err := r.Transform(transformation) c.Assert(err, qt.IsNil) c.Assert(tr.MediaType(), eq, media.Builtin.PNGType) img, ok := tr.(images.ImageResource) c.Assert(ok, qt.Equals, true) c.Assert(img.Width(), qt.Equals, 75) c.Assert(img.Height(), qt.Equals, 60) // RelPermalink called. resizedPublished1, err := img.Resize("40x40") c.Assert(err, qt.IsNil) c.Assert(resizedPublished1.Height(), qt.Equals, 40) c.Assert(resizedPublished1.RelPermalink(), qt.Equals, "/gopher.changed_hu_6347c67500afc377.png") assertShouldExist(c, spec, "public/gopher.changed_hu_6347c67500afc377.png", true) // Permalink called. resizedPublished2, err := img.Resize("30x30") c.Assert(err, qt.IsNil) c.Assert(resizedPublished2.Height(), qt.Equals, 30) c.Assert(resizedPublished2.Permalink(), qt.Equals, "https://example.com/gopher.changed_hu_2d293650135f63d6.png") assertShouldExist(c, spec, "public/gopher.changed_hu_2d293650135f63d6.png", true) assertNoDuplicateWrites(c, spec) }) c.Run("Concurrent", func(c *qt.C) { spec := newTestResourceSpec(specDescriptor{c: c}) transformers := make([]resources.Transformer, 10) transformations := make([]resources.ResourceTransformation, 10) for i := range 10 { transformers[i] = createTransformer(c, spec, fmt.Sprintf("f%d.txt", i), fmt.Sprintf("color is %d", i)) transformations[i] = createContentReplacer("test", strconv.Itoa(i), "blue") } var wg sync.WaitGroup for i := range 13 { wg.Add(1) go func(i int) { defer wg.Done() for j := range 23 { id := (i + j) % 10 tr, err := transformers[id].Transform(transformations[id]) c.Assert(err, qt.IsNil) content, err := tr.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "color is blue") c.Assert(tr.RelPermalink(), qt.Equals, fmt.Sprintf("/f%d.test.txt", id)) } }(i) } wg.Wait() assertNoDuplicateWrites(c, spec) }) } type testTransformation struct { name string transform func(ctx *resources.ResourceTransformationCtx) error } func (t *testTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey(t.name) } func (t *testTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { return t.transform(ctx) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/docs.go
resources/docs.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package resources contains Resource related types. package resources
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/transform.go
resources/transform.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources import ( "bytes" "context" "fmt" "image" "io" "path" "strings" "sync" "github.com/gohugoio/hugo/common/constants" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/images/exif" "github.com/spf13/afero" bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/media" ) var ( _ resource.ContentResource = (*resourceAdapter)(nil) _ resourceCopier = (*resourceAdapter)(nil) _ resource.ReadSeekCloserResource = (*resourceAdapter)(nil) _ resource.Resource = (*resourceAdapter)(nil) _ resource.Staler = (*resourceAdapterInner)(nil) _ identity.IdentityGroupProvider = (*resourceAdapterInner)(nil) _ resource.Source = (*resourceAdapter)(nil) _ resource.Identifier = (*resourceAdapter)(nil) _ resource.TransientIdentifier = (*resourceAdapter)(nil) _ targetPathProvider = (*resourceAdapter)(nil) _ sourcePathProvider = (*resourceAdapter)(nil) _ resource.Identifier = (*resourceAdapter)(nil) _ resource.ResourceNameTitleProvider = (*resourceAdapter)(nil) _ resource.WithResourceMetaProvider = (*resourceAdapter)(nil) _ identity.DependencyManagerProvider = (*resourceAdapter)(nil) _ identity.IdentityGroupProvider = (*resourceAdapter)(nil) _ resource.NameNormalizedProvider = (*resourceAdapter)(nil) _ isPublishedProvider = (*resourceAdapter)(nil) ) // These are transformations that need special support in Hugo that may not // be available when building the theme/site so we write the transformation // result to disk and reuse if needed for these, // TODO(bep) it's a little fragile having these constants redefined here. var transformationsToCacheOnDisk = map[string]bool{ "postcss": true, "tocss": true, "tocss-dart": true, } func newResourceAdapter(spec *Spec, lazyPublish bool, target transformableResource) *resourceAdapter { var po *publishOnce if lazyPublish { po = &publishOnce{} } return &resourceAdapter{ resourceTransformations: &resourceTransformations{}, metaProvider: target, resourceAdapterInner: &resourceAdapterInner{ ctx: context.Background(), spec: spec, publishOnce: po, target: target, Staler: &AtomicStaler{}, }, } } // ResourceTransformation is the interface that a resource transformation step // needs to implement. type ResourceTransformation interface { Key() internal.ResourceTransformationKey Transform(ctx *ResourceTransformationCtx) error } type ResourceTransformationCtx struct { // The context that started the transformation. Ctx context.Context // The dependency manager to use for dependency tracking. DependencyManager identity.Manager // The content to transform. From io.Reader // The target of content transformation. // The current implementation requires that r is written to w // even if no transformation is performed. To io.Writer // This is the relative path to the original source. Unix styled slashes. SourcePath string // This is the relative target path to the resource. Unix styled slashes. InPath string // The relative target path to the transformed resource. Unix styled slashes. OutPath string // The input media type InMediaType media.Type // The media type of the transformed resource. OutMediaType media.Type // Data data can be set on the transformed Resource. Not that this need // to be simple types, as it needs to be serialized to JSON and back. Data map[string]any // This is used to publish additional artifacts, e.g. source maps. // We may improve this. OpenResourcePublisher func(relTargetPath string) (io.WriteCloser, error) } // AddOutPathIdentifier transforming InPath to OutPath adding an identifier, // eg '.min' before any extension. func (ctx *ResourceTransformationCtx) AddOutPathIdentifier(identifier string) { ctx.OutPath = ctx.addPathIdentifier(ctx.InPath, identifier) } // PublishSourceMap writes the content to the target folder of the main resource // with the ".map" extension added. func (ctx *ResourceTransformationCtx) PublishSourceMap(content string) error { target := ctx.OutPath + ".map" f, err := ctx.OpenResourcePublisher(target) if err != nil { return err } defer f.Close() _, err = f.Write([]byte(content)) return err } // ReplaceOutPathExtension transforming InPath to OutPath replacing the file // extension, e.g. ".scss" func (ctx *ResourceTransformationCtx) ReplaceOutPathExtension(newExt string) { dir, file := path.Split(ctx.InPath) base, _ := paths.PathAndExt(file) ctx.OutPath = path.Join(dir, (base + newExt)) } func (ctx *ResourceTransformationCtx) addPathIdentifier(inPath, identifier string) string { dir, file := path.Split(inPath) base, ext := paths.PathAndExt(file) return path.Join(dir, (base + identifier + ext)) } type publishOnce struct { publisherInit sync.Once publisherErr error } type resourceAdapter struct { commonResource *resourceTransformations *resourceAdapterInner metaProvider resource.ResourceMetaProvider } var _ identity.ForEeachIdentityByNameProvider = (*resourceAdapter)(nil) func (r *resourceAdapter) Content(ctx context.Context) (any, error) { r.init(false, true) if r.transformationsErr != nil { return nil, r.transformationsErr } return r.target.Content(ctx) } func (r *resourceAdapter) GetIdentity() identity.Identity { return identity.FirstIdentity(r.target) } func (r *resourceAdapter) Data() any { r.init(false, false) return r.target.Data() } func (r *resourceAdapter) ForEeachIdentityByName(name string, f func(identity.Identity) bool) { if constants.IsFieldRelOrPermalink(name) && !r.resourceTransformations.hasTransformationPermalinkHash() { // Special case for links without any content hash in the URL. // We don't need to rebuild all pages that use this resource, // but we want to make sure that the resource is accessed at least once. f(identity.NewFindFirstManagerIdentityProvider(r.target.GetDependencyManager(), r.target.GetIdentityGroup())) return } f(r.target.GetIdentityGroup()) f(r.target.GetDependencyManager()) } func (r *resourceAdapter) GetIdentityGroup() identity.Identity { return r.target.GetIdentityGroup() } func (r *resourceAdapter) GetDependencyManager() identity.Manager { return r.target.GetDependencyManager() } func (r resourceAdapter) cloneTo(targetPath string) resource.Resource { newtTarget := r.target.cloneTo(targetPath) newInner := &resourceAdapterInner{ ctx: r.ctx, spec: r.spec, Staler: r.Staler, target: newtTarget.(transformableResource), } if r.resourceAdapterInner.publishOnce != nil { newInner.publishOnce = &publishOnce{} } r.resourceAdapterInner = newInner return &r } func (r *resourceAdapter) Process(spec string) (images.ImageResource, error) { return r.getImageOps().Process(spec) } func (r *resourceAdapter) Crop(spec string) (images.ImageResource, error) { return r.getImageOps().Crop(spec) } func (r *resourceAdapter) Fill(spec string) (images.ImageResource, error) { return r.getImageOps().Fill(spec) } func (r *resourceAdapter) Fit(spec string) (images.ImageResource, error) { return r.getImageOps().Fit(spec) } func (r *resourceAdapter) Filter(filters ...any) (images.ImageResource, error) { return r.getImageOps().Filter(filters...) } func (r *resourceAdapter) Resize(spec string) (images.ImageResource, error) { return r.getImageOps().Resize(spec) } func (r *resourceAdapter) Height() int { return r.getImageOps().Height() } func (r *resourceAdapter) Exif() *exif.ExifInfo { return r.getImageOps().Exif() } func (r *resourceAdapter) Colors() ([]images.Color, error) { return r.getImageOps().Colors() } func (r *resourceAdapter) Key() string { r.init(false, false) return r.target.(resource.Identifier).Key() } func (r *resourceAdapter) TransientKey() string { return r.Key() } func (r *resourceAdapter) targetPath() string { r.init(false, false) return r.target.(targetPathProvider).targetPath() } func (r *resourceAdapter) sourcePath() string { r.init(false, false) if sp, ok := r.target.(sourcePathProvider); ok { return sp.sourcePath() } return "" } func (r *resourceAdapter) MediaType() media.Type { r.init(false, false) return r.target.MediaType() } func (r *resourceAdapter) Name() string { r.init(false, false) return r.metaProvider.Name() } func (r *resourceAdapter) NameNormalized() string { r.init(false, false) return r.target.(resource.NameNormalizedProvider).NameNormalized() } func (r *resourceAdapter) Params() maps.Params { r.init(false, false) return r.metaProvider.Params() } func (r *resourceAdapter) Permalink() string { r.init(true, false) return r.target.Permalink() } func (r *resourceAdapter) Publish() error { r.init(false, false) return r.target.Publish() } func (r *resourceAdapter) isPublished() bool { r.init(false, false) return r.target.isPublished() } func (r *resourceAdapter) ReadSeekCloser() (hugio.ReadSeekCloser, error) { r.init(false, false) return r.target.ReadSeekCloser() } func (r *resourceAdapter) RelPermalink() string { r.init(true, false) return r.target.RelPermalink() } func (r *resourceAdapter) ResourceType() string { r.init(false, false) return r.target.ResourceType() } func (r *resourceAdapter) String() string { return r.Name() } func (r *resourceAdapter) Title() string { r.init(false, false) return r.metaProvider.Title() } func (r resourceAdapter) Transform(t ...ResourceTransformation) (ResourceTransformer, error) { return r.TransformWithContext(context.Background(), t...) } func (r resourceAdapter) TransformWithContext(ctx context.Context, t ...ResourceTransformation) (ResourceTransformer, error) { r.resourceTransformations = &resourceTransformations{ transformations: append(r.transformations, t...), } r.resourceAdapterInner = &resourceAdapterInner{ ctx: ctx, spec: r.spec, Staler: r.Staler, publishOnce: &publishOnce{}, target: r.target, } return &r, nil } func (r *resourceAdapter) Width() int { return r.getImageOps().Width() } func (r *resourceAdapter) DecodeImage() (image.Image, error) { return r.getImageOps().DecodeImage() } func (r resourceAdapter) WithResourceMeta(mp resource.ResourceMetaProvider) resource.Resource { r.metaProvider = mp return &r } func (r *resourceAdapter) getImageOps() images.ImageResourceOps { img, ok := r.target.(images.ImageResourceOps) if !ok { if r.MediaType().SubType == "svg" { panic("this method is only available for raster images. To determine if an image is SVG, you can do {{ if eq .MediaType.SubType \"svg\" }}{{ end }}") } panic("this method is only available for image resources") } r.init(false, false) return img } // IsImage reports whether the given resource is an image that can be processed. func IsImage(v any) bool { r, ok := v.(resource.Resource) if !ok { return false } mt := r.MediaType() if mt.MainType != "image" { return false } _, isImage := images.ImageFormatFromMediaSubType(mt.SubType) return isImage } func (r *resourceAdapter) publish() { if r.publishOnce == nil { return } r.publisherInit.Do(func() { r.publisherErr = r.target.Publish() if r.publisherErr != nil { r.spec.Logger.Errorf("Failed to publish Resource: %s", r.publisherErr) } }) } func (r *resourceAdapter) TransformationKey() string { var key string for _, tr := range r.transformations { key = key + "_" + tr.Key().Value() } return r.spec.ResourceCache.cleanKey(r.target.Key()) + "_" + hashing.MD5FromStringHexEncoded(key) } func (r *resourceAdapter) getOrTransform(publish, setContent bool) error { key := r.TransformationKey() res, err := r.spec.ResourceCache.cacheResourceTransformation.GetOrCreate(key, func(string) (*resourceAdapterInner, error) { return r.transform(key, publish, setContent) }) if err != nil { return err } r.resourceAdapterInner = res return nil } func (r *resourceAdapter) transform(key string, publish, setContent bool) (*resourceAdapterInner, error) { cache := r.spec.ResourceCache b1 := bp.GetBuffer() b2 := bp.GetBuffer() defer bp.PutBuffer(b1) defer bp.PutBuffer(b2) tctx := &ResourceTransformationCtx{ Ctx: r.ctx, Data: make(map[string]any), OpenResourcePublisher: r.target.openPublishFileForWriting, DependencyManager: r.target.GetDependencyManager(), } tctx.InMediaType = r.target.MediaType() tctx.OutMediaType = r.target.MediaType() startCtx := *tctx updates := &transformationUpdate{startCtx: startCtx} var contentrc hugio.ReadSeekCloser contentrc, err := contentReadSeekerCloser(r.target) if err != nil { return nil, err } defer contentrc.Close() tctx.From = contentrc tctx.To = b1 tctx.InPath = r.target.TargetPath() tctx.SourcePath = strings.TrimPrefix(tctx.InPath, "/") counter := 0 writeToFileCache := false var transformedContentr io.Reader for i, tr := range r.transformations { if i != 0 { tctx.InMediaType = tctx.OutMediaType } mayBeCachedOnDisk := transformationsToCacheOnDisk[tr.Key().Name] if !writeToFileCache { writeToFileCache = mayBeCachedOnDisk } if i > 0 { hasWrites := tctx.To.(*bytes.Buffer).Len() > 0 if hasWrites { counter++ // Switch the buffers if counter%2 == 0 { tctx.From = b2 b1.Reset() tctx.To = b1 } else { tctx.From = b1 b2.Reset() tctx.To = b2 } } } newErr := func(err error) error { msg := fmt.Sprintf("%s: failed to transform %q (%s)", strings.ToUpper(tr.Key().Name), tctx.InPath, tctx.InMediaType.Type) if herrors.IsFeatureNotAvailableError(err) { var errMsg string switch strings.ToLower(tr.Key().Name) { case "postcss": // This transformation is not available in this // Most likely because PostCSS is not installed. errMsg = ". You need to install PostCSS. See https://gohugo.io/functions/css/postcss/" case "tailwindcss": errMsg = ". You need to install TailwindCSS CLI. See https://gohugo.io/functions/css/tailwindcss/" case "tocss": errMsg = ". Check your Hugo installation; you need the extended version to build SCSS/SASS with transpiler set to 'libsass'." case "tocss-dart": errMsg = ". You need to install Dart Sass, see https://gohugo.io//functions/css/sass/#dart-sass" case "babel": errMsg = ". You need to install Babel, see https://gohugo.io/functions/js/babel/" } return fmt.Errorf(msg+errMsg+": %w", err) } return fmt.Errorf(msg+": %w", err) } bcfg := r.spec.BuildConfig() var tryFileCache bool if mayBeCachedOnDisk && bcfg.UseResourceCache(nil) { tryFileCache = true } else { err = tr.Transform(tctx) if err != nil && err != herrors.ErrFeatureNotAvailable { return nil, newErr(err) } if mayBeCachedOnDisk { tryFileCache = bcfg.UseResourceCache(err) } if err != nil && !tryFileCache { return nil, newErr(err) } } if tryFileCache { f := r.target.tryTransformedFileCache(key, updates) if f == nil { if err != nil { return nil, newErr(err) } return nil, newErr(fmt.Errorf("resource %q not found in file cache", key)) } transformedContentr = f updates.sourceFs = cache.fileCache.Fs defer f.Close() // The reader above is all we need. break } if tctx.OutPath != "" { tctx.InPath = tctx.OutPath tctx.OutPath = "" } } if transformedContentr == nil { updates.updateFromCtx(tctx) } var publishwriters []io.WriteCloser if publish { publicw, err := r.target.openPublishFileForWriting(updates.targetPath) if err != nil { return nil, err } publishwriters = append(publishwriters, publicw) } if transformedContentr == nil { if writeToFileCache { // Also write it to the cache fi, metaw, err := cache.writeMeta(key, updates.toTransformedResourceMetadata()) if err != nil { return nil, err } updates.sourceFilename = &fi.Name updates.sourceFs = cache.fileCache.Fs publishwriters = append(publishwriters, metaw) } // Any transformations reading from From must also write to To. // This means that if the target buffer is empty, we can just reuse // the original reader. if b, ok := tctx.To.(*bytes.Buffer); ok && b.Len() > 0 { transformedContentr = tctx.To.(*bytes.Buffer) } else { transformedContentr = contentrc } } // Also write it to memory var contentmemw *bytes.Buffer setContent = setContent || !writeToFileCache if setContent { contentmemw = bp.GetBuffer() defer bp.PutBuffer(contentmemw) publishwriters = append(publishwriters, hugio.ToWriteCloser(contentmemw)) } publishw := hugio.NewMultiWriteCloser(publishwriters...) _, err = io.Copy(publishw, transformedContentr) if err != nil { return nil, err } publishw.Close() if setContent { s := contentmemw.String() updates.content = &s } newTarget, err := r.target.cloneWithUpdates(updates) if err != nil { return nil, err } r.target = newTarget return r.resourceAdapterInner, nil } func (r *resourceAdapter) init(publish, setContent bool) { if err := r.doInit(publish, setContent); err != nil { // The panic will be handled and converted to an error by the template framework. panic(err) } } func (r *resourceAdapter) doInit(publish, setContent bool) error { r.transformationsInit.Do(func() { if len(r.transformations) == 0 { // Nothing to do. return } if publish { // The transformation will write the content directly to // the destination. r.publishOnce = nil } r.transformationsErr = r.getOrTransform(publish, setContent) }) if publish && r.publishOnce != nil { r.publish() } return r.transformationsErr } type resourceAdapterInner struct { // The context that started this transformation. ctx context.Context target transformableResource resource.Staler spec *Spec // Handles publishing (to /public) if needed. *publishOnce } func (r *resourceAdapterInner) GetIdentityGroup() identity.Identity { return r.target.GetIdentityGroup() } func (r *resourceAdapterInner) StaleVersion() uint32 { // Both of these are incremented on change. return r.Staler.StaleVersion() + r.target.StaleVersion() } type resourceTransformations struct { transformationsInit sync.Once transformationsErr error transformations []ResourceTransformation } // hasTransformationPermalinkHash reports whether any of the transformations // in the chain creates a permalink that's based on the content, e.g. fingerprint. func (r *resourceTransformations) hasTransformationPermalinkHash() bool { for _, t := range r.transformations { if constants.IsResourceTransformationPermalinkHash(t.Key().Name) { return true } } return false } type transformableResource interface { baseResourceInternal resource.ContentProvider resource.Resource resource.Identifier resource.Staler resourceCopier } type transformationUpdate struct { content *string sourceFilename *string sourceFs afero.Fs targetPath string mediaType media.Type data map[string]any startCtx ResourceTransformationCtx } func (u *transformationUpdate) isContentChanged() bool { return u.content != nil || u.sourceFilename != nil } func (u *transformationUpdate) toTransformedResourceMetadata() transformedResourceMetadata { return transformedResourceMetadata{ MediaTypeV: u.mediaType.Type, Target: u.targetPath, MetaData: u.data, } } func (u *transformationUpdate) updateFromCtx(ctx *ResourceTransformationCtx) { u.targetPath = ctx.OutPath u.mediaType = ctx.OutMediaType u.data = ctx.Data u.targetPath = ctx.InPath } // We will persist this information to disk. type transformedResourceMetadata struct { Target string `json:"Target"` MediaTypeV string `json:"MediaType"` MetaData map[string]any `json:"Data"` } // contentReadSeekerCloser returns a ReadSeekerCloser if possible for a given Resource. func contentReadSeekerCloser(r resource.Resource) (hugio.ReadSeekCloser, error) { switch rr := r.(type) { case resource.ReadSeekCloserResource: rc, err := rr.ReadSeekCloser() if err != nil { return nil, err } return rc, nil default: return nil, fmt.Errorf("cannot transform content of Resource of type %T", r) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/testhelpers_test.go
resources/testhelpers_test.go
package resources_test import ( "image" "os" "path/filepath" "runtime" "strings" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/resource" "github.com/spf13/afero" ) type specDescriptor struct { baseURL string c *qt.C fs afero.Fs } func newTestResourceSpec(desc specDescriptor) *resources.Spec { baseURL := desc.baseURL if baseURL == "" { baseURL = "https://example.com/" } afs := desc.fs if afs == nil { afs = afero.NewMemMapFs() } if hugofs.IsOsFs(afs) { panic("osFs not supported for this test") } if err := afs.MkdirAll("assets", 0o755); err != nil { panic(err) } cfg := config.New() cfg.Set("baseURL", baseURL) cfg.Set("publishDir", "public") imagingCfg := map[string]any{ "resampleFilter": "linear", "quality": 68, "anchor": "left", } cfg.Set("imaging", imagingCfg) d := testconfig.GetTestDeps( afs, cfg, func(d *deps.Deps) { d.Fs.PublishDir = hugofs.NewCreateCountingFs(d.Fs.PublishDir) }, ) desc.c.Cleanup(func() { if err := d.Close(); err != nil { panic(err) } }) return d.ResourceSpec } func newTestResourceOsFs(c *qt.C) (*resources.Spec, string) { cfg := config.New() cfg.Set("baseURL", "https://example.com") workDir, err := os.MkdirTemp("", "hugores") c.Assert(err, qt.IsNil) c.Assert(workDir, qt.Not(qt.Equals), "") if runtime.GOOS == "darwin" && !strings.HasPrefix(workDir, "/private") { // To get the entry folder in line with the rest. This its a little bit // mysterious, but so be it. workDir = "/private" + workDir } cfg.Set("workingDir", workDir) os.MkdirAll(filepath.Join(workDir, "assets"), 0o755) d := testconfig.GetTestDeps(hugofs.Os, cfg) return d.ResourceSpec, workDir } func fetchSunset(c *qt.C) (*resources.Spec, images.ImageResource) { return fetchImage(c, "sunset.jpg") } func fetchImage(c *qt.C, name string) (*resources.Spec, images.ImageResource) { spec := newTestResourceSpec(specDescriptor{c: c}) return spec, fetchImageForSpec(spec, c, name) } func fetchImageForSpec(spec *resources.Spec, c *qt.C, name string) images.ImageResource { r := fetchResourceForSpec(spec, c, name) img := r.(images.ImageResource) c.Assert(img, qt.Not(qt.IsNil)) return img } func fetchResourceForSpec(spec *resources.Spec, c *qt.C, name string, targetPathAddends ...string) resource.ContentResource { b, err := os.ReadFile(filepath.FromSlash("testdata/" + name)) c.Assert(err, qt.IsNil) open := hugio.NewOpenReadSeekCloser(hugio.NewReadSeekerNoOpCloserFromBytes(b)) targetPath := name base := "/a/" r, err := spec.NewResource(resources.ResourceSourceDescriptor{ LazyPublish: true, NameNormalized: name, TargetPath: targetPath, BasePathRelPermalink: base, BasePathTargetPath: base, OpenReadSeekCloser: open, GroupIdentity: identity.Anonymous, }) c.Assert(err, qt.IsNil) c.Assert(r, qt.Not(qt.IsNil)) return r.(resource.ContentResource) } func assertImageFile(c *qt.C, fs afero.Fs, filename string, width, height int) { filename = filepath.Clean(filename) f, err := fs.Open(filename) c.Assert(err, qt.IsNil) defer f.Close() config, _, err := image.DecodeConfig(f) c.Assert(err, qt.IsNil) c.Assert(config.Width, qt.Equals, width) c.Assert(config.Height, qt.Equals, height) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_test.go
resources/resource_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources import ( "os" "testing" qt "github.com/frankban/quicktest" ) func TestAtomicStaler(t *testing.T) { c := qt.New(t) type test struct { AtomicStaler } var v test c.Assert(v.StaleVersion(), qt.Equals, uint32(0)) v.MarkStale() c.Assert(v.StaleVersion(), qt.Equals, uint32(1)) v.MarkStale() c.Assert(v.StaleVersion(), qt.Equals, uint32(2)) } func BenchmarkHashImage(b *testing.B) { f, err := os.Open("testdata/sunset.jpg") if err != nil { b.Fatal(err) } defer f.Close() for b.Loop() { _, _, err := hashImage(f) if err != nil { b.Fatal(err) } f.Seek(0, 0) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource.go
resources/resource.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources import ( "context" "errors" "fmt" "io" "mime" "strings" "sync" "sync/atomic" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources/internal" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hsync" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/helpers" ) var ( _ resource.ContentResource = (*genericResource)(nil) _ resource.ReadSeekCloserResource = (*genericResource)(nil) _ resource.Resource = (*genericResource)(nil) _ resource.Source = (*genericResource)(nil) _ resource.Cloner = (*genericResource)(nil) _ resource.ResourcesLanguageMerger = (*resource.Resources)(nil) _ resource.Identifier = (*genericResource)(nil) _ resource.TransientIdentifier = (*genericResource)(nil) _ targetPathProvider = (*genericResource)(nil) _ sourcePathProvider = (*genericResource)(nil) _ identity.IdentityGroupProvider = (*genericResource)(nil) _ identity.DependencyManagerProvider = (*genericResource)(nil) _ identity.Identity = (*genericResource)(nil) _ fileInfo = (*genericResource)(nil) _ isPublishedProvider = (*genericResource)(nil) ) type ResourceSourceDescriptor struct { // The source content. OpenReadSeekCloser hugio.OpenReadSeekCloser // The canonical source path. Path *paths.Path // The normalized name of the resource. NameNormalized string // The name of the resource as it was read from the source. NameOriginal string // The title of the resource. Title string // Any base paths prepended to the target path. This will also typically be the // language code, but setting it here means that it should not have any effect on // the permalink. // This may be several values. In multihost mode we may publish the same resources to // multiple targets. TargetBasePaths []string TargetPath string BasePathRelPermalink string BasePathTargetPath string SourceFilenameOrPath string // Used for error logging. // The Data to associate with this resource. Data map[string]any // The Params to associate with this resource. Params maps.Params // Delay publishing until either Permalink or RelPermalink is called. Maybe never. LazyPublish bool // Set when its known up front, else it's resolved from the target filename. MediaType media.Type // Used to track dependencies (e.g. imports). May be nil if that's of no concern. DependencyManager identity.Manager // A shared identity for this resource and all its clones. // If this is not set, an Identity is created. GroupIdentity identity.Identity } func (fd *ResourceSourceDescriptor) init(r *Spec) error { if len(fd.TargetBasePaths) == 0 { // If not set, we publish the same resource to all hosts. fd.TargetBasePaths = r.MultihostTargetBasePaths } if fd.OpenReadSeekCloser == nil { panic(errors.New("OpenReadSeekCloser is nil")) } if fd.TargetPath == "" { panic(errors.New("RelPath is empty")) } if fd.Params == nil { fd.Params = make(maps.Params) } if fd.Path == nil { fd.Path = r.Cfg.PathParser().Parse("", fd.TargetPath) } if fd.TargetPath == "" { fd.TargetPath = fd.Path.Path() } else { fd.TargetPath = paths.ToSlashPreserveLeading(fd.TargetPath) } fd.BasePathRelPermalink = paths.ToSlashPreserveLeading(fd.BasePathRelPermalink) if fd.BasePathRelPermalink == "/" { fd.BasePathRelPermalink = "" } fd.BasePathTargetPath = paths.ToSlashPreserveLeading(fd.BasePathTargetPath) if fd.BasePathTargetPath == "/" { fd.BasePathTargetPath = "" } fd.TargetPath = paths.ToSlashPreserveLeading(fd.TargetPath) if fd.NameNormalized == "" { fd.NameNormalized = fd.TargetPath } if fd.NameOriginal == "" { fd.NameOriginal = fd.NameNormalized } if fd.Title == "" { fd.Title = fd.NameOriginal } mediaType := fd.MediaType if mediaType.IsZero() { ext := fd.Path.Ext() var ( found bool suffixInfo media.SuffixInfo ) mediaType, suffixInfo, found = r.MediaTypes().GetFirstBySuffix(ext) // TODO(bep) we need to handle these ambiguous types better, but in this context // we most likely want the application/xml type. if suffixInfo.Suffix == "xml" && mediaType.SubType == "rss" { mediaType, found = r.MediaTypes().GetByType("application/xml") } if !found { // A fallback. Note that mime.TypeByExtension is slow by Hugo standards, // so we should configure media types to avoid this lookup for most // situations. mimeStr := mime.TypeByExtension("." + ext) if mimeStr != "" { mediaType, _ = media.FromStringAndExt(mimeStr, ext) } } } fd.MediaType = mediaType if fd.DependencyManager == nil { fd.DependencyManager = r.Cfg.NewIdentityManager() } return nil } type ResourceTransformer interface { resource.Resource Transformer } type Transformer interface { Transform(...ResourceTransformation) (ResourceTransformer, error) TransformWithContext(context.Context, ...ResourceTransformation) (ResourceTransformer, error) } func NewFeatureNotAvailableTransformer(key string, elements ...any) ResourceTransformation { return transformerNotAvailable{ key: internal.NewResourceTransformationKey(key, elements...), } } type transformerNotAvailable struct { key internal.ResourceTransformationKey } func (t transformerNotAvailable) Transform(ctx *ResourceTransformationCtx) error { return herrors.ErrFeatureNotAvailable } func (t transformerNotAvailable) Key() internal.ResourceTransformationKey { return t.key } // resourceCopier is for internal use. type resourceCopier interface { cloneTo(targetPath string) resource.Resource } // Copy copies r to the targetPath given. func Copy(r resource.Resource, targetPath string) resource.Resource { return r.(resourceCopier).cloneTo(targetPath) } type baseResourceResource interface { resource.Cloner resourceCopier resource.ContentProvider resource.Resource resource.Identifier } type baseResourceInternal interface { resource.Source resource.NameNormalizedProvider sourcePath() string fileInfo mediaTypeAssigner targetPather isPublishedProvider ReadSeekCloser() (hugio.ReadSeekCloser, error) identity.IdentityGroupProvider identity.DependencyManagerProvider // For internal use. cloneWithUpdates(*transformationUpdate) (baseResource, error) tryTransformedFileCache(key string, u *transformationUpdate) io.ReadCloser getResourcePaths() internal.ResourcePaths specProvider openPublishFileForWriting(relTargetPath string) (io.WriteCloser, error) } type specProvider interface { getSpec() *Spec } type baseResource interface { baseResourceResource baseResourceInternal resource.Staler } type commonResource struct{} // Slice is for internal use. // for the template functions. See collections.Slice. func (commonResource) Slice(in any) (any, error) { switch items := in.(type) { case resource.Resources: return items, nil case []any: groups := make(resource.Resources, len(items)) for i, v := range items { g, ok := v.(resource.Resource) if !ok { return nil, fmt.Errorf("type %T is not a Resource", v) } groups[i] = g { } } return groups, nil default: return nil, fmt.Errorf("invalid slice type %T", items) } } type fileInfo interface { setOpenSource(hugio.OpenReadSeekCloser) setSourceFilenameIsHash(bool) setTargetPath(internal.ResourcePaths) size() int64 hashProvider } type hashProvider interface { hash() uint64 } var _ resource.StaleInfo = (*StaleValue[any])(nil) type StaleValue[V any] struct { // The value. Value V // StaleVersionFunc reports the current version of the value. // This always starts out at 0 and get incremented on staleness. StaleVersionFunc func() uint32 } func (s *StaleValue[V]) StaleVersion() uint32 { return s.StaleVersionFunc() } type AtomicStaler struct { stale uint32 } func (s *AtomicStaler) MarkStale() { atomic.AddUint32(&s.stale, 1) } func (s *AtomicStaler) StaleVersion() uint32 { return atomic.LoadUint32(&(s.stale)) } // For internal use. type GenericResourceTestInfo struct { Paths internal.ResourcePaths } // For internal use. func GetTestInfoForResource(r resource.Resource) GenericResourceTestInfo { var gr *genericResource switch v := r.(type) { case *genericResource: gr = v case *resourceAdapter: gr = v.target.(*genericResource) default: panic(fmt.Sprintf("unknown resource type: %T", r)) } return GenericResourceTestInfo{ Paths: gr.paths, } } // genericResource represents a generic linkable resource. type genericResource struct { publishInit *hsync.OnceMore key string keyInit *sync.Once sd ResourceSourceDescriptor paths internal.ResourcePaths includeHashInKey bool sourceFilenameIsHash bool h *resourceHash // A hash of the source content. Is only calculated in caching situations. resource.Staler title string name string params map[string]any spec *Spec } func (l *genericResource) IdentifierBase() string { return l.sd.Path.IdentifierBase() } func (l *genericResource) GetIdentityGroup() identity.Identity { return l.sd.GroupIdentity } func (l *genericResource) GetDependencyManager() identity.Manager { return l.sd.DependencyManager } func (l *genericResource) ReadSeekCloser() (hugio.ReadSeekCloser, error) { return l.sd.OpenReadSeekCloser() } func (l *genericResource) Clone() resource.Resource { return l.clone() } func (l *genericResource) size() int64 { l.hash() return l.h.size } func (l *genericResource) hash() uint64 { if err := l.h.init(l); err != nil { panic(err) } return l.h.value } func (l *genericResource) setOpenSource(openSource hugio.OpenReadSeekCloser) { l.sd.OpenReadSeekCloser = openSource } func (l *genericResource) setSourceFilenameIsHash(b bool) { l.sourceFilenameIsHash = b } func (l *genericResource) setTargetPath(d internal.ResourcePaths) { l.paths = d } func (l *genericResource) cloneTo(targetPath string) resource.Resource { c := l.clone() c.paths = c.paths.FromTargetPath(targetPath) return c } func (l *genericResource) Content(context.Context) (any, error) { r, err := l.ReadSeekCloser() if err != nil { return "", err } defer r.Close() return hugio.ReadString(r) } func (l *genericResource) Data() any { return l.sd.Data } func (l *genericResource) Key() string { l.keyInit.Do(func() { basePath := l.spec.Cfg.BaseURL().BasePathNoTrailingSlash if basePath == "" { l.key = l.RelPermalink() } else { l.key = strings.TrimPrefix(l.RelPermalink(), basePath) } if l.spec.Cfg.IsMultihost() { l.key = l.spec.Lang() + l.key } if l.includeHashInKey && !l.sourceFilenameIsHash { l.key += fmt.Sprintf("_%d", l.hash()) } }) return l.key } func (l *genericResource) TransientKey() string { return l.Key() } func (l *genericResource) targetPath() string { return l.paths.TargetPath() } func (l *genericResource) sourcePath() string { if p := l.sd.SourceFilenameOrPath; p != "" { return p } return "" } func (l *genericResource) MediaType() media.Type { return l.sd.MediaType } func (l *genericResource) setMediaType(mediaType media.Type) { l.sd.MediaType = mediaType } func (l *genericResource) Name() string { return l.name } func (l *genericResource) NameNormalized() string { return l.sd.NameNormalized } func (l *genericResource) Params() maps.Params { return l.params } func (l *genericResource) Publish() error { var err error l.publishInit.Do(func() { targetFilenames := l.getResourcePaths().TargetFilenames() if l.sourceFilenameIsHash { // This is a processed image. We want to avoid copying it if it hasn't changed. var changedFilenames []string for _, targetFilename := range targetFilenames { if _, err := l.getSpec().BaseFs.PublishFs.Stat(targetFilename); err == nil { continue } changedFilenames = append(changedFilenames, targetFilename) } if len(changedFilenames) == 0 { return } targetFilenames = changedFilenames } var fr hugio.ReadSeekCloser fr, err = l.ReadSeekCloser() if err != nil { return } defer fr.Close() var fw io.WriteCloser fw, err = helpers.OpenFilesForWriting(l.spec.BaseFs.PublishFs, targetFilenames...) if err != nil { return } defer fw.Close() _, err = io.Copy(fw, fr) }) return err } func (l *genericResource) isPublished() bool { return l.publishInit.Done() } func (l *genericResource) RelPermalink() string { return l.spec.PathSpec.GetBasePath(false) + paths.PathEscape(l.paths.TargetLink()) } func (l *genericResource) Permalink() string { return l.spec.Cfg.BaseURL().WithPathNoTrailingSlash + paths.PathEscape(l.paths.TargetPath()) } func (l *genericResource) ResourceType() string { return l.MediaType().MainType } func (l *genericResource) String() string { return fmt.Sprintf("Resource(%s: %s)", l.ResourceType(), l.name) } // Path is stored with Unix style slashes. func (l *genericResource) TargetPath() string { return l.paths.TargetPath() } func (l *genericResource) Title() string { return l.title } func (l *genericResource) getSpec() *Spec { return l.spec } func (l *genericResource) getResourcePaths() internal.ResourcePaths { return l.paths } func (r *genericResource) tryTransformedFileCache(key string, u *transformationUpdate) io.ReadCloser { fi, f, meta, found := r.spec.ResourceCache.getFromFile(key) if !found { return nil } u.sourceFilename = &fi.Name mt, _ := r.spec.MediaTypes().GetByType(meta.MediaTypeV) u.mediaType = mt u.data = meta.MetaData u.targetPath = meta.Target return f } func (r *genericResource) mergeData(in map[string]any) { if len(in) == 0 { return } if r.sd.Data == nil { r.sd.Data = make(map[string]any) } for k, v := range in { if _, found := r.sd.Data[k]; !found { r.sd.Data[k] = v } } } func (rc *genericResource) cloneWithUpdates(u *transformationUpdate) (baseResource, error) { r := rc.clone() if u.content != nil { r.sd.OpenReadSeekCloser = func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(*u.content), nil } } r.sd.MediaType = u.mediaType if u.sourceFilename != nil { if u.sourceFs == nil { return nil, errors.New("sourceFs is nil") } r.setOpenSource(func() (hugio.ReadSeekCloser, error) { return u.sourceFs.Open(*u.sourceFilename) }) } else if u.sourceFs != nil { return nil, errors.New("sourceFs is set without sourceFilename") } if u.targetPath == "" { return nil, errors.New("missing targetPath") } r.setTargetPath(r.paths.FromTargetPath(u.targetPath)) r.mergeData(u.data) return r, nil } func (l genericResource) clone() *genericResource { l.publishInit = &hsync.OnceMore{} l.keyInit = &sync.Once{} return &l } func (r *genericResource) openPublishFileForWriting(relTargetPath string) (io.WriteCloser, error) { filenames := r.paths.FromTargetPath(relTargetPath).TargetFilenames() return helpers.OpenFilesForWriting(r.spec.BaseFs.PublishFs, filenames...) } type targetPather interface { TargetPath() string } type isPublishedProvider interface { isPublished() bool } type resourceHash struct { value uint64 size int64 initOnce sync.Once } func (r *resourceHash) init(l hugio.ReadSeekCloserProvider) error { var initErr error r.initOnce.Do(func() { var hash uint64 var size int64 f, err := l.ReadSeekCloser() if err != nil { initErr = fmt.Errorf("failed to open source: %w", err) return } defer f.Close() hash, size, err = hashImage(f) if err != nil { initErr = fmt.Errorf("failed to calculate hash: %w", err) return } r.value = hash r.size = size }) return initErr } func hashImage(r io.ReadSeeker) (uint64, int64, error) { return hashing.XXHashFromReader(r) } // InternalResourceTargetPath is used internally to get the target path for a Resource. func InternalResourceTargetPath(r resource.Resource) string { return r.(targetPathProvider).targetPath() } // InternalResourceSourcePathBestEffort is used internally to get the source path for a Resource. // It returns an empty string if the source path is not available. func InternalResourceSourcePath(r resource.Resource) string { if sp, ok := r.(sourcePathProvider); ok { if p := sp.sourcePath(); p != "" { return p } } return "" } // InternalResourceSourceContent is used internally to get the source content for a Resource. func InternalResourceSourceContent(ctx context.Context, r resource.Resource) (string, error) { if cp, ok := r.(resource.ContentProvider); ok { c, err := cp.Content(ctx) if err != nil { return "", err } return cast.ToStringE(c) } return "", nil } // InternalResourceSourcePathBestEffort is used internally to get the source path for a Resource. // Used for error messages etc. // It will fall back to the target path if the source path is not available. func InternalResourceSourcePathBestEffort(r resource.Resource) string { if s := InternalResourceSourcePath(r); s != "" { return s } return InternalResourceTargetPath(r) } // isPublished returns true if the resource is published. func IsPublished(r resource.Resource) bool { return r.(isPublishedProvider).isPublished() } type targetPathProvider interface { // targetPath is the relative path to this resource. // In most cases this will be the same as the RelPermalink(), // but it will not trigger any lazy publishing. targetPath() string } // Optional interface implemented by resources that can provide the source path. type sourcePathProvider interface { // sourcePath is the source path to this resource's source. // This is used in error messages etc. sourcePath() string }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_metadata.go
resources/resource_metadata.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources import ( "fmt" "path/filepath" "strconv" "strings" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/gohugoio/hugo/resources/resource" "github.com/spf13/cast" maps0 "maps" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" ) var ( _ mediaTypeAssigner = (*genericResource)(nil) _ mediaTypeAssigner = (*imageResource)(nil) _ resource.Staler = (*genericResource)(nil) _ resource.NameNormalizedProvider = (*genericResource)(nil) ) // metaAssigner allows updating metadata in resources that supports it. type metaAssigner interface { setTitle(title string) setName(name string) updateParams(params map[string]any) } // metaAssigner allows updating the media type in resources that supports it. type mediaTypeAssigner interface { setMediaType(mediaType media.Type) } const counterPlaceHolder = ":counter" var _ metaAssigner = (*metaResource)(nil) // metaResource is a resource with metadata that can be updated. type metaResource struct { changed bool title string name string params maps.Params } func (r *metaResource) Name() string { return r.name } func (r *metaResource) Title() string { return r.title } func (r *metaResource) Params() maps.Params { return r.params } func (r *metaResource) setTitle(title string) { r.title = title r.changed = true } func (r *metaResource) setName(name string) { r.name = name r.changed = true } func (r *metaResource) updateParams(params map[string]any) { if r.params == nil { r.params = make(map[string]any) } maps0.Copy(r.params, params) r.changed = true } // cloneWithMetadataFromResourceConfigIfNeeded clones the given resource with the given metadata if the resource supports it. func cloneWithMetadataFromResourceConfigIfNeeded(rc *pagemeta.ResourceConfig, r resource.Resource) resource.Resource { wmp, ok := r.(resource.WithResourceMetaProvider) if !ok { return r } if rc.Name == "" && rc.Title == "" && len(rc.Params) == 0 { // No metadata. return r } if rc.Title == "" { rc.Title = rc.Name } wrapped := &metaResource{ name: rc.Name, title: rc.Title, params: rc.Params, } return wmp.WithResourceMeta(wrapped) } // CloneWithMetadataFromMapIfNeeded clones the given resource with the given metadata if the resource supports it. func CloneWithMetadataFromMapIfNeeded(m []map[string]any, r resource.Resource) resource.Resource { wmp, ok := r.(resource.WithResourceMetaProvider) if !ok { return r } wrapped := &metaResource{ name: r.Name(), title: r.Title(), params: r.Params(), } assignMetadata(m, wrapped) if !wrapped.changed { return r } return wmp.WithResourceMeta(wrapped) } // AssignMetadata assigns the given metadata to those resources that supports updates // and matching by wildcard given in `src` using `filepath.Match` with lower cased values. // This assignment is additive, but the most specific match needs to be first. // The `name` and `title` metadata field support shell-matched collection it got a match in. // See https://golang.org/pkg/path/#Match func assignMetadata(metadata []map[string]any, ma *metaResource) error { counters := make(map[string]int) var ( nameSet, titleSet bool nameCounter, titleCounter = 0, 0 nameCounterFound, titleCounterFound bool resourceSrcKey = strings.ToLower(ma.Name()) ) for _, meta := range metadata { src, found := meta["src"] if !found { return fmt.Errorf("missing 'src' in metadata for resource") } srcKey := strings.ToLower(cast.ToString(src)) glob, err := hglob.GetGlob(srcKey) if err != nil { return fmt.Errorf("failed to match resource with metadata: %w", err) } match := glob.Match(resourceSrcKey) if match { if !nameSet { name, found := meta["name"] if found { name := cast.ToString(name) // Bundled resources in sub folders are relative paths with forward slashes. Make sure any renames also matches that format: name = paths.TrimLeading(filepath.ToSlash(name)) if !nameCounterFound { nameCounterFound = strings.Contains(name, counterPlaceHolder) } if nameCounterFound && nameCounter == 0 { counterKey := "name_" + srcKey nameCounter = counters[counterKey] + 1 counters[counterKey] = nameCounter } ma.setName(replaceResourcePlaceholders(name, nameCounter)) nameSet = true } } if !titleSet { title, found := meta["title"] if found { title := cast.ToString(title) if !titleCounterFound { titleCounterFound = strings.Contains(title, counterPlaceHolder) } if titleCounterFound && titleCounter == 0 { counterKey := "title_" + srcKey titleCounter = counters[counterKey] + 1 counters[counterKey] = titleCounter } ma.setTitle((replaceResourcePlaceholders(title, titleCounter))) titleSet = true } } params, found := meta["params"] if found { m := maps.ToStringMap(params) // Needed for case insensitive fetching of params values maps.PrepareParams(m) ma.updateParams(m) } } } return nil } func replaceResourcePlaceholders(in string, counter int) string { return strings.Replace(in, counterPlaceHolder, strconv.Itoa(counter), -1) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/transform_integration_test.go
resources/transform_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resources_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestTransformCached(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] -- assets/css/main.css -- body { background: #fff; } -- content/p1.md -- --- title: "P1" --- P1. -- content/p2.md -- --- title: "P2" --- P2. -- layouts/list.html -- List. -- layouts/single.html -- {{ $css := resources.Get "css/main.css" | resources.Minify }} CSS: {{ $css.Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "CSS: body{background:#fff}") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_factories/create/create.go
resources/resource_factories/create/create.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package create contains functions for to create Resource objects. This will // typically non-files. package create import ( "net/http" "os" "path" "path/filepath" "strings" "time" "github.com/bep/helpers/contexthelpers" "github.com/bep/logg" "github.com/gohugoio/httpcache" hhttpcache "github.com/gohugoio/hugo/cache/httpcache" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/tasks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client httpCacheConfig hhttpcache.ConfigCompiled cacheGetResource *filecache.Cache resourceIDDispatcher contexthelpers.ContextDispatcher[string] // Set when watching. remoteResourceChecker *tasks.RunEvery remoteResourceLogger logg.LevelLogger } type contextKey uint8 const ( contextKeyResourceID contextKey = iota ) // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { fileCache := rs.FileCaches.GetResourceCache() resourceIDDispatcher := contexthelpers.NewContextDispatcher[string](contextKeyResourceID) httpCacheConfig := rs.Cfg.GetConfigSection("httpCacheCompiled").(hhttpcache.ConfigCompiled) var remoteResourceChecker *tasks.RunEvery if rs.Cfg.Watching() && !httpCacheConfig.IsPollingDisabled() { remoteResourceChecker = &tasks.RunEvery{ HandleError: func(name string, err error) { rs.Logger.Warnf("Failed to check remote resource: %s", err) }, RunImmediately: false, } if err := remoteResourceChecker.Start(); err != nil { panic(err) } rs.BuildClosers.Add(remoteResourceChecker) } httpTimeout := 2 * time.Minute // Need to cover retries. if httpTimeout < (rs.Cfg.Timeout() + 30*time.Second) { httpTimeout = rs.Cfg.Timeout() + 30*time.Second } return &Client{ rs: rs, httpCacheConfig: httpCacheConfig, resourceIDDispatcher: resourceIDDispatcher, remoteResourceChecker: remoteResourceChecker, remoteResourceLogger: rs.Logger.InfoCommand("remote"), httpClient: &http.Client{ Timeout: httpTimeout, Transport: &httpcache.Transport{ Cache: fileCache.AsHTTPCache(), CacheKey: func(req *http.Request) string { return resourceIDDispatcher.Get(req.Context()) }, Around: func(req *http.Request, key string) func() { return fileCache.NamedLock(key) }, AlwaysUseCachedResponse: func(req *http.Request, key string) bool { return !httpCacheConfig.For(req.URL.String()) }, ShouldCache: func(req *http.Request, resp *http.Response, key string) bool { return shouldCache(resp.StatusCode) }, CanStore: func(reqCacheControl, respCacheControl httpcache.CacheControl) (canStore bool) { if httpCacheConfig.Base.RespectCacheControlNoStoreInResponse { if _, ok := respCacheControl["no-store"]; ok { return false } } if httpCacheConfig.Base.RespectCacheControlNoStoreInRequest { if _, ok := reqCacheControl["no-store"]; ok { return false } } return true }, MarkCachedResponses: true, EnableETagPair: true, Transport: &transport{ Cfg: rs.Cfg, Logger: rs.Logger, }, }, }, cacheGetResource: fileCache, } } // Copy copies r to the new targetPath. func (c *Client) Copy(r resource.Resource, targetPath string) (resource.Resource, error) { key := dynacache.CleanKey(targetPath) + "__copy" return c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) { return resources.Copy(r, targetPath), nil }) } // 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) key := dynacache.CleanKey(pathname) + "__get" return c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) { // 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) fi, err := c.rs.BaseFs.Assets.Fs.Stat(filename) if err != nil { if os.IsNotExist(err) { return nil, nil } // A real error. return nil, err } return c.getOrCreateFileResource(fi.(hugofs.FileMetaInfo)) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match("__match", pattern, nil, false) } func (c *Client) ByType(tp string) resource.Resources { res, err := c.match(path.Join("_byType", tp), "**", func(r resource.Resource) bool { return r.ResourceType() == tp }, false) if err != nil { panic(err) } return res } // GetMatch gets first resource matching the given pattern from the assets filesystem. func (c *Client) GetMatch(pattern string) (resource.Resource, error) { res, err := c.match("__get-match", pattern, nil, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) getOrCreateFileResource(info hugofs.FileMetaInfo) (resource.Resource, error) { meta := info.Meta() return c.rs.ResourceCache.GetOrCreateFile(filepath.ToSlash(meta.Filename), func() (resource.Resource, error) { return c.rs.NewResource(resources.ResourceSourceDescriptor{ LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, NameNormalized: meta.PathInfo.Path(), NameOriginal: meta.PathInfo.Unnormalized().Path(), GroupIdentity: meta.PathInfo, TargetPath: meta.PathInfo.Unnormalized().Path(), SourceFilenameOrPath: meta.Filename, }) }) } func (c *Client) match(name, pattern string, matchFunc func(r resource.Resource) bool, firstOnly bool) (resource.Resources, error) { pattern = hglob.NormalizePath(pattern) partitions := hglob.FilterGlobParts(strings.Split(pattern, "/")) key := path.Join(name, path.Join(partitions...)) key = path.Join(key, pattern) return c.rs.ResourceCache.GetOrCreateResources(key, func() (resource.Resources, error) { var res resource.Resources handle := func(info hugofs.FileMetaInfo) (bool, error) { r, err := c.getOrCreateFileResource(info) if err != nil { return true, err } if matchFunc != nil && !matchFunc(r) { return false, nil } res = append(res, r) return firstOnly, nil } if err := hugofs.Glob(c.rs.BaseFs.Assets.Fs, pattern, handle); err != nil { return nil, err } return res, nil }) } type Options struct { // The target path relative to the publish directory. // Unix style path, i.e. "images/logo.png". TargetPath string // Whether the TargetPath has a hash in it which will change if the resource changes. // If not, we will calculate a hash from the content. TargetPathHasHash bool // The content to create the Resource from. CreateContent func() (func() (hugio.ReadSeekCloser, error), error) } // FromOpts creates a new Resource from the given Options. // Make sure to set optis.TargetPathHasHash if the TargetPath already contains a hash, // as this avoids the need to calculate it. // To create a new ReadSeekCloser from a string, use hugio.NewReadSeekerNoOpCloserFromString, // or hugio.NewReadSeekerNoOpCloserFromBytes for a byte slice. // See FromString. func (c *Client) FromOpts(opts Options) (resource.Resource, error) { opts.TargetPath = path.Clean(opts.TargetPath) var hash string var newReadSeeker func() (hugio.ReadSeekCloser, error) = nil if !opts.TargetPathHasHash { var err error newReadSeeker, err = opts.CreateContent() if err != nil { return nil, err } if err := func() error { r, err := newReadSeeker() if err != nil { return err } defer r.Close() hash, err = hashing.XxHashFromReaderHexEncoded(r) if err != nil { return err } return nil }(); err != nil { return nil, err } } key := dynacache.CleanKey(opts.TargetPath) + hash r, err := c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) { if newReadSeeker == nil { var err error newReadSeeker, err = opts.CreateContent() if err != nil { return nil, err } } return c.rs.NewResource( resources.ResourceSourceDescriptor{ LazyPublish: true, GroupIdentity: identity.Anonymous, // All usage of this resource are tracked via its string content. OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return newReadSeeker() }, TargetPath: opts.TargetPath, }) }) return r, err } // FromString creates a new Resource from a string with the given relative target path. func (c *Client) FromString(targetPath, content string) (resource.Resource, error) { return c.FromOpts(Options{ TargetPath: targetPath, CreateContent: func() (func() (hugio.ReadSeekCloser, error), error) { return func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, nil }, }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_factories/create/remote.go
resources/resource_factories/create/remote.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package create import ( "bytes" "context" "fmt" "io" "math/rand" "mime" "net/http" "net/url" "path" "strings" "time" gmaps "maps" "github.com/gohugoio/httpcache" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/tasks" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/mitchellh/mapstructure" ) type HTTPError struct { error Data map[string]any StatusCode int Body string } func responseToData(res *http.Response, readBody bool, includeHeaders []string) map[string]any { var body []byte if readBody { body, _ = io.ReadAll(res.Body) } responseHeaders := make(map[string][]string) if len(includeHeaders) > 0 { for k, v := range res.Header { if hstrings.InSlicEqualFold(includeHeaders, k) { responseHeaders[k] = v } } } m := map[string]any{ "StatusCode": res.StatusCode, "Status": res.Status, "TransferEncoding": res.TransferEncoding, "ContentLength": res.ContentLength, "ContentType": res.Header.Get("Content-Type"), "Headers": responseHeaders, } if readBody { m["Body"] = string(body) } return m } func toHTTPError(err error, res *http.Response, readBody bool, responseHeaders []string) *HTTPError { if err == nil { panic("err is nil") } if res == nil { return &HTTPError{ error: err, Data: map[string]any{}, } } return &HTTPError{ error: err, Data: responseToData(res, readBody, responseHeaders), } } var temporaryHTTPStatusCodes = map[int]bool{ 408: true, 429: true, 500: true, 502: true, 503: true, 504: true, } func (c *Client) configurePollingIfEnabled(uri, optionsKey string, getRes func() (*http.Response, error)) { if c.remoteResourceChecker == nil { return } // Set up polling for changes to this resource. pollingConfig := c.httpCacheConfig.PollConfigFor(uri) if pollingConfig.IsZero() || pollingConfig.Config.Disable { return } if c.remoteResourceChecker.Has(optionsKey) { return } var lastChange time.Time c.remoteResourceChecker.Add(optionsKey, tasks.Func{ IntervalLow: pollingConfig.Config.Low, IntervalHigh: pollingConfig.Config.High, F: func(interval time.Duration) (time.Duration, error) { start := time.Now() defer func() { duration := time.Since(start) c.rs.Logger.Debugf("Polled remote resource for changes in %13s. Interval: %4s (low: %4s high: %4s) resource: %q ", duration, interval, pollingConfig.Config.Low, pollingConfig.Config.High, uri) }() // TODO(bep) figure out a ways to remove unused tasks. res, err := getRes() if err != nil { return pollingConfig.Config.High, err } // The caching is delayed until the body is read. io.Copy(io.Discard, res.Body) res.Body.Close() x1, x2 := res.Header.Get(httpcache.XETag1), res.Header.Get(httpcache.XETag2) if x1 != x2 { lastChange = time.Now() c.remoteResourceLogger.Logf("detected change in remote resource %q", uri) c.rs.Rebuilder.SignalRebuild(identity.StringIdentity(optionsKey)) } if time.Since(lastChange) < 10*time.Second { // The user is typing, check more often. return 0, nil } // Increase the interval to avoid hammering the server. interval += 1 * time.Second return interval, nil }, }) } // FromRemote expects one or n-parts of a URL to a resource // If you provide multiple parts they will be joined together to the final URL. func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, fmt.Errorf("failed to parse URL for resource %s: %w", uri, err) } method := "GET" if s, _, ok := maps.LookupEqualFold(optionsm, "method"); ok { method = strings.ToUpper(s.(string)) } isHeadMethod := method == "HEAD" optionsm = gmaps.Clone(optionsm) userKey, optionsKey := remoteResourceKeys(uri, optionsm) // A common pattern is to use the key in the options map as // a way to control cache eviction, // so make sure we use any user provided key as the file cache key, // but the auto generated and more stable key for everything else. filecacheKey := userKey return c.rs.ResourceCache.CacheResourceRemote.GetOrCreate(optionsKey, func(key string) (resource.Resource, error) { options, err := decodeRemoteOptions(optionsm) if err != nil { return nil, fmt.Errorf("failed to decode options for resource %s: %w", uri, err) } if err := c.validateFromRemoteArgs(uri, options); err != nil { return nil, err } getRes := func() (*http.Response, error) { ctx := context.Background() ctx = c.resourceIDDispatcher.Set(ctx, filecacheKey) req, err := options.NewRequest(uri) if err != nil { return nil, fmt.Errorf("failed to create request for resource %s: %w", uri, err) } req = req.WithContext(ctx) return c.httpClient.Do(req) } res, err := getRes() if err != nil { return nil, err } defer res.Body.Close() c.configurePollingIfEnabled(uri, optionsKey, getRes) if res.StatusCode == http.StatusNotFound { // Not found. This matches how lookups for local resources work. // To cache this, we need to make sure the body is read. io.Copy(io.Discard, res.Body) return nil, nil } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, toHTTPError(fmt.Errorf("failed to fetch remote resource from '%s': %s", uri, http.StatusText(res.StatusCode)), res, !isHeadMethod, options.ResponseHeaders) } var ( body []byte mediaType media.Type ) // A response to a HEAD method should not have a body. If it has one anyway, that body must be ignored. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD if !isHeadMethod && res.Body != nil { body, err = io.ReadAll(res.Body) if err != nil { return nil, fmt.Errorf("failed to read remote resource %q: %w", uri, err) } } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } contentType := res.Header.Get("Content-Type") // For HEAD requests we have no body to work with, so we need to use the Content-Type header. if isHeadMethod || c.rs.ExecHelper.Sec().HTTP.MediaTypes.Accept(contentType) { var found bool mediaType, found = c.rs.MediaTypes().GetByType(contentType) if !found { // A media type not configured in Hugo, just create one from the content type string. mediaType, _ = media.FromString(contentType) } } if mediaType.IsZero() { var extensionHints []string // mime.ExtensionsByType gives a long list of extensions for text/plain, // just use ".txt". if strings.HasPrefix(contentType, "text/plain") { extensionHints = []string{".txt"} } else { exts, _ := mime.ExtensionsByType(contentType) if exts != nil { extensionHints = exts } } // Look for a file extension. If it's .txt, look for a more specific. if extensionHints == nil || extensionHints[0] == ".txt" { if ext := path.Ext(filename); ext != "" { extensionHints = []string{ext} } } // Now resolve the media type primarily using the content. mediaType = media.FromContent(c.rs.MediaTypes(), extensionHints, body) } if mediaType.IsZero() { return nil, fmt.Errorf("failed to resolve media type for remote resource %q", uri) } userKey = filename[:len(filename)-len(path.Ext(filename))] + "_" + userKey + mediaType.FirstSuffix.FullSuffix data := responseToData(res, false, options.ResponseHeaders) return c.rs.NewResource( resources.ResourceSourceDescriptor{ MediaType: mediaType, Data: data, GroupIdentity: identity.StringIdentity(optionsKey), LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, TargetPath: userKey, }) }) } func (c *Client) validateFromRemoteArgs(uri string, options fromRemoteOptions) error { if err := c.rs.ExecHelper.Sec().CheckAllowedHTTPURL(uri); err != nil { return err } if err := c.rs.ExecHelper.Sec().CheckAllowedHTTPMethod(options.Method); err != nil { return err } return nil } func remoteResourceKeys(uri string, optionsm map[string]any) (string, string) { var userKey string if key, k, found := maps.LookupEqualFold(optionsm, "key"); found { userKey = hashing.HashString(key) delete(optionsm, k) } optionsKey := hashing.HashString(uri, optionsm) if userKey == "" { userKey = optionsKey } return userKey, optionsKey } func addDefaultHeaders(req *http.Request) { if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]any, req *http.Request) { if headers == nil { return } for key, val := range headers { vals := types.ToStringSlicePreserveString(val) for _, s := range vals { req.Header.Add(key, s) } } } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } type fromRemoteOptions struct { Method string Headers map[string]any Body []byte ResponseHeaders []string } func (o fromRemoteOptions) BodyReader() io.Reader { if o.Body == nil { return nil } return bytes.NewBuffer(o.Body) } func (o fromRemoteOptions) NewRequest(url string) (*http.Request, error) { req, err := http.NewRequest(o.Method, url, o.BodyReader()) if err != nil { return nil, err } // First add any user provided headers. if o.Headers != nil { addUserProvidedHeaders(o.Headers, req) } // Then add default headers not provided by the user. addDefaultHeaders(req) return req, nil } func decodeRemoteOptions(optionsm map[string]any) (fromRemoteOptions, error) { options := fromRemoteOptions{ Method: "GET", } err := mapstructure.WeakDecode(optionsm, &options) if err != nil { return options, err } options.Method = strings.ToUpper(options.Method) return options, nil } var _ http.RoundTripper = (*transport)(nil) type transport struct { Cfg config.AllProvider Logger loggers.Logger } func (t *transport) RoundTrip(req *http.Request) (resp *http.Response, err error) { defer func() { if resp != nil && resp.StatusCode != http.StatusNotFound && resp.StatusCode != http.StatusNotModified { t.Logger.Debugf("Fetched remote resource: %s", req.URL.String()) } }() var ( start time.Time nextSleep = time.Duration((rand.Intn(1000) + 100)) * time.Millisecond nextSleepLimit = time.Duration(5) * time.Second retry bool ) for { resp, retry, err = func() (*http.Response, bool, error) { resp2, err := http.DefaultTransport.RoundTrip(req) if err != nil { return resp2, false, err } if resp2.StatusCode != http.StatusNotFound && resp2.StatusCode != http.StatusNotModified { if resp2.StatusCode < 200 || resp2.StatusCode > 299 { return resp2, temporaryHTTPStatusCodes[resp2.StatusCode], nil } } return resp2, false, nil }() if retry { if start.IsZero() { start = time.Now() } else if d := time.Since(start) + nextSleep; d >= t.Cfg.Timeout() { msg := "<nil>" if resp != nil { msg = resp.Status } err := toHTTPError(fmt.Errorf("retry timeout (configured to %s) fetching remote resource: %s", t.Cfg.Timeout(), msg), resp, req.Method != "HEAD", nil) return resp, err } time.Sleep(nextSleep) if nextSleep < nextSleepLimit { nextSleep *= 2 } continue } return } } // We need to send the redirect responses back to the HTTP client from RoundTrip, // but we don't want to cache them. func shouldCache(statusCode int) bool { switch statusCode { case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect: return false } return true }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_factories/create/remote_test.go
resources/resource_factories/create/remote_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package create import ( "testing" qt "github.com/frankban/quicktest" ) func TestDecodeRemoteOptions(t *testing.T) { t.Parallel() c := qt.New(t) for _, test := range []struct { name string args map[string]any want fromRemoteOptions wantErr bool }{ { "POST", map[string]any{ "meThod": "PoST", "headers": map[string]any{ "foo": "bar", }, }, fromRemoteOptions{ Method: "POST", Headers: map[string]any{ "foo": "bar", }, }, false, }, { "Body", map[string]any{ "meThod": "POST", "body": []byte("foo"), }, fromRemoteOptions{ Method: "POST", Body: []byte("foo"), }, false, }, { "Body, string", map[string]any{ "meThod": "POST", "body": "foo", }, fromRemoteOptions{ Method: "POST", Body: []byte("foo"), }, false, }, } { c.Run(test.name, func(c *qt.C) { got, err := decodeRemoteOptions(test.args) isErr := qt.IsNil if test.wantErr { isErr = qt.IsNotNil } c.Assert(err, isErr) c.Assert(got, qt.DeepEquals, test.want) }) } } func TestOptionsNewRequest(t *testing.T) { t.Parallel() c := qt.New(t) opts := fromRemoteOptions{ Method: "GET", Body: []byte("foo"), } req, err := opts.NewRequest("https://example.com/api") c.Assert(err, qt.IsNil) c.Assert(req.Method, qt.Equals, "GET") c.Assert(req.Header["User-Agent"], qt.DeepEquals, []string{"Hugo Static Site Generator"}) opts = fromRemoteOptions{ Method: "GET", Body: []byte("foo"), Headers: map[string]any{ "User-Agent": "foo", }, } req, err = opts.NewRequest("https://example.com/api") c.Assert(err, qt.IsNil) c.Assert(req.Method, qt.Equals, "GET") c.Assert(req.Header["User-Agent"], qt.DeepEquals, []string{"foo"}) } func TestRemoteResourceKeys(t *testing.T) { t.Parallel() c := qt.New(t) check := func(uri string, optionsm map[string]any, expect1, expect2 string) { c.Helper() got1, got2 := remoteResourceKeys(uri, optionsm) c.Assert(got1, qt.Equals, expect1) c.Assert(got2, qt.Equals, expect2) } check("foo", nil, "7763396052142361238", "7763396052142361238") check("foo", map[string]any{"bar": "baz"}, "5783339285578751849", "5783339285578751849") check("foo", map[string]any{"key": "1234", "bar": "baz"}, "15578353952571222948", "5783339285578751849") check("foo", map[string]any{"key": "12345", "bar": "baz"}, "14335752410685132726", "5783339285578751849") check("asdf", map[string]any{"key": "1234", "bar": "asdf"}, "15578353952571222948", "15615023578599429261") check("asdf", map[string]any{"key": "12345", "bar": "asdf"}, "14335752410685132726", "15615023578599429261") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_factories/create/create_integration_test.go
resources/resource_factories/create/create_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package create_test import ( "fmt" "math/rand" "net/http" "net/http/httptest" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestGetRemoteHead(t *testing.T) { files := ` -- hugo.toml -- [security] [security.http] methods = ['(?i)GET|POST|HEAD'] urls = ['.*gohugo\.io.*'] -- layouts/home.html -- {{ $url := "https://gohugo.io/img/hugo.png" }} {{ $opts := dict "method" "head" }} {{ with try (resources.GetRemote $url $opts) }} {{ with .Err }} {{ errorf "Unable to get remote resource: %s" . }} {{ else with .Value }} Head Content: {{ .Content }}. Head Data: {{ .Data }} {{ else }} {{ errorf "Unable to get remote resource: %s" $url }} {{ end }} {{ end }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ) b.Build() b.AssertFileContent("public/index.html", "Head Content: .", "Head Data: map[ContentLength:18210 ContentType:image/png Headers:map[] Status:200 OK StatusCode:200 TransferEncoding:[]]", ) } func TestGetRemoteResponseHeaders(t *testing.T) { files := ` -- hugo.toml -- [security] [security.http] methods = ['(?i)GET|POST|HEAD'] urls = ['.*gohugo\.io.*'] -- layouts/home.html -- {{ $url := "https://gohugo.io/img/hugo.png" }} {{ $opts := dict "method" "head" "responseHeaders" (slice "X-Frame-Options" "Server") }} {{ with try (resources.GetRemote $url $opts) }} {{ with .Err }} {{ errorf "Unable to get remote resource: %s" . }} {{ else with .Value }} Response Headers: {{ .Data.Headers }} {{ else }} {{ errorf "Unable to get remote resource: %s" $url }} {{ end }} {{ end }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ) b.Build() b.AssertFileContent("public/index.html", "Response Headers: map[Server:[Netlify] X-Frame-Options:[DENY]]", ) } func TestGetRemoteRetry(t *testing.T) { t.Parallel() temporaryHTTPCodes := []int{408, 429, 500, 502, 503, 504} numPages := 20 handler := func(w http.ResponseWriter, r *http.Request) { if rand.Intn(3) == 0 { w.WriteHeader(temporaryHTTPCodes[rand.Intn(len(temporaryHTTPCodes))]) return } w.Header().Add("Content-Type", "text/plain") w.Write([]byte("Response for " + r.URL.Path + ".")) } srv := httptest.NewServer(http.HandlerFunc(handler)) t.Cleanup(func() { srv.Close() }) filesTemplate := ` -- hugo.toml -- disableKinds = ["home", "taxonomy", "term"] timeout = "TIMEOUT" [security] [security.http] urls = ['.*'] mediaTypes = ['text/plain'] -- layouts/single.html -- {{ $url := printf "%s%s" "URL" .RelPermalink}} {{ $opts := dict }} {{ with try (resources.GetRemote $url $opts) }} {{ with .Err }} {{ errorf "Got Err: %s" . }} {{ with .Cause }}{{ errorf "Data: %s" .Data }}{{ end }} {{ else with .Value }} Content: {{ .Content }} {{ else }} {{ errorf "Unable to get remote resource: %s" $url }} {{ end }} {{ end }} ` for i := range numPages { filesTemplate += fmt.Sprintf("-- content/post/p%d.md --\n", i) } filesTemplate = strings.ReplaceAll(filesTemplate, "URL", srv.URL) t.Run("OK", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "TIMEOUT", "60s") b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ) b.Build() for i := range numPages { b.AssertFileContent(fmt.Sprintf("public/post/p%d/index.html", i), fmt.Sprintf("Content: Response for /post/p%d/.", i)) } }) t.Run("Timeout", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "TIMEOUT", "100ms") b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() // This is hard to get stable on GitHub Actions, it sometimes succeeds due to timing issues. if err != nil { b.AssertLogContains("Got Err") b.AssertLogContains("retry timeout") } }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_factories/bundler/bundler_test.go
resources/resource_factories/bundler/bundler_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package bundler import ( "testing" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/hugio" ) func TestMultiReadSeekCloser(t *testing.T) { c := qt.New(t) rc := newMultiReadSeekCloser( hugio.NewReadSeekerNoOpCloserFromString("A"), hugio.NewReadSeekerNoOpCloserFromString("B"), hugio.NewReadSeekerNoOpCloserFromString("C"), ) for range 3 { s1 := helpers.ReaderToString(rc) c.Assert(s1, qt.Equals, "ABC") _, err := rc.Seek(0, 0) c.Assert(err, qt.IsNil) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_factories/bundler/bundler.go
resources/resource_factories/bundler/bundler.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package bundler contains functions for concatenation etc. of Resource objects. package bundler import ( "fmt" "io" "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" ) // Client contains methods perform concatenation and other bundling related // tasks to Resource objects. type Client struct { rs *resources.Spec } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } type multiReadSeekCloser struct { mr io.Reader sources []hugio.ReadSeekCloser } func toReaders(sources []hugio.ReadSeekCloser) []io.Reader { readers := make([]io.Reader, len(sources)) for i, r := range sources { readers[i] = r } return readers } func newMultiReadSeekCloser(sources ...hugio.ReadSeekCloser) *multiReadSeekCloser { mr := io.MultiReader(toReaders(sources)...) return &multiReadSeekCloser{mr, sources} } func (r *multiReadSeekCloser) Read(p []byte) (n int, err error) { return r.mr.Read(p) } func (r *multiReadSeekCloser) Seek(offset int64, whence int) (newOffset int64, err error) { for _, s := range r.sources { newOffset, err = s.Seek(offset, whence) if err != nil { return } } r.mr = io.MultiReader(toReaders(r.sources)...) return } func (r *multiReadSeekCloser) Close() error { for _, s := range r.sources { s.Close() } return nil } // Concat concatenates the list of Resource objects. func (c *Client) Concat(targetPath string, r resource.Resources) (resource.Resource, error) { targetPath = path.Clean(targetPath) return c.rs.ResourceCache.GetOrCreate(targetPath, func() (resource.Resource, error) { var resolvedm media.Type // 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, 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 = rr.MediaType() } idm := c.rs.Cfg.NewIdentityManager() // Re-create on structural changes. idm.AddIdentity(identity.StructuralChangeAdd, identity.StructuralChangeRemove) // 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 { rcr, ok := s.(resource.ReadSeekCloserResource) if !ok { return nil, fmt.Errorf("resource %T does not implement resource.ReadSeekerCloserResource", s) } rc, err := rcr.ReadSeekCloser() if err != nil { // Close the already opened. for _, rcs := range rcsources { rcs.Close() } return nil, err } rcsources = append(rcsources, rc) } // Arbitrary JavaScript files require a barrier between them to be safely concatenated together. // Without this, the last line of one file can affect the first line of the next file and change how both files are interpreted. if resolvedm.MainType == media.Builtin.JavascriptType.MainType && resolvedm.SubType == media.Builtin.JavascriptType.SubType { readers := make([]hugio.ReadSeekCloser, 2*len(rcsources)-1) j := 0 for i := range rcsources { if i > 0 { readers[j] = hugio.NewReadSeekerNoOpCloserFromString("\n;\n") j++ } readers[j] = rcsources[i] j++ } return newMultiReadSeekCloser(readers...), nil } return newMultiReadSeekCloser(rcsources...), nil } composite, err := c.rs.NewResource( resources.ResourceSourceDescriptor{ LazyPublish: true, OpenReadSeekCloser: concatr, TargetPath: targetPath, DependencyManager: idm, }) if err != nil { return nil, err } return composite, nil }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/jsconfig/jsconfig_test.go
resources/jsconfig/jsconfig_test.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package jsconfig import ( "path/filepath" "testing" qt "github.com/frankban/quicktest" ) func TestJsConfigBuilder(t *testing.T) { c := qt.New(t) b := NewBuilder() b.AddSourceRoot("/c/assets") b.AddSourceRoot("/d/assets") conf := b.Build("/a/b") c.Assert(conf.CompilerOptions.BaseURL, qt.Equals, ".") c.Assert(conf.CompilerOptions.Paths["*"], qt.DeepEquals, []string{filepath.FromSlash("../../c/assets/*"), filepath.FromSlash("../../d/assets/*")}) c.Assert(NewBuilder().Build("/a/b"), qt.IsNil) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/jsconfig/jsconfig.go
resources/jsconfig/jsconfig.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package jsconfig import ( "path/filepath" "sort" "sync" ) // Builder builds a jsconfig.json file that, currently, is used only to assist // IntelliSense in editors. type Builder struct { sourceRootsMu sync.RWMutex sourceRoots map[string]bool } // NewBuilder creates a new Builder. func NewBuilder() *Builder { return &Builder{sourceRoots: make(map[string]bool)} } // Build builds a new Config with paths relative to dir. // This method is thread safe. func (b *Builder) Build(dir string) *Config { b.sourceRootsMu.RLock() defer b.sourceRootsMu.RUnlock() if len(b.sourceRoots) == 0 { return nil } conf := newJSConfig() var roots []string for root := range b.sourceRoots { rel, err := filepath.Rel(dir, filepath.Join(root, "*")) if err == nil { roots = append(roots, rel) } } sort.Strings(roots) conf.CompilerOptions.Paths["*"] = roots return conf } // AddSourceRoot adds a new source root. // This method is thread safe. func (b *Builder) AddSourceRoot(root string) { b.sourceRootsMu.RLock() found := b.sourceRoots[root] b.sourceRootsMu.RUnlock() if found { return } b.sourceRootsMu.Lock() b.sourceRoots[root] = true b.sourceRootsMu.Unlock() } // CompilerOptions holds compilerOptions for jsonconfig.json. type CompilerOptions struct { BaseURL string `json:"baseUrl"` Paths map[string][]string `json:"paths"` } // Config holds the data for jsconfig.json. type Config struct { CompilerOptions CompilerOptions `json:"compilerOptions"` } func newJSConfig() *Config { return &Config{ CompilerOptions: CompilerOptions{ BaseURL: ".", Paths: make(map[string][]string), }, } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource/resources_integration_test.go
resources/resource/resources_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resource_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestResourcesMount(t *testing.T) { files := ` -- hugo.toml -- -- assets/text/txt1.txt -- Text 1. -- assets/text/txt2.txt -- Text 2. -- assets/text/sub/txt3.txt -- Text 3. -- assets/text/sub/txt4.txt -- Text 4. -- content/mybundle/index.md -- --- title: "My Bundle" --- -- content/mybundle/txt1.txt -- Text 1. -- content/mybundle/sub/txt2.txt -- Text 1. -- layouts/home.html -- {{ $mybundle := site.GetPage "mybundle" }} {{ $subResources := resources.Match "/text/sub/*.*" }} {{ $subResourcesMount := $subResources.Mount "/text/sub" "/newroot" }} resources:text/txt1.txt:{{ with resources.Get "text/txt1.txt" }}{{ .Name }}{{ end }}| resources:text/txt2.txt:{{ with resources.Get "text/txt2.txt" }}{{ .Name }}{{ end }}| resources:text/sub/txt3.txt:{{ with resources.Get "text/sub/txt3.txt" }}{{ .Name }}{{ end }}| subResources.range:{{ range $subResources }}{{ .Name }}|{{ end }}| subResources:"text/sub/txt3.txt:{{ with $subResources.Get "text/sub/txt3.txt" }}{{ .Name }}{{ end }}| subResourcesMount:/newroot/txt3.txt:{{ with $subResourcesMount.Get "/newroot/txt3.txt" }}{{ .Name }}{{ end }}| page:txt1.txt:{{ with $mybundle.Resources.Get "txt1.txt" }}{{ .Name }}{{ end }}| page:./txt1.txt:{{ with $mybundle.Resources.Get "./txt1.txt" }}{{ .Name }}{{ end }}| page:sub/txt2.txt:{{ with $mybundle.Resources.Get "sub/txt2.txt" }}{{ .Name }}{{ end }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` resources:text/txt1.txt:/text/txt1.txt| resources:text/txt2.txt:/text/txt2.txt| resources:text/sub/txt3.txt:/text/sub/txt3.txt| subResources:"text/sub/txt3.txt:/text/sub/txt3.txt| subResourcesMount:/newroot/txt3.txt:/text/sub/txt3.txt| page:txt1.txt:txt1.txt| page:./txt1.txt:txt1.txt| page:sub/txt2.txt:sub/txt2.txt| `) } func TestResourcesMountOnRename(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "home", "sitemap"] -- content/mybundle/index.md -- --- title: "My Bundle" resources: - name: /foo/bars.txt src: foo/txt1.txt - name: foo/bars2.txt src: foo/txt2.txt --- -- content/mybundle/foo/txt1.txt -- Text 1. -- content/mybundle/foo/txt2.txt -- Text 2. -- layouts/single.html -- Single. {{ $mybundle := site.GetPage "mybundle" }} Resources:{{ range $mybundle.Resources }}Name: {{ .Name }}|{{ end }}$ {{ $subResourcesMount := $mybundle.Resources.Mount "/foo" "/newroot" }} {{ $subResourcesMount2 := $mybundle.Resources.Mount "foo" "/newroot" }} {{ $subResourcesMount3 := $mybundle.Resources.Mount "foo" "." }} subResourcesMount:/newroot/bars.txt:{{ with $subResourcesMount.Get "/newroot/bars.txt" }}{{ .Name }}{{ end }}| subResourcesMount:/newroot/bars2.txt:{{ with $subResourcesMount.Get "/newroot/bars2.txt" }}{{ .Name }}{{ end }}| subResourcesMount2:/newroot/bars2.txt:{{ with $subResourcesMount2.Get "/newroot/bars2.txt" }}{{ .Name }}{{ end }}| subResourcesMount3:bars2.txt:{{ with $subResourcesMount3.Get "bars2.txt" }}{{ .Name }}{{ end }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/mybundle/index.html", "Resources:Name: foo/bars.txt|Name: foo/bars2.txt|$", "subResourcesMount:/newroot/bars.txt:|\nsubResourcesMount:/newroot/bars2.txt:|", "subResourcesMount2:/newroot/bars2.txt:foo/bars2.txt|", "subResourcesMount3:bars2.txt:foo/bars2.txt|", ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource/resources.go
resources/resource/resources.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package resource contains Resource related types. package resource import ( "fmt" "path" "slices" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/spf13/cast" ) var _ ResourceFinder = (*Resources)(nil) // Resources represents a slice of resources, which can be a mix of different types. // I.e. both pages and images etc. type Resources []Resource // Mount mounts the given resources from base to the given target path. // Note that leading slashes in target marks an absolute path. // This method is currently only useful in js.Batch. func (r Resources) Mount(base, target string) ResourceGetter { return resourceGetterFunc(func(namev any) Resource { name1, err := cast.ToStringE(namev) if err != nil { panic(err) } isTargetAbs := strings.HasPrefix(target, "/") if target != "" { name1 = strings.TrimPrefix(name1, target) if !isTargetAbs { name1 = paths.TrimLeading(name1) } } if base != "" && isTargetAbs { name1 = path.Join(base, name1) } for _, res := range r { name2 := res.Name() if base != "" && !isTargetAbs { name2 = paths.TrimLeading(strings.TrimPrefix(name2, base)) } if strings.EqualFold(name1, name2) { return res } } return nil }) } type ResourcesProvider interface { // Resources returns a list of all resources. Resources() Resources } // var _ resource.ResourceFinder = (*Namespace)(nil) // ResourcesConverter converts a given slice of Resource objects to Resources. type ResourcesConverter interface { // For internal use. ToResources() Resources } // ByType returns resources of a given resource type (e.g. "image"). func (r Resources) ByType(typ any) Resources { tpstr, err := cast.ToStringE(typ) if err != nil { panic(err) } var filtered Resources for _, resource := range r { if resource.ResourceType() == tpstr { filtered = append(filtered, resource) } } return filtered } // Get locates the name given in Resources. // The search is case insensitive. func (r Resources) Get(name any) Resource { if r == nil { return nil } namestr, err := cast.ToStringE(name) if err != nil { panic(err) } isDotCurrent := strings.HasPrefix(namestr, "./") if isDotCurrent { namestr = strings.TrimPrefix(namestr, "./") } else { namestr = paths.AddLeadingSlash(namestr) } check := func(name string) bool { if !isDotCurrent { name = paths.AddLeadingSlash(name) } return strings.EqualFold(namestr, name) } // First check the Name. // Note that this can be modified by the user in the front matter, // also, it does not contain any language code. for _, resource := range r { if check(resource.Name()) { return resource } } // Finally, check the normalized name. for _, resource := range r { if nop, ok := resource.(NameNormalizedProvider); ok { if check(nop.NameNormalized()) { return resource } } } return nil } // GetMatch finds the first Resource matching the given pattern, or nil if none found. // See Match for a more complete explanation about the rules used. func (r Resources) GetMatch(pattern any) Resource { patternstr, err := cast.ToStringE(pattern) if err != nil { panic(err) } g, err := hglob.GetGlob(paths.AddLeadingSlash(patternstr)) if err != nil { panic(err) } for _, resource := range r { if g.Match(paths.AddLeadingSlash(resource.Name())) { return resource } } // Finally, check the normalized name. for _, resource := range r { if nop, ok := resource.(NameNormalizedProvider); ok { if g.Match(paths.AddLeadingSlash(nop.NameNormalized())) { return resource } } } return nil } // Match gets all resources matching the given base filename prefix, e.g // "*.png" will match all png files. The "*" does not match path delimiters (/), // so if you organize your resources in sub-folders, you need to be explicit about it, e.g.: // "images/*.png". To match any PNG image anywhere in the bundle you can do "**.png", and // to match all PNG images below the images folder, use "images/**.jpg". // The matching is case insensitive. // Match matches by using the value of Resource.Name, which, by default, is a filename with // path relative to the bundle root with Unix style slashes (/) and no leading slash, e.g. "images/logo.png". // See https://github.com/gobwas/glob for the full rules set. func (r Resources) Match(pattern any) Resources { patternstr, err := cast.ToStringE(pattern) if err != nil { panic(err) } g, err := hglob.GetGlob(paths.AddLeadingSlash(patternstr)) if err != nil { panic(err) } var matches Resources for _, resource := range r { if g.Match(paths.AddLeadingSlash(resource.Name())) { matches = append(matches, resource) } } if len(matches) == 0 { // Fall back to the normalized name. for _, resource := range r { if nop, ok := resource.(NameNormalizedProvider); ok { if g.Match(paths.AddLeadingSlash(nop.NameNormalized())) { matches = append(matches, resource) } } } } return matches } type translatedResource interface { TranslationKey() string } // MergeByLanguage adds missing translations in r1 from r2. func (r Resources) MergeByLanguage(r2 Resources) Resources { result := slices.Clone(r) m := make(map[string]bool) for _, rr := range r { if translated, ok := rr.(translatedResource); ok { m[translated.TranslationKey()] = true } } for _, rr := range r2 { if translated, ok := rr.(translatedResource); ok { if _, found := m[translated.TranslationKey()]; !found { result = append(result, rr) } } } return result } // MergeByLanguageInterface is the generic version of MergeByLanguage. It // is here just so it can be called from the tpl package. // This is for internal use. func (r Resources) MergeByLanguageInterface(in any) (any, error) { r2, ok := in.(Resources) if !ok { return nil, fmt.Errorf("%T cannot be merged by language", in) } return r.MergeByLanguage(r2), nil } // Source is an internal template and not meant for use in the templates. It // may change without notice. type Source interface { Publish() error } type ResourceGetter interface { // Get locates the Resource with the given name in the current context (e.g. in .Page.Resources). // // It returns nil if no Resource could found, panics if name is invalid. Get(name any) Resource } type IsProbablySameResourceGetter interface { IsProbablySameResourceGetter(other ResourceGetter) bool } // StaleInfoResourceGetter is a ResourceGetter that also provides information about // whether the underlying resources are stale. type StaleInfoResourceGetter interface { StaleInfo ResourceGetter } type resourceGetterFunc func(name any) Resource func (f resourceGetterFunc) Get(name any) Resource { return f(name) } // ResourceFinder provides methods to find Resources. // Note that GetRemote (as found in resources.GetRemote) is // not covered by this interface, as this is only available as a global template function. type ResourceFinder interface { ResourceGetter // GetMatch finds the first Resource matching the given pattern, or nil if none found. // // See Match for a more complete explanation about the rules used. // // It returns nil if no Resource could found, panics if pattern is invalid. GetMatch(pattern any) Resource // Match gets all resources matching the given base path prefix, e.g // "*.png" will match all png files. The "*" does not match path delimiters (/), // so if you organize your resources in sub-folders, you need to be explicit about it, e.g.: // "images/*.png". To match any PNG image anywhere in the bundle you can do "**.png", and // to match all PNG images below the images folder, use "images/**.jpg". // // The matching is case insensitive. // // Match matches by using a relative pathwith Unix style slashes (/) and no // leading slash, e.g. "images/logo.png". // // See https://github.com/gobwas/glob for the full rules set. // // See Match for a more complete explanation about the rules used. // // It returns nil if no Resources could found, panics if pattern is invalid. Match(pattern any) Resources // ByType returns resources of a given resource type (e.g. "image"). // It returns nil if no Resources could found, panics if typ is invalid. ByType(typ any) Resources } // NewCachedResourceGetter creates a new ResourceGetter from the given objects. // If multiple objects are provided, they are merged into one where // the first match wins. func NewCachedResourceGetter(os ...any) *cachedResourceGetter { var getters multiResourceGetter for _, o := range os { if g, ok := unwrapResourceGetter(o); ok { getters = append(getters, g) } } return &cachedResourceGetter{ cache: maps.NewCache[string, Resource](), delegate: getters, } } type multiResourceGetter []ResourceGetter func (m multiResourceGetter) Get(name any) Resource { for _, g := range m { if res := g.Get(name); res != nil { return res } } return nil } var ( _ ResourceGetter = (*cachedResourceGetter)(nil) _ IsProbablySameResourceGetter = (*cachedResourceGetter)(nil) ) type cachedResourceGetter struct { cache *maps.Cache[string, Resource] delegate ResourceGetter } func (c *cachedResourceGetter) Get(name any) Resource { namestr, err := cast.ToStringE(name) if err != nil { panic(err) } v, _ := c.cache.GetOrCreate(namestr, func() (Resource, error) { v := c.delegate.Get(name) return v, nil }) return v } func (c *cachedResourceGetter) IsProbablySameResourceGetter(other ResourceGetter) bool { isProbablyEq := true c.cache.ForEeach(func(k string, v Resource) bool { if v != other.Get(k) { isProbablyEq = false return false } return true }) return isProbablyEq } func unwrapResourceGetter(v any) (ResourceGetter, bool) { if v == nil { return nil, false } switch vv := v.(type) { case ResourceGetter: return vv, true case ResourcesProvider: return vv.Resources(), true case func(name any) Resource: return resourceGetterFunc(vv), true default: vvv, ok := hreflect.ToSliceAny(v) if !ok { return nil, false } var getters multiResourceGetter for _, vv := range vvv { if g, ok := unwrapResourceGetter(vv); ok { getters = append(getters, g) } } return getters, len(getters) > 0 } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource/resource_helpers.go
resources/resource/resource_helpers.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resource import ( "strings" "time" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" "github.com/pelletier/go-toml/v2" "github.com/spf13/cast" ) // GetParam will return the param with the given key from the Resource, // nil if not found. func GetParam(r Resource, key string) any { return getParam(r, key, false) } // GetParamToLower is the same as GetParam but it will lower case any string // result, including string slices. func GetParamToLower(r Resource, key string) any { return getParam(r, key, true) } func getParam(r Resource, key string, stringToLower bool) any { v, err := maps.GetNestedParam(key, ".", r.Params()) if v == nil || err != nil { return nil } switch val := v.(type) { case bool: return val case string: if stringToLower { return strings.ToLower(val) } return val case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return val case toml.LocalDate: return val.AsTime(time.UTC) case toml.LocalDateTime: return val.AsTime(time.UTC) case []string: if stringToLower { return helpers.SliceToLower(val) } return v case map[string]any: return v case map[any]any: return v } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource/resourcetypes.go
resources/resource/resourcetypes.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resource import ( "context" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/common/hugio" ) var ( _ ResourceDataProvider = (*resourceError)(nil) _ ResourceError = (*resourceError)(nil) ) // Cloner is for internal use. type Cloner interface { Clone() Resource } // OriginProvider provides the original Resource if this is wrapped. // This is an internal Hugo interface and not meant for use in the templates. type OriginProvider interface { Origin() Resource GetFieldString(pattern string) (string, bool) } // NewResourceError creates a new ResourceError. func NewResourceError(err error, data any) ResourceError { if data == nil { data = map[string]any{} } return &resourceError{ error: err, data: data, } } type resourceError struct { error data any } // The data associated with this error. func (e *resourceError) Data() any { return e.data } // ResourceError is the error return from .Err in Resource in error situations. type ResourceError interface { error ResourceDataProvider } // Resource represents a linkable resource, i.e. a content page, image etc. type Resource interface { ResourceWithoutMeta ResourceMetaProvider } type ResourceWithoutMeta interface { ResourceTypeProvider MediaTypeProvider ResourceLinksProvider ResourceDataProvider } type ResourceTypeProvider interface { // ResourceType is the resource type. For most file types, this is the main // part of the MIME type, e.g. "image", "application", "text" etc. // For content pages, this value is "page". ResourceType() string } type ResourceTypesProvider interface { ResourceTypeProvider MediaTypeProvider } type MediaTypeProvider interface { // MediaType is this resource's MIME type. MediaType() media.Type } type ResourceLinksProvider interface { // Permalink represents the absolute link to this resource. Permalink() string // RelPermalink represents the host relative link to this resource. RelPermalink() string } // ResourceMetaProvider provides metadata about a resource. type ResourceMetaProvider interface { ResourceNameTitleProvider ResourceParamsProvider } type WithResourceMetaProvider interface { // WithResourceMeta creates a new Resource with the given metadata. // For internal use. WithResourceMeta(ResourceMetaProvider) Resource } type ResourceNameTitleProvider interface { // Name is the logical name of this resource. This can be set in the front matter // metadata for this resource. If not set, Hugo will assign a value. // This will in most cases be the base filename. // So, for the image "/some/path/sunset.jpg" this will be "sunset.jpg". // The value returned by this method will be used in the GetByPrefix and ByPrefix methods // on Resources. Name() string // Title returns the title if set in front matter. For content pages, this will be the expected value. Title() string } type NameNormalizedProvider interface { // NameNormalized is the normalized name of this resource. // For internal use (for now). NameNormalized() string } type ResourceParamsProvider interface { // Params set in front matter for this resource. Params() maps.Params } type ResourceDataProvider interface { // Resource specific data set by Hugo. // One example would be .Data.Integrity for fingerprinted resources. Data() any } // ResourcesLanguageMerger describes an interface for merging resources from a // different language. type ResourcesLanguageMerger interface { MergeByLanguage(other Resources) Resources // Needed for integration with the tpl package. // For internal use. MergeByLanguageInterface(other any) (any, error) } // Identifier identifies a resource. type Identifier interface { // Key is mostly for internal use and should be considered opaque. // This value may change between Hugo versions. Key() string } // TransientIdentifier identifies a transient resource. type TransientIdentifier interface { // TransientKey is mostly for internal use and should be considered opaque. // This value is implemented by transient resources where pointers may be short lived and // not suitable for use as a map keys. TransientKey() string } // ContentResource represents a Resource that provides a way to get to its content. // Most Resource types in Hugo implements this interface, including Page. type ContentResource interface { MediaType() media.Type ContentProvider } // ContentProvider provides Content. // This should be used with care, as it will read the file content into memory, but it // should be cached as effectively as possible by the implementation. type ContentProvider interface { // Content returns this resource's content. It will be equivalent to reading the content // that RelPermalink points to in the published folder. // The return type will be contextual, and should be what you would expect: // * Page: template.HTML // * JSON: String // * Etc. Content(context.Context) (any, error) } // ReadSeekCloserResource is a Resource that supports loading its content. type ReadSeekCloserResource interface { MediaType() media.Type hugio.ReadSeekCloserProvider } // LengthProvider is a Resource that provides a length // (typically the length of the content). type LengthProvider interface { Len(context.Context) int } // LanguageProvider is a Resource in a language. type LanguageProvider interface { Language() *langs.Language Lang() string } // TranslationKeyProvider connects translations of the same Resource. type TranslationKeyProvider interface { TranslationKey() string } // Staler controls stale state of a Resource. A stale resource should be discarded. type Staler interface { StaleMarker StaleInfo } // StaleMarker marks a Resource as stale. type StaleMarker interface { MarkStale() } // StaleInfo tells if a resource is marked as stale. type StaleInfo interface { StaleVersion() uint32 } // StaleVersion returns the StaleVersion for the given os, // or 0 if not set. func StaleVersion(os any) uint32 { if s, ok := os.(StaleInfo); ok { return s.StaleVersion() } return 0 } // StaleVersionSum calculates the sum of the StaleVersionSum for the given oss. func StaleVersionSum(oss ...any) uint32 { var version uint32 for _, o := range oss { if s, ok := o.(StaleInfo); ok && s.StaleVersion() > 0 { version += s.StaleVersion() } } return version } // MarkStale will mark any of the oses as stale, if possible. func MarkStale(os ...any) { for _, o := range os { if types.IsNil(o) { continue } if s, ok := o.(StaleMarker); ok { s.MarkStale() } } } // UnmarshableResource represents a Resource that can be unmarshaled to some other format. type UnmarshableResource interface { ReadSeekCloserResource Identifier } type resourceTypesHolder struct { mediaType media.Type resourceType string } func (r resourceTypesHolder) MediaType() media.Type { return r.mediaType } func (r resourceTypesHolder) ResourceType() string { return r.resourceType } func NewResourceTypesProvider(mediaType media.Type, resourceType string) ResourceTypesProvider { return resourceTypesHolder{mediaType: mediaType, resourceType: resourceType} } // NameNormalizedOrName returns the normalized name if available, otherwise the name. func NameNormalizedOrName(r Resource) string { if nn, ok := r.(NameNormalizedProvider); ok { return nn.NameNormalized() } return r.Name() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource/params.go
resources/resource/params.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resource import ( "github.com/gohugoio/hugo/common/maps" "github.com/spf13/cast" ) func Param(r ResourceParamsProvider, fallback maps.Params, key any) (any, error) { keyStr, err := cast.ToStringE(key) if err != nil { return nil, err } if fallback == nil { return maps.GetNestedParam(keyStr, ".", r.Params()) } return maps.GetNestedParam(keyStr, ".", r.Params(), fallback) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource/dates.go
resources/resource/dates.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resource import ( "time" "github.com/gohugoio/hugo/common/htime" ) // Dated wraps a "dated resource". These are the 4 dates that makes // the date logic in Hugo. type Dated interface { // Date returns the date of the resource. Date() time.Time // Lastmod returns the last modification date of the resource. Lastmod() time.Time // PublishDate returns the publish date of the resource. PublishDate() time.Time // ExpiryDate returns the expiration date of the resource. ExpiryDate() time.Time } // IsFuture returns whether the argument represents the future. func IsFuture(d Dated) bool { if d.PublishDate().IsZero() { return false } return d.PublishDate().After(htime.Now()) } // IsExpired returns whether the argument is expired. func IsExpired(d Dated) bool { if d.ExpiryDate().IsZero() { return false } return d.ExpiryDate().Before(htime.Now()) } // IsZeroDates returns true if all of the dates are zero. func IsZeroDates(d Dated) bool { return d.Date().IsZero() && d.Lastmod().IsZero() && d.ExpiryDate().IsZero() && d.PublishDate().IsZero() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource/resources_test.go
resources/resource/resources_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resource import ( "testing" qt "github.com/frankban/quicktest" ) func TestResourcesMount(t *testing.T) { c := qt.New(t) c.Assert(true, qt.IsTrue) var m ResourceGetter var r Resources check := func(in, expect string) { c.Helper() r := m.Get(in) c.Assert(r, qt.Not(qt.IsNil)) c.Assert(r.Name(), qt.Equals, expect) } checkNil := func(in string) { c.Helper() r := m.Get(in) c.Assert(r, qt.IsNil) } // Misc tests. r = Resources{ testResource{name: "/foo/theme.css"}, } m = r.Mount("/foo", ".") check("./theme.css", "/foo/theme.css") // Relative target. r = Resources{ testResource{name: "/a/b/c/d.txt"}, testResource{name: "/a/b/c/e/f.txt"}, testResource{name: "/a/b/d.txt"}, testResource{name: "/a/b/e.txt"}, } m = r.Mount("/a/b/c", "z") check("z/d.txt", "/a/b/c/d.txt") check("z/e/f.txt", "/a/b/c/e/f.txt") m = r.Mount("/a/b", "") check("d.txt", "/a/b/d.txt") m = r.Mount("/a/b", ".") check("d.txt", "/a/b/d.txt") m = r.Mount("/a/b", "./") check("d.txt", "/a/b/d.txt") check("./d.txt", "/a/b/d.txt") m = r.Mount("/a/b", ".") check("./d.txt", "/a/b/d.txt") // Absolute target. m = r.Mount("/a/b/c", "/z") check("/z/d.txt", "/a/b/c/d.txt") check("/z/e/f.txt", "/a/b/c/e/f.txt") checkNil("/z/f.txt") m = r.Mount("/a/b", "/z") check("/z/c/d.txt", "/a/b/c/d.txt") check("/z/c/e/f.txt", "/a/b/c/e/f.txt") check("/z/d.txt", "/a/b/d.txt") checkNil("/z/f.txt") m = r.Mount("", "") check("/a/b/c/d.txt", "/a/b/c/d.txt") check("/a/b/c/e/f.txt", "/a/b/c/e/f.txt") check("/a/b/d.txt", "/a/b/d.txt") checkNil("/a/b/f.txt") m = r.Mount("/a/b", "/a/b") check("/a/b/c/d.txt", "/a/b/c/d.txt") check("/a/b/c/e/f.txt", "/a/b/c/e/f.txt") check("/a/b/d.txt", "/a/b/d.txt") checkNil("/a/b/f.txt") // Resources with relative paths. r = Resources{ testResource{name: "a/b/c/d.txt"}, testResource{name: "a/b/c/e/f.txt"}, testResource{name: "a/b/d.txt"}, testResource{name: "a/b/e.txt"}, testResource{name: "n.txt"}, } m = r.Mount("a/b", "z") check("z/d.txt", "a/b/d.txt") checkNil("/z/d.txt") } type testResource struct { Resource name string } func (r testResource) Name() string { return r.name } func (r testResource) NameNormalized() string { return r.name }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/postpub/postpub.go
resources/postpub/postpub.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package postpub import ( "context" "fmt" "reflect" "strconv" "strings" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/resource" ) type PostPublishedResource interface { resource.ResourceTypeProvider resource.ResourceLinksProvider resource.ResourceNameTitleProvider resource.ResourceParamsProvider resource.ResourceDataProvider resource.OriginProvider MediaType() map[string]any } const ( PostProcessPrefix = "__h_pp_l1" // The suffix has an '=' in it to prevent the minifier to remove any enclosing // quoutes around the attribute values. // See issue #8884. PostProcessSuffix = "__e=" ) func NewPostPublishResource(id int, r resource.Resource) PostPublishedResource { return &PostPublishResource{ prefix: PostProcessPrefix + "_" + strconv.Itoa(id) + "_", delegate: r, } } // PostPublishResource holds a Resource to be transformed post publishing. type PostPublishResource struct { prefix string delegate resource.Resource } func (r *PostPublishResource) field(name string) string { return r.prefix + name + PostProcessSuffix } func (r *PostPublishResource) Permalink() string { return r.field("Permalink") } func (r *PostPublishResource) RelPermalink() string { return r.field("RelPermalink") } func (r *PostPublishResource) Origin() resource.Resource { return r.delegate } func (r *PostPublishResource) GetFieldString(pattern string) (string, bool) { if r == nil { panic("resource is nil") } prefixIdx := strings.Index(pattern, r.prefix) if prefixIdx == -1 { // Not a method on this resource. return "", false } fieldAccessor := pattern[prefixIdx+len(r.prefix) : strings.Index(pattern, PostProcessSuffix)] d := r.delegate switch { case fieldAccessor == "RelPermalink": return d.RelPermalink(), true case fieldAccessor == "Permalink": return d.Permalink(), true case fieldAccessor == "Name": return d.Name(), true case fieldAccessor == "Title": return d.Title(), true case fieldAccessor == "ResourceType": return d.ResourceType(), true case fieldAccessor == "Content": content, err := d.(resource.ContentProvider).Content(context.Background()) if err != nil { return "", true } return cast.ToString(content), true case strings.HasPrefix(fieldAccessor, "MediaType"): return r.fieldToString(d.MediaType(), fieldAccessor), true case fieldAccessor == "Data.Integrity": return cast.ToString((d.Data().(map[string]any)["Integrity"])), true default: panic(fmt.Sprintf("unknown field accessor %q", fieldAccessor)) } } func (r *PostPublishResource) fieldToString(receiver any, path string) string { fieldname := strings.Split(path, ".")[1] receiverv := reflect.ValueOf(receiver) switch receiverv.Kind() { case reflect.Map: v := receiverv.MapIndex(reflect.ValueOf(fieldname)) return cast.ToString(v.Interface()) default: v := receiverv.FieldByName(fieldname) if !v.IsValid() { method := hreflect.GetMethodByName(receiverv, fieldname) if method.IsValid() { vals := method.Call(nil) if len(vals) > 0 { v = vals[0] } } } if v.IsValid() { return cast.ToString(v.Interface()) } return "" } } func (r *PostPublishResource) Data() any { m := map[string]any{ "Integrity": "", } insertFieldPlaceholders("Data", m, r.field) return m } func (r *PostPublishResource) MediaType() map[string]any { m := structToMapWithPlaceholders("MediaType", media.Type{}, r.field) return m } func (r *PostPublishResource) ResourceType() string { return r.field("ResourceType") } func (r *PostPublishResource) Name() string { return r.field("Name") } func (r *PostPublishResource) Title() string { return r.field("Title") } func (r *PostPublishResource) Params() maps.Params { panic(r.fieldNotSupported("Params")) } func (r *PostPublishResource) Content(context.Context) (any, error) { return r.field("Content"), nil } func (r *PostPublishResource) fieldNotSupported(name string) string { return fmt.Sprintf("method .%s is currently not supported in post-publish transformations.", name) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/postpub/fields_test.go
resources/postpub/fields_test.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package postpub import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/media" ) func TestCreatePlaceholders(t *testing.T) { c := qt.New(t) m := structToMap(media.Builtin.CSSType) insertFieldPlaceholders("foo", m, func(s string) string { return "pre_" + s + "_post" }) c.Assert(m, qt.DeepEquals, map[string]any{ "IsZero": "pre_foo.IsZero_post", "MarshalJSON": "pre_foo.MarshalJSON_post", "Suffixes": "pre_foo.Suffixes_post", "SuffixesCSV": "pre_foo.SuffixesCSV_post", "Delimiter": "pre_foo.Delimiter_post", "FirstSuffix": "pre_foo.FirstSuffix_post", "IsHTML": "pre_foo.IsHTML_post", "IsMarkdown": "pre_foo.IsMarkdown_post", "IsText": "pre_foo.IsText_post", "String": "pre_foo.String_post", "Type": "pre_foo.Type_post", "MainType": "pre_foo.MainType_post", "SubType": "pre_foo.SubType_post", }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/postpub/fields.go
resources/postpub/fields.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package postpub import ( "reflect" ) const ( FieldNotSupported = "__field_not_supported" ) func structToMapWithPlaceholders(root string, in any, createPlaceholder func(s string) string) map[string]any { m := structToMap(in) insertFieldPlaceholders(root, m, createPlaceholder) return m } func structToMap(s any) map[string]any { m := make(map[string]any) t := reflect.TypeOf(s) for i := range t.NumMethod() { method := t.Method(i) if method.PkgPath != "" { continue } if method.Type.NumIn() == 1 { m[method.Name] = "" } } for i := range t.NumField() { field := t.Field(i) if field.PkgPath != "" { continue } m[field.Name] = "" } return m } // insert placeholder for the templates. Do it very shallow for now. func insertFieldPlaceholders(root string, m map[string]any, createPlaceholder func(s string) string) { for k := range m { m[k] = createPlaceholder(root + "." + k) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/kinds/kinds_test.go
resources/kinds/kinds_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package kinds import ( "testing" qt "github.com/frankban/quicktest" ) func TestKind(t *testing.T) { t.Parallel() c := qt.New(t) // Add tests for these constants to make sure they don't change c.Assert(KindPage, qt.Equals, "page") c.Assert(KindHome, qt.Equals, "home") c.Assert(KindSection, qt.Equals, "section") c.Assert(KindTaxonomy, qt.Equals, "taxonomy") c.Assert(KindTerm, qt.Equals, "term") c.Assert(GetKindMain("TAXONOMYTERM"), qt.Equals, KindTaxonomy) c.Assert(GetKindMain("Taxonomy"), qt.Equals, KindTaxonomy) c.Assert(GetKindMain("Page"), qt.Equals, KindPage) c.Assert(GetKindMain("Home"), qt.Equals, KindHome) c.Assert(GetKindMain("SEction"), qt.Equals, KindSection) c.Assert(GetKindAny("Page"), qt.Equals, KindPage) c.Assert(GetKindAny("Robotstxt"), qt.Equals, KindRobotsTXT) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/kinds/kinds.go
resources/kinds/kinds.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package kinds import ( "sort" "strings" ) const ( KindPage = "page" // The rest are node types; home page, sections etc. KindHome = "home" KindSection = "section" // Note that before Hugo 0.73 these were confusingly named // taxonomy (now: term) // taxonomyTerm (now: taxonomy) KindTaxonomy = "taxonomy" KindTerm = "term" // The following are (currently) temporary nodes, // i.e. nodes we create just to render in isolation. KindTemporary = "temporary" KindRSS = "rss" KindSitemap = "sitemap" KindSitemapIndex = "sitemapindex" KindRobotsTXT = "robotstxt" KindStatus404 = "404" ) var ( // This is all the kinds we can expect to find in .Site.Pages. AllKindsInPages []string // This is all the kinds, including the temporary ones. AllKinds []string ) func init() { for k := range kindMapMain { AllKindsInPages = append(AllKindsInPages, k) AllKinds = append(AllKinds, k) } for k := range kindMapTemporary { AllKinds = append(AllKinds, k) } // Sort the slices for determinism. sort.Strings(AllKindsInPages) sort.Strings(AllKinds) } var kindMapMain = map[string]string{ KindPage: KindPage, KindHome: KindHome, KindSection: KindSection, KindTaxonomy: KindTaxonomy, KindTerm: KindTerm, // Legacy, pre v0.53.0. "taxonomyterm": KindTaxonomy, } var kindMapTemporary = map[string]string{ KindRSS: KindRSS, KindSitemap: KindSitemap, KindRobotsTXT: KindRobotsTXT, KindStatus404: KindStatus404, } // GetKindMain gets the page kind given a string, empty if not found. // Note that this will not return any temporary kinds (e.g. robotstxt). func GetKindMain(s string) string { return kindMapMain[strings.ToLower(s)] } // GetKindAny gets the page kind given a string, empty if not found. func GetKindAny(s string) string { if pkind := GetKindMain(s); pkind != "" { return pkind } return kindMapTemporary[strings.ToLower(s)] } // IsBranch returns whether the given kind is a branch node. func IsBranch(kind string) bool { switch kind { case KindHome, KindSection, KindTaxonomy, KindTerm: return true default: return false } } // IsDeprecatedAndReplacedWith returns the new kind if the given kind is deprecated. func IsDeprecatedAndReplacedWith(s string) string { s = strings.ToLower(s) switch s { case "taxonomyterm": return KindTaxonomy default: return "" } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/integrity/integrity_test.go
resources/resource_transformers/integrity/integrity_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package integrity import ( "context" "testing" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/resources/resource" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/resources/resource_transformers/htesting" ) func TestHashFromAlgo(t *testing.T) { for _, algo := range []struct { name string bits int }{ {"md5", 128}, {"sha256", 256}, {"sha384", 384}, {"sha512", 512}, {"shaman", -1}, } { t.Run(algo.name, func(t *testing.T) { c := qt.New(t) h, err := newHash(algo.name) if algo.bits > 0 { c.Assert(err, qt.IsNil) c.Assert(h.Size(), qt.Equals, algo.bits/8) } else { c.Assert(err, qt.Not(qt.IsNil)) c.Assert(err.Error(), qt.Contains, "use either md5, sha256, sha384 or sha512") } }) } } func TestTransform(t *testing.T) { c := qt.New(t) d := testconfig.GetTestDeps(nil, nil) t.Cleanup(func() { c.Assert(d.Close(), qt.IsNil) }) client := New(d.ResourceSpec) r, err := htesting.NewResourceTransformerForSpec(d.ResourceSpec, "hugo.txt", "Hugo Rocks!") c.Assert(err, qt.IsNil) transformed, err := client.Fingerprint(r, "") c.Assert(err, qt.IsNil) c.Assert(transformed.RelPermalink(), qt.Equals, "/hugo.a5ad1c6961214a55de53c1ce6e60d27b6b761f54851fa65e33066460dfa6a0db.txt") c.Assert(transformed.Data(), qt.DeepEquals, map[string]any{"Integrity": "sha256-pa0caWEhSlXeU8HObmDSe2t2H1SFH6ZeMwZkYN+moNs="}) content, err := transformed.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "Hugo Rocks!") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/integrity/integrity.go
resources/resource_transformers/integrity/integrity.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package integrity import ( "crypto/md5" "crypto/sha256" "crypto/sha512" "encoding/base64" "encoding/hex" "fmt" "hash" "io" "github.com/gohugoio/hugo/common/constants" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) const defaultHashAlgo = "sha256" // Client contains methods to fingerprint (cachebusting) and other integrity-related // methods. type Client struct { rs *resources.Spec } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } type fingerprintTransformation struct { algo string } func (t *fingerprintTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey(constants.ResourceTransformationFingerprint, t.algo) } // Transform creates a MD5 hash of the Resource content and inserts that hash before // the extension in the filename. func (t *fingerprintTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { h, err := newHash(t.algo) if err != nil { return err } var w io.Writer if rc, ok := ctx.From.(io.ReadSeeker); ok { // This transformation does not change the content, so try to // avoid writing to To if we can. defer rc.Seek(0, 0) w = h } else { w = io.MultiWriter(h, ctx.To) } io.Copy(w, ctx.From) d, err := digest(h) if err != nil { return err } ctx.Data["Integrity"] = integrity(t.algo, d) ctx.AddOutPathIdentifier("." + hex.EncodeToString(d[:])) return nil } func newHash(algo string) (hash.Hash, error) { switch algo { case "md5": return md5.New(), nil case "sha256": return sha256.New(), nil case "sha384": return sha512.New384(), nil case "sha512": return sha512.New(), nil default: return nil, fmt.Errorf("unsupported hash algorithm: %q, use either md5, sha256, sha384 or sha512", algo) } } // Fingerprint applies fingerprinting of the given resource and hash algorithm. // It defaults to sha256 if none given, and the options are md5, sha256 or sha512. // The same algo is used for both the fingerprinting part (aka cache busting) and // the base64-encoded Subresource Integrity hash, so you will have to stay away from // md5 if you plan to use both. // See https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity func (c *Client) Fingerprint(res resources.ResourceTransformer, algo string) (resource.Resource, error) { if algo == "" { algo = defaultHashAlgo } return res.Transform(&fingerprintTransformation{algo: algo}) } func integrity(algo string, sum []byte) string { encoded := base64.StdEncoding.EncodeToString(sum) return algo + "-" + encoded } func digest(h hash.Hash) ([]byte, error) { sum := h.Sum(nil) return sum, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/dartsass/client.go
resources/resource_transformers/tocss/dartsass/client.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package dartsass integrates with the Dart Sass Embedded protocol to transpile // SCSS/SASS. package dartsass import ( "fmt" "io" "strings" "github.com/bep/godartsass/v2" "github.com/bep/logg" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/spf13/afero" "github.com/mitchellh/mapstructure" ) // used as part of the cache key. const transformationName = "tocss-dart" // See https://github.com/sass/dart-sass-embedded/issues/24 // Note: This prefix must be all lower case. const dartSassStdinPrefix = "hugostdin:" func New(fs *filesystems.SourceFilesystem, rs *resources.Spec) (*Client, error) { if !Supports() { return &Client{}, nil } if hugo.DartSassBinaryName == "" { return nil, fmt.Errorf("no Dart Sass binary found in $PATH") } if !hugo.IsDartSassGeV2() { return nil, fmt.Errorf("unsupported Dart Sass version detected, please upgrade to Dart Sass 1.63.0 or later, see https://gohugo.io/functions/css/sass/#dart-sass") } if err := rs.ExecHelper.Sec().CheckAllowedExec(hugo.DartSassBinaryName); err != nil { return nil, err } var ( transpiler *godartsass.Transpiler err error infol = rs.Logger.InfoCommand("Dart Sass") warnl = rs.Logger.WarnCommand("Dart Sass") ) transpiler, err = godartsass.Start(godartsass.Options{ DartSassEmbeddedFilename: hugo.DartSassBinaryName, LogEventHandler: func(event godartsass.LogEvent) { message := strings.ReplaceAll(event.Message, dartSassStdinPrefix, "") switch event.Type { case godartsass.LogEventTypeDebug: // Log as Info for now, we may adjust this if it gets too chatty. infol.Log(logg.String(message)) case godartsass.LogEventTypeDeprecated: warnl.Logf("DEPRECATED [%s]: %s", event.DeprecationType, message) default: // The rest are @warn statements. warnl.Log(logg.String(message)) } }, }) if err != nil { return nil, err } return &Client{sfs: fs, workFs: rs.BaseFs.Work, rs: rs, transpiler: transpiler}, nil } type Client struct { rs *resources.Spec sfs *filesystems.SourceFilesystem workFs afero.Fs // This may be nil if Dart Sass is not available. transpiler *godartsass.Transpiler } func (c *Client) ToCSS(res resources.ResourceTransformer, args map[string]any) (resource.Resource, error) { if c.transpiler == nil { return res.Transform(resources.NewFeatureNotAvailableTransformer(transformationName, args)) } return res.Transform(&transform{c: c, optsm: args}) } func (c *Client) Close() error { if c.transpiler == nil { return nil } return c.transpiler.Close() } func (c *Client) toCSS(args godartsass.Args, src io.Reader) (godartsass.Result, error) { in := helpers.ReaderToString(src) args.Source = in res, err := c.transpiler.Execute(args) if err != nil { if err.Error() == "unexpected EOF" { //lint:ignore ST1005 end user message. return res, fmt.Errorf("got unexpected EOF when executing %q. The user running hugo must have read and execute permissions on this program. With execute permissions only, this error is thrown.", hugo.DartSassBinaryName) } return res, herrors.NewFileErrorFromFileInErr(err, hugofs.Os, herrors.OffsetMatcher) } return res, err } type Options struct { // Hugo, will by default, just replace the extension of the source // to .css, e.g. "scss/main.scss" becomes "scss/main.css". You can // control this by setting this, e.g. "styles/main.css" will create // a Resource with that as a base for RelPermalink etc. TargetPath string // Hugo automatically adds the entry directories (where the main.scss lives) // for project and themes to the list of include paths sent to LibSASS. // Any paths set in this setting will be appended. Note that these will be // treated as relative to the working dir, i.e. no include paths outside the // project/themes. IncludePaths []string // Default is nested. // One of nested, expanded, compact, compressed. OutputStyle string // When enabled, Hugo will generate a source map. EnableSourceMap bool // If enabled, sources will be embedded in the generated source map. SourceMapIncludeSources bool // Vars will be available in 'hugo:vars', e.g: // @use "hugo:vars"; // $color: vars.$color; Vars map[string]any // Deprecations IDs in this slice will be silenced. // The IDs can be found in the Dart Sass log output, e.g. "import" in // WARN Dart Sass: DEPRECATED [import]. SilenceDeprecations []string // Whether to silence deprecation warnings from dependencies, where a // dependency is considered any file transitively imported through a load // path. This does not apply to @warn or @debug rules. SilenceDependencyDeprecations bool } func decodeOptions(m map[string]any) (opts Options, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) if opts.TargetPath != "" { opts.TargetPath = paths.ToSlashTrimLeading(opts.TargetPath) } return }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/dartsass/transform.go
resources/resource_transformers/tocss/dartsass/transform.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dartsass import ( "fmt" "io" "path" "path/filepath" "strings" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass" "github.com/spf13/afero" "github.com/gohugoio/hugo/hugofs" "github.com/bep/godartsass/v2" ) // Supports returns whether sass, dart-sass, or dart-sass-embedded is found in $PATH. func Supports() bool { if htesting.SupportsAll() { return true } return hugo.DartSassBinaryName != "" } type transform struct { optsm map[string]any c *Client } func (t *transform) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey(transformationName, t.optsm) } func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { ctx.OutMediaType = media.Builtin.CSSType opts, err := decodeOptions(t.optsm) if err != nil { return err } if opts.TargetPath != "" { ctx.OutPath = opts.TargetPath } else { ctx.ReplaceOutPathExtension(".css") } baseDir := path.Dir(ctx.SourcePath) filename := dartSassStdinPrefix if ctx.SourcePath != "" { filename += t.c.sfs.RealFilename(ctx.SourcePath) } args := godartsass.Args{ URL: filename, IncludePaths: t.c.sfs.RealDirs(baseDir), ImportResolver: importResolver{ baseDir: baseDir, c: t.c, dependencyManager: ctx.DependencyManager, varsStylesheet: godartsass.Import{Content: sass.CreateVarsStyleSheet(sass.TranspilerDart, opts.Vars)}, }, OutputStyle: godartsass.ParseOutputStyle(opts.OutputStyle), EnableSourceMap: opts.EnableSourceMap, SourceMapIncludeSources: opts.SourceMapIncludeSources, SilenceDeprecations: opts.SilenceDeprecations, SilenceDependencyDeprecations: opts.SilenceDependencyDeprecations, } // Append any workDir relative include paths for _, ip := range opts.IncludePaths { info, err := t.c.workFs.Stat(filepath.Clean(ip)) if err == nil { filename := info.(hugofs.FileMetaInfo).Meta().Filename args.IncludePaths = append(args.IncludePaths, filename) } } if ctx.InMediaType.SubType == media.Builtin.SASSType.SubType { args.SourceSyntax = godartsass.SourceSyntaxSASS } res, err := t.c.toCSS(args, ctx.From) if err != nil { return err } out := res.CSS _, err = io.WriteString(ctx.To, out) if err != nil { return err } if opts.EnableSourceMap && res.SourceMap != "" { if err := ctx.PublishSourceMap(res.SourceMap); err != nil { return err } _, err = fmt.Fprintf(ctx.To, "\n\n/*# sourceMappingURL=%s */", path.Base(ctx.OutPath)+".map") } return err } type importResolver struct { baseDir string c *Client dependencyManager identity.Manager varsStylesheet godartsass.Import } func (t importResolver) CanonicalizeURL(url string) (string, error) { if url == sass.HugoVarsNamespace { return url, nil } filePath, isURL := paths.UrlStringToFilename(url) var prevDir string var pathDir string if isURL { var found bool prevDir, found = t.c.sfs.MakePathRelative(filepath.Dir(filePath), true) if !found { // Not a member of this filesystem, let Dart Sass handle it. return "", nil } } else { prevDir = t.baseDir pathDir = path.Dir(url) } basePath := filepath.Join(prevDir, pathDir) name := filepath.Base(filePath) // Pick the first match. var namePatterns []string if strings.Contains(name, ".") { namePatterns = []string{"_%s", "%s"} } else if strings.HasPrefix(name, "_") { namePatterns = []string{"_%s.scss", "_%s.sass", "_%s.css"} } else { namePatterns = []string{ "_%s.scss", "%s.scss", "_%s.sass", "%s.sass", "_%s.css", "%s.css", "%s/_index.scss", "%s/_index.sass", "%s/index.scss", "%s/index.sass", } } name = strings.TrimPrefix(name, "_") for _, namePattern := range namePatterns { filenameToCheck := filepath.Join(basePath, fmt.Sprintf(namePattern, name)) fi, err := t.c.sfs.Fs.Stat(filenameToCheck) if err == nil { if fim, ok := fi.(hugofs.FileMetaInfo); ok { t.dependencyManager.AddIdentity(identity.CleanStringIdentity(filenameToCheck)) return "file://" + filepath.ToSlash(fim.Meta().Filename), nil } } } // Not found, let Dart Sass handle it return "", nil } func (t importResolver) Load(url string) (godartsass.Import, error) { if url == sass.HugoVarsNamespace { return t.varsStylesheet, nil } filename, _ := paths.UrlStringToFilename(url) b, err := afero.ReadFile(hugofs.Os, filename) sourceSyntax := godartsass.SourceSyntaxSCSS if strings.HasSuffix(filename, ".sass") { sourceSyntax = godartsass.SourceSyntaxSASS } else if strings.HasSuffix(filename, ".css") { sourceSyntax = godartsass.SourceSyntaxCSS } return godartsass.Import{Content: string(b), SourceSyntax: sourceSyntax}, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/dartsass/dartsass_integration_test.go
resources/resource_transformers/tocss/dartsass/dartsass_integration_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dartsass_test import ( "strings" "testing" "github.com/bep/logg" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" ) func TestTransformIncludePaths(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- hugo.toml -- -- layouts/home.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- hugo.toml -- -- layouts/home.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformImportIndentedSASS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.sass -- #main color: blue -- assets/scss/main.scss -- @import "moo"; /* foo */ -- hugo.toml -- -- layouts/home.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", "T1: #main {\n color: blue;\n}\n\n/* foo */") } // Issue 10592 func TestTransformImportMountedCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/main.scss -- @import "import-this-file.css"; @import "foo/import-this-mounted-file.css"; @import "compile-this-file"; @import "foo/compile-this-mounted-file"; a {color: main-scss;} -- assets/_compile-this-file.css -- a {color: compile-this-file-css;} -- assets/_import-this-file.css -- a {color: import-this-file-css;} -- foo/_compile-this-mounted-file.css -- a {color: compile-this-mounted-file-css;} -- foo/_import-this-mounted-file.css -- a {color: import-this-mounted-file-css;} -- layouts/home.html -- {{- $opts := dict "transpiler" "dartsass" }} {{- with resources.Get "main.scss" | toCSS $opts }}{{ .Content | safeHTML }}{{ end }} -- hugo.toml -- disableKinds = ['RSS','sitemap','taxonomy','term','page','section'] [[module.mounts]] source = 'assets' target = 'assets' [[module.mounts]] source = 'foo' target = 'assets/foo' ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", ` @import "import-this-file.css"; @import "foo/import-this-mounted-file.css"; a { color: compile-this-file-css; } a { color: compile-this-mounted-file-css; } a { color: main-scss; } `) } func TestTransformThemeOverrides(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- hugo.toml -- theme = 'mytheme' -- layouts/home.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- hugo.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/home.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: logg.LevelInfo, }).Build() b.AssertLogMatches(`Dart Sass: foo`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- hugo.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/home.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fileErrs := herrors.UnwrapFileErrors(err) b.Assert(len(fileErrs), qt.Equals, 2) // template + scss. templErr := fileErrs[0] b.Assert(templErr.ErrorContext(), qt.IsNotNil) b.Assert(templErr.ErrorContext().Lines, qt.DeepEquals, []string{"{{ $cssOpts := dict \"transpiler\" \"dartsass\" }}", "{{ $r := resources.Get \"scss/main.scss\" | toCSS $cssOpts | minify }}", "T1: {{ $r.Content }}", "", "\t"}) b.Assert(templErr.ErrorContext().ChromaLexer, qt.Equals, "go-html-template") scssErr := fileErrs[1] b.Assert(scssErr.ErrorContext(), qt.IsNotNil) b.Assert(scssErr.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(scssErr.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fileErrs := herrors.UnwrapFileErrors(err) b.Assert(len(fileErrs), qt.Equals, 2) // template + scss. scssErr := fileErrs[1] b.Assert(scssErr.ErrorContext(), qt.IsNotNil) b.Assert(scssErr.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(scssErr.ErrorContext().ChromaLexer, qt.Equals, "scss") }) } func TestOptionVars(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; font-family: vars.$font; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/home.html -- {{ $image := "images/hero.jpg" }} {{ $font := "Hugo's New Roman" }} {{ $vars := dict "$color1" "blue" "$color2" "green" "font_size" "24px" "image" $image "font" $font }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover;font-family:Hugo&#39;s New Roman}p{color:blue;font-size:24px}b{color:green}`) } func TestOptionVarsParams(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- hugo.toml -- [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/home.html -- {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) } func TestVarsCasting(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- hugo.toml -- disableKinds = ["term", "taxonomy", "section", "page"] [params] [params.sassvars] color_hex = "#fff" color_rgb = "rgb(255, 255, 255)" color_hsl = "hsl(0, 0%, 100%)" dimension = "24px" percentage = "10%" flex = "5fr" name = "Hugo" url = "https://gohugo.io" integer = 32 float = 3.14 -- assets/scss/main.scss -- @use "hugo:vars"; @use "sass:meta"; @debug meta.type-of(vars.$color_hex); @debug meta.type-of(vars.$color_rgb); @debug meta.type-of(vars.$color_hsl); @debug meta.type-of(vars.$dimension); @debug meta.type-of(vars.$percentage); @debug meta.type-of(vars.$flex); @debug meta.type-of(vars.$name); @debug meta.type-of(vars.$url); @debug meta.type-of(vars.$not_a_number); @debug meta.type-of(vars.$integer); @debug meta.type-of(vars.$float); @debug meta.type-of(vars.$a_number); -- layouts/home.html -- {{ $vars := site.Params.sassvars}} {{ $vars = merge $vars (dict "not_a_number" ("32xxx" | css.Quoted) "a_number" ("234" | css.Unquoted) )}} {{ $cssOpts := (dict "transpiler" "dartsass" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: logg.LevelInfo, }).Build() b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:3:0: color`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:4:0: color`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:5:0: color`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:6:0: number`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:7:0: number`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:8:0: number`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:9:0: string`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:10:0: string`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:11:0: string`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:12:0: number`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:13:0: number`) b.AssertLogMatches(`Dart Sass: .*assets.*main.scss:14:0: number`) } // Note: This test is more or less duplicated in both of the SCSS packages (libsass and dartsass). func TestBootstrap(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } if !htesting.IsCI() { t.Skip("skip (slow) test in non-CI environment") } files := ` -- hugo.toml -- disableKinds = ["term", "taxonomy", "section", "page"] [module] [[module.imports]] path="github.com/gohugoio/hugo-mod-bootstrap-scss/v5" -- go.mod -- module github.com/gohugoio/tests/testHugoModules -- assets/scss/main.scss -- @import "bootstrap/bootstrap"; -- layouts/home.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} Styles: {{ $r.RelPermalink }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", "Styles: /scss/main.css") } // Issue 12849 func TestDirectoryIndexes(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- hugo.toml -- disableKinds = ['page','section','rss','sitemap','taxonomy','term'] [[module.mounts]] source = 'assets' target = 'assets' [[module.mounts]] source = "miscellaneous/sass" target = "assets/sass" -- layouts/home.html -- {{ $opts := dict "transpiler" "dartsass" "outputStyle" "compressed" }} {{ (resources.Get "sass/main.scss" | toCSS $opts).Content }} -- assets/sass/main.scss -- @use "foo1"; // directory with _index file from OS file system @use "bar1"; // directory with _index file from module mount @use "foo2"; // directory with index file from OS file system @use "bar2"; // directory with index file from module mount -- assets/sass/foo1/_index.scss -- .foo1 {color: red;} -- miscellaneous/sass/bar1/_index.scss -- .bar1 {color: blue;} -- assets/sass/foo2/index.scss -- .foo2 {color: red;} -- miscellaneous/sass/bar2/index.scss -- .bar2 {color: blue;} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, NeedsOsFS: true, TxtarString: files, }).Build() b.AssertFileContent("public/index.html", ".foo1{color:red}.bar1{color:blue}.foo2{color:red}.bar2{color:blue}") } func TestIgnoreDeprecationWarnings(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- hugo.toml -- disableKinds = ['page','section','rss','sitemap','taxonomy','term'] -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- hugo.toml -- -- layouts/home.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.Test(t, files, hugolib.TestOptOsFs(), hugolib.TestOptWarn()) b.AssertLogContains("Dart Sass: DEPRECATED [import]") b.AssertFileContent("public/index.html", `moo{color:#fff}`) files = strings.ReplaceAll(files, `"transpiler" "dartsass"`, `"transpiler" "dartsass" "silenceDeprecations" (slice "import")`) b = hugolib.Test(t, files, hugolib.TestOptOsFs(), hugolib.TestOptWarn()) b.AssertLogContains("! Dart Sass: DEPRECATED [import]") b.AssertFileContent("public/index.html", `moo{color:#fff}`) } func TestSilenceDependencyDeprecations(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ $opts := dict "transpiler" "dartsass" "outputStyle" "compressed" "includePaths" (slice "node_modules") KVPAIR }} {{ (resources.Get "sass/main.scss" | css.Sass $opts).Content }} -- assets/sass/main.scss -- @use "sass:color"; @use "foo/deprecated.scss"; h3 { color: rgb(color.channel(#ccc, "red", $space: rgb), 0, 0); } // COMMENT -- node_modules/foo/deprecated.scss -- @use "sass:color"; h1 { color: rgb(color.channel(#eee, "red", $space: rgb), 0, 0); } h2 { color: rgb(color.red(#ddd), 0, 0); } // deprecated ` expectedCSS := "h1{color:#e00}h2{color:#d00}h3{color:#c00}" // Do not silence dependency deprecation warnings (default). f := strings.ReplaceAll(files, "KVPAIR", "") b := hugolib.Test(t, f, hugolib.TestOptWarn(), hugolib.TestOptOsFs()) b.AssertFileContent("public/index.html", expectedCSS) b.AssertLogContains( "WARN Dart Sass: DEPRECATED [color-functions]", "color.red() is deprecated", ) // Do not silence dependency deprecation warnings (explicit). f = strings.ReplaceAll(files, "KVPAIR", `"silenceDependencyDeprecations" false`) b = hugolib.Test(t, f, hugolib.TestOptWarn(), hugolib.TestOptOsFs()) b.AssertFileContent("public/index.html", expectedCSS) b.AssertLogContains( "WARN Dart Sass: DEPRECATED [color-functions]", "color.red() is deprecated", ) // Silence dependency deprecation warnings. f = strings.ReplaceAll(files, "KVPAIR", `"silenceDependencyDeprecations" true`) b = hugolib.Test(t, f, hugolib.TestOptWarn(), hugolib.TestOptOsFs()) b.AssertFileContent("public/index.html", expectedCSS) b.AssertLogContains("! WARN") // Make sure that we are not silencing non-dependency deprecation warnings. f = strings.ReplaceAll(files, "KVPAIR", `"silenceDependencyDeprecations" true`) f = strings.ReplaceAll(f, "// COMMENT", "h4 { color: rgb(0, color.green(#bbb), 0); }") b = hugolib.Test(t, f, hugolib.TestOptWarn(), hugolib.TestOptOsFs()) b.AssertFileContent("public/index.html", expectedCSS+"h4{color:#0b0}") b.AssertLogContains( "WARN Dart Sass: DEPRECATED [color-functions]", "color.green() is deprecated", ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/scss/client_notavailable.go
resources/resource_transformers/tocss/scss/client_notavailable.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !extended package scss import ( "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) func (c *Client) ToCSS(res resources.ResourceTransformer, opts Options) (resource.Resource, error) { return res.Transform(resources.NewFeatureNotAvailableTransformer(transformationName, opts)) } // Used in tests. func Supports() bool { return false }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/scss/client.go
resources/resource_transformers/tocss/scss/client.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package scss import ( "regexp" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/resources" "github.com/spf13/afero" "github.com/mitchellh/mapstructure" ) const transformationName = "tocss" type Client struct { rs *resources.Spec sfs *filesystems.SourceFilesystem workFs afero.Fs } func New(fs *filesystems.SourceFilesystem, rs *resources.Spec) (*Client, error) { return &Client{sfs: fs, workFs: rs.BaseFs.Work, rs: rs}, nil } type Options struct { // Hugo, will by default, just replace the extension of the source // to .css, e.g. "scss/main.scss" becomes "scss/main.css". You can // control this by setting this, e.g. "styles/main.css" will create // a Resource with that as a base for RelPermalink etc. TargetPath string // Hugo automatically adds the entry directories (where the main.scss lives) // for project and themes to the list of include paths sent to LibSASS. // Any paths set in this setting will be appended. Note that these will be // treated as relative to the working dir, i.e. no include paths outside the // project/themes. IncludePaths []string // Default is nested. // One of nested, expanded, compact, compressed. OutputStyle string // Precision of floating point math. Precision int // When enabled, Hugo will generate a source map. EnableSourceMap bool // Vars will be available in 'hugo:vars', e.g: // @import "hugo:vars"; Vars map[string]any } func DecodeOptions(m map[string]any) (opts Options, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) if opts.TargetPath != "" { opts.TargetPath = paths.ToSlashTrimLeading(opts.TargetPath) } return } var ( regularCSSImportTo = regexp.MustCompile(`.*(@import "(.*\.css)";).*`) regularCSSImportFrom = regexp.MustCompile(`.*(\/\* HUGO_IMPORT_START (.*) HUGO_IMPORT_END \*\/).*`) ) func replaceRegularImportsIn(s string) (string, bool) { replaced := regularCSSImportTo.ReplaceAllString(s, "/* HUGO_IMPORT_START $2 HUGO_IMPORT_END */") return replaced, s != replaced } func replaceRegularImportsOut(s string) string { return regularCSSImportFrom.ReplaceAllString(s, "@import \"$2\";") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/scss/scss_integration_test.go
resources/resource_transformers/tocss/scss/scss_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package scss_test import ( "path/filepath" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestTransformIncludePaths(t *testing.T) { t.Parallel() if !scss.Supports() { t.Skip() } c := qt.New(t) files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- hugo.toml -- -- layouts/home.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !scss.Supports() { t.Skip() } c := qt.New(t) files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- hugo.toml -- -- layouts/home.html -- {{ $r := resources.Get "scss/main.scss" | toCSS }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: files, NeedsOsFS: true, }).Build() // LibSass does not support regular CSS imports. There // is an open bug about it that probably will never be resolved. // Hugo works around this by preserving them in place: b.AssertFileContent("public/index.html", ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } func TestTransformThemeOverrides(t *testing.T) { t.Parallel() if !scss.Supports() { t.Skip() } c := qt.New(t) files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- hugo.toml -- theme = 'mytheme' -- layouts/home.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformErrors(t *testing.T) { t.Parallel() if !scss.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- hugo.toml -- theme = 'mytheme' -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- themes/mytheme/assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/home.html -- {{ $cssOpts := dict }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`themes/mytheme/assets/scss/main.scss:6:1": expected ':' after $maincolor in assignment statement`)) ferrs := herrors.UnwrapFileErrors(err) c.Assert(len(ferrs), qt.Equals, 2) fe := ferrs[1] b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 4 */", "", "$maincolor #eee;", "", "body {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `assets/scss/components/_foo.scss:2:1": expected ':' after $foocolor in assignment statement`) ferrs := herrors.UnwrapFileErrors(err) c.Assert(len(ferrs), qt.Equals, 2) fe := ferrs[1] b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) } func TestOptionVars(t *testing.T) { t.Parallel() if !scss.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "hugo:vars"; body { body { background: url($image) no-repeat center/cover; font-family: $font; } } p { color: $color1; font-size: var$font_size; } b { color: $color2; } -- layouts/home.html -- {{ $image := "images/hero.jpg" }} {{ $font := "Hugo's New Roman" }} {{ $vars := dict "$color1" "blue" "$color2" "green" "font_size" "24px" "image" $image "font" $font }} {{ $cssOpts := (dict "transpiler" "libsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover;font-family:Hugo&#39;s New Roman}p{color:blue;font-size:var 24px}b{color:green}`) } // Note: This test is more or less duplicated in both of the SCSS packages (libsass and dartsass). func TestBootstrap(t *testing.T) { t.Parallel() if !scss.Supports() { t.Skip() } if !htesting.IsCI() { t.Skip("skip (slow) test in non-CI environment") } files := ` -- hugo.toml -- disableKinds = ["term", "taxonomy", "section", "page"] [module] [[module.imports]] path="github.com/gohugoio/hugo-mod-bootstrap-scss/v5" -- go.mod -- module github.com/gohugoio/tests/testHugoModules -- assets/scss/main.scss -- @import "bootstrap/bootstrap"; -- layouts/home.html -- {{ $cssOpts := (dict "transpiler" "libsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} Styles: {{ $r.RelPermalink }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", "Styles: /scss/main.css") } // Issue #1239. func TestRebuildAssetGetMatch(t *testing.T) { t.Parallel() if !scss.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- b { color: red; } -- layouts/home.html -- {{ $r := resources.GetMatch "scss/main.scss" | toCSS }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, Running: true, }).Build() b.AssertFileContent("public/index.html", `color: red`) b.EditFiles("assets/scss/main.scss", `b { color: blue; }`).Build() b.AssertFileContent("public/index.html", `color: blue`) } func TestRebuildAssetMatchIssue12456(t *testing.T) { t.Parallel() if !scss.Supports() { t.Skip() } files := ` -- hugo.toml -- disableKinds = ["term", "taxonomy", "section", "page"] disableLiveReload = true -- assets/a.scss -- h1 { color: red; } -- assets/dir/b.scss -- h2 { color: blue; } -- assets/dir/c.scss -- h3 { color: green; } -- layouts/home.html -- {{ $a := slice (resources.Get "a.scss") }} {{ $b := resources.Match "dir/*.scss" }} {{/* Add styles in a specific order. */}} {{ $styles := slice $a $b }} {{ $stylesheets := slice }} {{ range $styles }} {{ $stylesheets = $stylesheets | collections.Append . }} {{ end }} {{ range $stylesheets }} {{ with . | css.Sass | fingerprint }} <link as="style" href="{{ .RelPermalink }}" rel="preload stylesheet"> {{ end }} {{ end }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, Running: true, // LogLevel: logg.LevelTrace, }).Build() b.AssertFileContent("public/index.html", `b.60a9f3bdc189ee8a857afd5b7e1b93ad1644de0873761a7c9bc84f781a821942.css`) b.EditFiles("assets/dir/b.scss", `h2 { color: orange; }`).Build() b.AssertFileContent("public/index.html", `b.46b2d77c7ffe37ee191678f72df991ecb1319f849957151654362f09b0ef467f.css`) } // Issue 12851 func TestDirectoryIndexes(t *testing.T) { t.Parallel() if !scss.Supports() { t.Skip() } files := ` -- hugo.toml -- disableKinds = ['page','section','rss','sitemap','taxonomy','term'] [[module.mounts]] source = 'assets' target = 'assets' [[module.mounts]] source = "miscellaneous/sass" target = "assets/sass" -- layouts/home.html -- {{ $opts := dict "transpiler" "libsass" "outputStyle" "compressed" }} {{ (resources.Get "sass/main.scss" | toCSS $opts).Content }} -- assets/sass/main.scss -- @import "foo1"; // directory with _index file from OS file system @import "bar1"; // directory with _index file from module mount @import "foo2"; // directory with index file from OS file system @import "bar2"; // directory with index file from module mount -- assets/sass/foo1/_index.scss -- .foo1 {color: red;} -- miscellaneous/sass/bar1/_index.scss -- .bar1 {color: blue;} -- assets/sass/foo2/index.scss -- .foo2 {color: red;} -- miscellaneous/sass/bar2/index.scss -- .bar2 {color: blue;} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, NeedsOsFS: true, TxtarString: files, }).Build() b.AssertFileContent("public/index.html", ".foo1{color:red}.bar1{color:blue}.foo2{color:red}.bar2{color:blue}") } func TestLibsassDeprecatedIssue14261(t *testing.T) { // This cannot be run in parallel because of global state in log deprecation handling. if !scss.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- body { background-color: #fff; } -- hugo.toml -- -- layouts/home.html -- {{ $cssOpts := (dict "transpiler" "libsass") }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} {{ $r.RelPermalink }} ` b := hugolib.Test(t, files, hugolib.TestOptOsFs(), hugolib.TestOptInfo()) b.AssertLogContains("deprecated: css.Sass: libsass was deprecated in Hugo v0.153.0") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/scss/client_test.go
resources/resource_transformers/tocss/scss/client_test.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package scss import ( "testing" qt "github.com/frankban/quicktest" ) func TestReplaceRegularCSSImports(t *testing.T) { c := qt.New(t) scssWithImport := ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; @import "foo.scss"; /* foo */` scssWithoutImport := ` @import "moo"; /* foo */` res, replaced := replaceRegularImportsIn(scssWithImport) c.Assert(replaced, qt.Equals, true) c.Assert(res, qt.Equals, "\n\t\n@import \"moo\";\n/* HUGO_IMPORT_START regular.css HUGO_IMPORT_END */\n@import \"moo\";\n/* HUGO_IMPORT_START another.css HUGO_IMPORT_END */\n@import \"foo.scss\";\n\n/* foo */") res2, replaced2 := replaceRegularImportsIn(scssWithoutImport) c.Assert(replaced2, qt.Equals, false) c.Assert(res2, qt.Equals, scssWithoutImport) reverted := replaceRegularImportsOut(res) c.Assert(reverted, qt.Equals, scssWithImport) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/scss/tocss.go
resources/resource_transformers/tocss/scss/tocss.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build extended package scss import ( "fmt" "io" "path" "path/filepath" "strings" "github.com/bep/golibsass/libsass" "github.com/bep/golibsass/libsass/libsasserrors" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass" ) // Used in tests. This feature requires Hugo to be built with the extended tag. func Supports() bool { return true } func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { ctx.OutMediaType = media.Builtin.CSSType var outName string if t.options.from.TargetPath != "" { ctx.OutPath = t.options.from.TargetPath } else { ctx.ReplaceOutPathExtension(".css") } outName = path.Base(ctx.OutPath) options := t.options baseDir := path.Dir(ctx.SourcePath) options.to.IncludePaths = t.c.sfs.RealDirs(baseDir) // Append any workDir relative include paths for _, ip := range options.from.IncludePaths { info, err := t.c.workFs.Stat(filepath.Clean(ip)) if err == nil { filename := info.(hugofs.FileMetaInfo).Meta().Filename options.to.IncludePaths = append(options.to.IncludePaths, filename) } } varsStylesheet := sass.CreateVarsStyleSheet(sass.TranspilerLibSass, options.from.Vars) // To allow for overrides of SCSS files anywhere in the project/theme hierarchy, we need // to help libsass revolve the filename by looking in the composite filesystem first. // We add the entry directories for both project and themes to the include paths list, but // that only work for overrides on the top level. options.to.ImportResolver = func(url string, prev string) (newUrl string, body string, resolved bool) { if url == sass.HugoVarsNamespace { return url, varsStylesheet, true } // We get URL paths from LibSASS, but we need file paths. url = filepath.FromSlash(url) prev = filepath.FromSlash(prev) var basePath string urlDir := filepath.Dir(url) var prevDir string if prev == "stdin" { prevDir = baseDir } else { prevDir, _ = t.c.sfs.MakePathRelative(filepath.Dir(prev), true) if prevDir == "" { // Not a member of this filesystem. Let LibSASS handle it. return "", "", false } } basePath = filepath.Join(prevDir, urlDir) name := filepath.Base(url) // Libsass throws an error in cases where you have several possible candidates. // We make this simpler and pick the first match. var namePatterns []string if strings.Contains(name, ".") { namePatterns = []string{"_%s", "%s"} } else if strings.HasPrefix(name, "_") { namePatterns = []string{"_%s.scss", "_%s.sass"} } else { namePatterns = []string{ "_%s.scss", "%s.scss", "_%s.sass", "%s.sass", "%s/_index.scss", "%s/_index.sass", "%s/index.scss", "%s/index.sass", } } name = strings.TrimPrefix(name, "_") for _, namePattern := range namePatterns { filenameToCheck := filepath.Join(basePath, fmt.Sprintf(namePattern, name)) fi, err := t.c.sfs.Fs.Stat(filenameToCheck) if err == nil { if fim, ok := fi.(hugofs.FileMetaInfo); ok { ctx.DependencyManager.AddIdentity(identity.CleanStringIdentity(filenameToCheck)) return fim.Meta().Filename, "", true } } } // Not found, let LibSASS handle it return "", "", false } if ctx.InMediaType.SubType == media.Builtin.SASSType.SubType { options.to.SassSyntax = true } if options.from.EnableSourceMap { options.to.SourceMapOptions.Filename = outName + ".map" options.to.SourceMapOptions.Root = t.c.rs.Cfg.BaseConfig().WorkingDir // Setting this to the relative input filename will get the source map // more correct for the main entry path (main.scss typically), but // it will mess up the import mappings. As a workaround, we do a replacement // in the source map itself (see below). // options.InputPath = inputPath options.to.SourceMapOptions.OutputPath = outName options.to.SourceMapOptions.Contents = true options.to.SourceMapOptions.OmitURL = false options.to.SourceMapOptions.EnableEmbedded = false } res, err := t.c.toCSS(options.to, ctx.To, ctx.From) if err != nil { if sasserr, ok := err.(libsasserrors.Error); ok { if sasserr.File == "stdin" && ctx.SourcePath != "" { sasserr.File = t.c.sfs.RealFilename(ctx.SourcePath) err = sasserr } } return herrors.NewFileErrorFromFileInErr(err, hugofs.Os, nil) } if options.from.EnableSourceMap && res.SourceMapContent != "" { sourcePath := t.c.sfs.RealFilename(ctx.SourcePath) if strings.HasPrefix(sourcePath, t.c.rs.Cfg.BaseConfig().WorkingDir) { sourcePath = strings.TrimPrefix(sourcePath, t.c.rs.Cfg.BaseConfig().WorkingDir+helpers.FilePathSeparator) } // This needs to be Unix-style slashes, even on Windows. // See https://github.com/gohugoio/hugo/issues/4968 sourcePath = filepath.ToSlash(sourcePath) // This is a workaround for what looks like a bug in Libsass. But // getting this resolution correct in tools like Chrome Workspaces // is important enough to go this extra mile. mapContent := strings.Replace(res.SourceMapContent, `stdin"`, fmt.Sprintf("%s\"", sourcePath), 1) return ctx.PublishSourceMap(mapContent) } return nil } func (c *Client) toCSS(options libsass.Options, dst io.Writer, src io.Reader) (libsass.Result, error) { var res libsass.Result transpiler, err := libsass.New(options) if err != nil { return res, err } in := helpers.ReaderToString(src) // See https://github.com/gohugoio/hugo/issues/7059 // We need to preserve the regular CSS imports. This is by far // a perfect solution, and only works for the main entry file, but // that should cover many use cases, e.g. using SCSS as a preprocessor // for Tailwind. var importsReplaced bool in, importsReplaced = replaceRegularImportsIn(in) res, err = transpiler.Execute(in) if err != nil { return res, err } out := res.CSS if importsReplaced { out = replaceRegularImportsOut(out) } _, err = io.WriteString(dst, out) return res, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/scss/client_extended.go
resources/resource_transformers/tocss/scss/client_extended.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build extended package scss import ( "github.com/bep/golibsass/libsass" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource" ) type options struct { // The options we receive from the end user. from Options // The options we send to the SCSS library. to libsass.Options } func (c *Client) ToCSS(res resources.ResourceTransformer, opts Options) (resource.Resource, error) { internalOptions := options{ from: opts, } // Transfer values from client. internalOptions.to.Precision = opts.Precision internalOptions.to.OutputStyle = libsass.ParseOutputStyle(opts.OutputStyle) if internalOptions.to.Precision == 0 { // bootstrap-sass requires 8 digits precision. The libsass default is 5. // https://github.com/twbs/bootstrap-sass/blob/master/README.md#sass-number-precision internalOptions.to.Precision = 8 } return res.Transform(&toCSSTransformation{c: c, options: internalOptions}) } type toCSSTransformation struct { c *Client options options } func (t *toCSSTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey(transformationName, t.options.from) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/sass/helpers_test.go
resources/resource_transformers/tocss/sass/helpers_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sass import ( "testing" qt "github.com/frankban/quicktest" ) func TestIsUnquotedCSSValue(t *testing.T) { c := qt.New(t) for _, test := range []struct { in any out bool }{ {"24px", true}, {"1.5rem", true}, {"10%", true}, {"hsl(0, 0%, 100%)", true}, {"calc(24px + 36px)", true}, {"24xxx", true}, // a false positive. {123, true}, {123.12, true}, {"#fff", true}, {"#ffffff", true}, {"#ffffffff", false}, } { c.Assert(isTypedCSSValue(test.in), qt.Equals, test.out) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/tocss/sass/helpers.go
resources/resource_transformers/tocss/sass/helpers.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sass import ( "fmt" "regexp" "sort" "strings" "github.com/gohugoio/hugo/common/types/css" ) const ( HugoVarsNamespace = "hugo:vars" // Transpiler implementation can be controlled from the client by // setting the 'transpiler' option. // Default is currently 'libsass', but that may change. TranspilerDart = "dartsass" TranspilerLibSass = "libsass" ) func CreateVarsStyleSheet(transpiler string, vars map[string]any) string { if vars == nil { return "" } var varsStylesheet string var varsSlice []string for k, v := range vars { var prefix string if !strings.HasPrefix(k, "$") { prefix = "$" } switch v.(type) { case css.QuotedString: // Marked by the user as a string that needs to be quoted. varsSlice = append(varsSlice, fmt.Sprintf("%s%s: %q;", prefix, k, v)) default: if isTypedCSSValue(v) { // E.g. 24px, 1.5rem, 10%, hsl(0, 0%, 100%), calc(24px + 36px), #fff, #ffffff. varsSlice = append(varsSlice, fmt.Sprintf("%s%s: %v;", prefix, k, v)) } else { // unquote will preserve quotes around URLs etc. if needed. if transpiler == TranspilerDart { varsSlice = append(varsSlice, fmt.Sprintf("%s%s: string.unquote(%q);", prefix, k, v)) } else { varsSlice = append(varsSlice, fmt.Sprintf("%s%s: unquote(%q);", prefix, k, v)) } } } } sort.Strings(varsSlice) if transpiler == TranspilerDart { varsStylesheet = `@use "sass:string";` + "\n" + strings.Join(varsSlice, "\n") } else { varsStylesheet = strings.Join(varsSlice, "\n") } return varsStylesheet } var ( isCSSColor = regexp.MustCompile(`^#[0-9a-fA-F]{3,6}$`) isCSSFunc = regexp.MustCompile(`^([a-zA-Z-]+)\(`) isCSSUnit = regexp.MustCompile(`^([0-9]+)(\.[0-9]+)?([a-zA-Z-%]+)$`) ) // isTypedCSSValue returns true if the given string is a CSS value that // we should preserve the type of, as in: Not wrap it in quotes. func isTypedCSSValue(v any) bool { switch s := v.(type) { case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, css.UnquotedString: return true case string: if isCSSColor.MatchString(s) { return true } if isCSSFunc.MatchString(s) { return true } if isCSSUnit.MatchString(s) { return true } } return false }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/js/js_integration_test.go
resources/resource_transformers/js/js_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package js_test import ( "os" "path/filepath" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/internal/js/esbuild" ) func TestBuildVariants(t *testing.T) { c := qt.New(t) mainWithImport := ` -- hugo.toml -- disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"] disableLiveReload = true -- assets/js/main.js -- import { hello1, hello2 } from './util1'; hello1(); hello2(); -- assets/js/util1.js -- import { hello3 } from './util2'; export function hello1() { return 'abcd'; } export function hello2() { return hello3(); } -- assets/js/util2.js -- export function hello3() { return 'efgh'; } -- layouts/home.html -- {{ $js := resources.Get "js/main.js" | js.Build }} JS Content:{{ $js.Content }}:End: ` c.Run("Basic", func(c *qt.C) { b := hugolib.NewIntegrationTestBuilder(hugolib.IntegrationTestConfig{T: c, NeedsOsFS: true, TxtarString: mainWithImport}).Build() b.AssertFileContent("public/index.html", `abcd`) }) c.Run("Edit Import", func(c *qt.C) { b := hugolib.NewIntegrationTestBuilder(hugolib.IntegrationTestConfig{T: c, Running: true, NeedsOsFS: true, TxtarString: mainWithImport}).Build() b.AssertFileContent("public/index.html", `abcd`) b.EditFileReplaceFunc("assets/js/util1.js", func(s string) string { return strings.ReplaceAll(s, "abcd", "1234") }).Build() b.AssertFileContent("public/index.html", `1234`) }) c.Run("Edit Import Nested", func(c *qt.C) { b := hugolib.NewIntegrationTestBuilder(hugolib.IntegrationTestConfig{T: c, Running: true, NeedsOsFS: true, TxtarString: mainWithImport}).Build() b.AssertFileContent("public/index.html", `efgh`) b.EditFileReplaceFunc("assets/js/util2.js", func(s string) string { return strings.ReplaceAll(s, "efgh", "1234") }).Build() b.AssertFileContent("public/index.html", `1234`) }) } func TestBuildWithModAndNpm(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } c := qt.New(t) files := ` -- hugo.toml -- baseURL = "https://example.org" disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"] [module] [[module.imports]] path="github.com/gohugoio/hugoTestProjectJSModImports" -- go.mod -- module github.com/gohugoio/tests/testHugoModules go 1.16 require github.com/gohugoio/hugoTestProjectJSModImports v0.10.0 // indirect -- package.json -- { "dependencies": { "date-fns": "^2.16.1" } } ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, NeedsOsFS: true, NeedsNpmInstall: true, TxtarString: files, Verbose: true, }).Build() b.AssertFileContent("public/js/main.js", ` greeting: "greeting configured in mod2" Hello1 from mod1: $ return "Hello2 from mod1"; var Hugo = "Rocks!"; Hello3 from mod2. Date from date-fns: ${today} Hello from lib in the main project Hello5 from mod2. var myparam = "Hugo Rocks!"; shim cwd `) // React JSX, verify the shimming. b.AssertFileContent("public/js/like.js", filepath.FromSlash(`@v0.10.0/assets/js/shims/react.js module.exports = window.ReactDOM; `)) } func TestBuildWithNpm(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } c := qt.New(t) files := ` -- assets/js/included.js -- console.log("included"); -- assets/js/main.js -- import "./included"; import { toCamelCase } from "to-camel-case"; console.log("main"); console.log("To camel:", toCamelCase("space case")); -- assets/js/myjsx.jsx -- import * as React from 'react' import * as ReactDOM from 'react-dom' ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('root') ); -- assets/js/myts.ts -- function greeter(person: string) { return "Hello, " + person; } let user = [0, 1, 2]; document.body.textContent = greeter(user); -- hugo.toml -- disablekinds = ['taxonomy', 'term', 'page'] -- content/p1.md -- Content. -- data/hugo.toml -- slogan = "Hugo Rocks!" -- i18n/en.yaml -- hello: other: "Hello" -- i18n/fr.yaml -- hello: other: "Bonjour" -- layouts/home.html -- {{ $options := dict "minify" false "externals" (slice "react" "react-dom") "sourcemap" "linked" }} {{ $js := resources.Get "js/main.js" | js.Build $options }} JS: {{ template "print" $js }} {{ $jsx := resources.Get "js/myjsx.jsx" | js.Build $options }} JSX: {{ template "print" $jsx }} {{ $ts := resources.Get "js/myts.ts" | js.Build (dict "sourcemap" "inline")}} TS: {{ template "print" $ts }} {{ $ts2 := resources.Get "js/myts.ts" | js.Build (dict "sourcemap" "external" "TargetPath" "js/myts2.js")}} TS2: {{ template "print" $ts2 }} {{ define "print" }}RelPermalink: {{.RelPermalink}}|MIME: {{ .MediaType }}|Content: {{ .Content | safeJS }}{{ end }} -- package.json -- { "scripts": {}, "dependencies": { "to-camel-case": "1.0.0" } } ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, NeedsOsFS: true, NeedsNpmInstall: true, TxtarString: files, }).Build() b.AssertFileContent("public/js/main.js", `//# sourceMappingURL=main.js.map`) b.AssertFileContent("public/js/main.js.map", `"version":3`, "! ns-hugo") // linked b.AssertFileContent("public/js/myts.js", `//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJz`) // inline b.AssertFileContent("public/index.html", ` console.log(&#34;included&#34;); if (hasSpace.test(string)) var React = __toESM(__require(&#34;react&#34;)); function greeter(person) { `) checkMap := func(p string, expectLen int) { s := b.FileContent(p) sources := esbuild.SourcesFromSourceMap(s) b.Assert(sources, qt.HasLen, expectLen) // Check that all source files exist. for _, src := range sources { filename, ok := paths.UrlStringToFilename(src) b.Assert(ok, qt.IsTrue) _, err := os.Stat(filename) b.Assert(err, qt.IsNil, qt.Commentf("src: %q", src)) } } checkMap("public/js/main.js.map", 4) } func TestBuildError(t *testing.T) { c := qt.New(t) filesTemplate := ` -- hugo.toml -- disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"] -- assets/js/main.js -- // A comment. import { hello1, hello2 } from './util1'; hello1(); hello2(); -- assets/js/util1.js -- /* Some comments. */ import { hello3 } from './util2'; export function hello1() { return 'abcd'; } export function hello2() { return hello3(); } -- assets/js/util2.js -- export function hello3() { return 'efgh'; } -- layouts/home.html -- {{ $js := resources.Get "js/main.js" | js.Build }} JS Content:{{ $js.Content }}:End: ` c.Run("Import from main not found", func(c *qt.C) { c.Parallel() files := strings.Replace(filesTemplate, "import { hello1, hello2 }", "import { hello1, hello2, FOOBAR }", 1) b, err := hugolib.NewIntegrationTestBuilder(hugolib.IntegrationTestConfig{T: c, NeedsOsFS: true, TxtarString: files}).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.js:2:25": No matching export`) }) c.Run("Import from import not found", func(c *qt.C) { c.Parallel() files := strings.Replace(filesTemplate, "import { hello3 } from './util2';", "import { hello3, FOOBAR } from './util2';", 1) b, err := hugolib.NewIntegrationTestBuilder(hugolib.IntegrationTestConfig{T: c, NeedsOsFS: true, TxtarString: files}).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `util1.js:4:17": No matching export in`) }) } // See issue 10527. func TestImportHugoVsESBuild(t *testing.T) { c := qt.New(t) for _, importSrcDir := range []string{"node_modules", "assets"} { c.Run(importSrcDir, func(c *qt.C) { files := ` -- IMPORT_SRC_DIR/imp1/index.js -- console.log("IMPORT_SRC_DIR:imp1/index.js"); -- IMPORT_SRC_DIR/imp2/index.ts -- console.log("IMPORT_SRC_DIR:imp2/index.ts"); -- IMPORT_SRC_DIR/imp3/foo.ts -- console.log("IMPORT_SRC_DIR:imp3/foo.ts"); -- assets/js/main.js -- import 'imp1/index.js'; import 'imp2/index.js'; import 'imp3/foo.js'; -- layouts/home.html -- {{ $js := resources.Get "js/main.js" | js.Build }} {{ $js.RelPermalink }} ` files = strings.ReplaceAll(files, "IMPORT_SRC_DIR", importSrcDir) b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, NeedsOsFS: true, TxtarString: files, }).Build() expected := ` IMPORT_SRC_DIR:imp1/index.js IMPORT_SRC_DIR:imp2/index.ts IMPORT_SRC_DIR:imp3/foo.ts ` expected = strings.ReplaceAll(expected, "IMPORT_SRC_DIR", importSrcDir) b.AssertFileContent("public/js/main.js", expected) }) } } // See https://github.com/evanw/esbuild/issues/2745 func TestPreserveLegalComments(t *testing.T) { t.Parallel() files := ` -- assets/js/main.js -- /* @license * Main license. */ import * as foo from 'js/utils'; console.log("Hello Main"); -- assets/js/utils/index.js -- export * from './util1'; export * from './util2'; -- assets/js/utils/util1.js -- /*! License util1 */ console.log("Hello 1"); -- assets/js/utils/util2.js -- //! License util2 */ console.log("Hello 2"); -- layouts/home.html -- {{ $js := resources.Get "js/main.js" | js.Build (dict "minify" false) }} {{ $js.RelPermalink }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, NeedsOsFS: true, TxtarString: files, }).Build() b.AssertFileContent("public/js/main.js", ` License util1 License util2 Main license `) } // Issue #11232 func TestTypeScriptExperimentalDecorators(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['RSS','sitemap','taxonomy','term'] -- tsconfig.json -- { "compilerOptions": { "experimentalDecorators": true, } } -- assets/ts/main.ts -- function addFoo(target: any) {target.prototype.foo = 'bar'} @addFoo class A {} -- layouts/home.html -- {{ $opts := dict "target" "es2020" "targetPath" "js/main.js" }} {{ (resources.Get "ts/main.ts" | js.Build $opts).Publish }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, NeedsOsFS: true, TxtarString: files, }).Build() b.AssertFileContent("public/js/main.js", "__decorateClass") } // Issue 13183. func TestExternalsInAssets(t *testing.T) { files := ` -- assets/js/util1.js -- export function hello1() { return 'abcd'; } -- assets/js/util2.js -- export function hello2() { return 'efgh'; } -- assets/js/main.js -- import { hello1 } from './util1.js'; import { hello2 } from './util2.js'; hello1(); hello2(); -- layouts/home.html -- Home. {{ $js := resources.Get "js/main.js" | js.Build (dict "externals" (slice "./util1.js")) }} {{ $js.Publish }} ` b := hugolib.Test(t, files, hugolib.TestOptOsFs()) b.AssertFileContent("public/js/main.js", "efgh") b.AssertFileContent("public/js/main.js", "! abcd") } func TestBuildErrorStack(t *testing.T) { files := ` -- hugo.toml -- disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"] -- assets/js/main.js -- import { hello1, hello2 } from './util1'; hello1(); -- layouts/home.html -- {{ $js := resources.Get "js/main.js" | js.Build }} JS Content:{{ $js.Content }}:End: ` b, err := hugolib.TestE(t, files, hugolib.TestOptOsFs()) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `execute of template failed: template: home.html:2:17`) b.Assert(err.Error(), qt.Contains, `main.js:1:31": Could not resolve "./util1"`) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/js/build.go
resources/resource_transformers/js/build.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package js import ( "path" "regexp" "github.com/evanw/esbuild/pkg/api" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/internal/js/esbuild" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) // Client context for ESBuild. type Client struct { c *esbuild.BuildClient } // New creates a new client context. func New(fs *filesystems.SourceFilesystem, rs *resources.Spec) *Client { return &Client{ c: esbuild.NewBuildClient(fs, rs), } } // Process processes a resource with the user provided options. func (c *Client) Process(res resources.ResourceTransformer, opts map[string]any) (resource.Resource, error) { return res.Transform( &buildTransformation{c: c, optsm: opts}, ) } func (c *Client) transform(opts esbuild.Options, transformCtx *resources.ResourceTransformationCtx) (api.BuildResult, error) { if transformCtx.DependencyManager != nil { opts.DependencyManager = transformCtx.DependencyManager } opts.StdinSourcePath = transformCtx.SourcePath result, err := c.c.Build(opts) if err != nil { return result, err } if opts.ExternalOptions.SourceMap == "linked" || opts.ExternalOptions.SourceMap == "external" { content := string(result.OutputFiles[1].Contents) if opts.ExternalOptions.SourceMap == "linked" { symPath := path.Base(transformCtx.OutPath) + ".map" re := regexp.MustCompile(`//# sourceMappingURL=.*\n?`) content = re.ReplaceAllString(content, "//# sourceMappingURL="+symPath+"\n") } if err = transformCtx.PublishSourceMap(string(result.OutputFiles[0].Contents)); err != nil { return result, err } _, err := transformCtx.To.Write([]byte(content)) if err != nil { return result, err } } else { _, err := transformCtx.To.Write(result.OutputFiles[0].Contents) if err != nil { return result, err } } return result, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/js/transform.go
resources/resource_transformers/js/transform.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package js import ( "io" "path" "path/filepath" "github.com/gohugoio/hugo/internal/js/esbuild" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal" ) type buildTransformation struct { optsm map[string]any c *Client } func (t *buildTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("jsbuild", t.optsm) } func (t *buildTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { ctx.OutMediaType = media.Builtin.JavascriptType var opts esbuild.Options if t.optsm != nil { optsExt, err := esbuild.DecodeExternalOptions(t.optsm) if err != nil { return err } opts.ExternalOptions = optsExt } if opts.TargetPath != "" { ctx.OutPath = opts.TargetPath } else { ctx.ReplaceOutPathExtension(".js") } src, err := io.ReadAll(ctx.From) if err != nil { return err } opts.SourceDir = filepath.FromSlash(path.Dir(ctx.SourcePath)) opts.Contents = string(src) opts.MediaType = ctx.InMediaType opts.Stdin = true _, err = t.c.transform(opts, ctx) return err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/templates/templates_integration_test.go
resources/resource_transformers/templates/templates_integration_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package templates_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestExecuteAsTemplateMultipleLanguages(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/blog" defaultContentLanguage = "fr" defaultContentLanguageInSubdir = true [Languages] [Languages.en] weight = 10 title = "In English" languageName = "English" [Languages.fr] weight = 20 title = "Le Français" languageName = "Français" -- i18n/en.toml -- [hello] other = "Hello" -- i18n/fr.toml -- [hello] other = "Bonjour" -- layouts/home.fr.html -- Lang: {{ site.Language.Lang }} {{ $templ := "{{T \"hello\"}}" | resources.FromString "f1.html" }} {{ $helloResource := $templ | resources.ExecuteAsTemplate (print "f%s.html" .Lang) . }} Hello1: {{T "hello"}} Hello2: {{ $helloResource.Content }} LangURL: {{ relLangURL "foo" }} -- layouts/home.html -- Lang: {{ site.Language.Lang }} {{ $templ := "{{T \"hello\"}}" | resources.FromString "f1.html" }} {{ $helloResource := $templ | resources.ExecuteAsTemplate (print "f%s.html" .Lang) . }} Hello1: {{T "hello"}} Hello2: {{ $helloResource.Content }} LangURL: {{ relLangURL "foo" }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/templates/execute_as_template.go
resources/resource_transformers/templates/execute_as_template.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package templates contains functions for template processing of Resource objects. package templates import ( "context" "fmt" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/tpl/tplimpl" ) // Client contains methods to perform template processing of Resource objects. type Client struct { rs *resources.Spec t tplimpl.TemplateStoreProvider } // New creates a new Client with the given specification. func New(rs *resources.Spec, t tplimpl.TemplateStoreProvider) *Client { if rs == nil { panic("must provide a resource Spec") } if t == nil { panic("must provide a template provider") } return &Client{rs: rs, t: t} } type executeAsTemplateTransform struct { rs *resources.Spec t tplimpl.TemplateStoreProvider targetPath string data any } func (t *executeAsTemplateTransform) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("execute-as-template", t.targetPath) } func (t *executeAsTemplateTransform) Transform(ctx *resources.ResourceTransformationCtx) error { tplStr := helpers.ReaderToString(ctx.From) th := t.t.GetTemplateStore() ti, err := th.TextParse(ctx.InPath, tplStr) if err != nil { return fmt.Errorf("failed to parse Resource %q as Template:: %w", ctx.InPath, err) } ctx.OutPath = t.targetPath return th.ExecuteWithContext(ctx.Ctx, ti, ctx.To, t.data) } func (c *Client) ExecuteAsTemplate(ctx context.Context, res resources.ResourceTransformer, targetPath string, data any) (resource.Resource, error) { return res.TransformWithContext(ctx, &executeAsTemplateTransform{ rs: c.rs, targetPath: paths.ToSlashTrimLeading(targetPath), t: c.t, data: data, }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/cssjs/postcss.go
resources/resource_transformers/cssjs/postcss.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package cssjs provides resource transformations backed by some popular JS based frameworks. package cssjs import ( "bytes" "fmt" "io" "path/filepath" "strings" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/resources/internal" "github.com/spf13/cast" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) // NewPostCSSClient creates a new PostCSSClient with the given specification. func NewPostCSSClient(rs *resources.Spec) *PostCSSClient { return &PostCSSClient{rs: rs} } func decodePostCSSOptions(m map[string]any) (opts PostCSSOptions, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) if !opts.NoMap { // There was for a long time a discrepancy between documentation and // implementation for the noMap property, so we need to support both // camel and snake case. opts.NoMap = cast.ToBool(m["no-map"]) } return } // PostCSSClient is the client used to do PostCSS transformations. type PostCSSClient struct { rs *resources.Spec } // Process transforms the given Resource with the PostCSS processor. func (c *PostCSSClient) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) { return res.Transform(&postcssTransformation{rs: c.rs, optionsm: options}) } type InlineImports struct { // Enable inlining of @import statements. // Does so recursively, but currently once only per file; // that is, it's not possible to import the same file in // different scopes (root, media query...) // Note that this import routine does not care about the CSS spec, // so you can have @import anywhere in the file. InlineImports bool // See issue https://github.com/gohugoio/hugo/issues/13719 // Disable inlining of @import statements // This is currenty only used for css.TailwindCSS. DisableInlineImports bool // When InlineImports is enabled, we fail the build if an import cannot be resolved. // You can enable this to allow the build to continue and leave the import statement in place. // Note that the inline importer does not process url location or imports with media queries, // so those will be left as-is even without enabling this option. SkipInlineImportsNotFound bool } // Some of the options from https://github.com/postcss/postcss-cli type PostCSSOptions struct { // Set a custom path to look for a config file. Config string NoMap bool // Disable the default inline sourcemaps InlineImports `mapstructure:",squash"` // Options for when not using a config file Use string // List of postcss plugins to use Parser string // Custom postcss parser Stringifier string // Custom postcss stringifier Syntax string // Custom postcss syntax } func (opts PostCSSOptions) toArgs() []string { var args []string if opts.NoMap { args = append(args, "--no-map") } if opts.Use != "" { args = append(args, "--use") args = append(args, strings.Fields(opts.Use)...) } if opts.Parser != "" { args = append(args, "--parser", opts.Parser) } if opts.Stringifier != "" { args = append(args, "--stringifier", opts.Stringifier) } if opts.Syntax != "" { args = append(args, "--syntax", opts.Syntax) } return args } type postcssTransformation struct { optionsm map[string]any rs *resources.Spec } func (t *postcssTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("postcss", t.optionsm) } // Transform shells out to postcss-cli to do the heavy lifting. // For this to work, you need some additional tools. To install them globally: // npm install -g postcss-cli // npm install -g autoprefixer func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { const binaryName = "postcss" infol := t.rs.Logger.InfoCommand(binaryName) infow := loggers.LevelLoggerToWriter(infol) ex := t.rs.ExecHelper var configFile string options, err := decodePostCSSOptions(t.optionsm) if err != nil { return err } if options.Config != "" { configFile = options.Config } else { configFile = "postcss.config.js" } configFile = filepath.Clean(configFile) // We need an absolute filename to the config file. if !filepath.IsAbs(configFile) { configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && options.Config != "" { // Only fail if the user specified config file is not found. return fmt.Errorf("postcss config %q not found", options.Config) } } var cmdArgs []any if configFile != "" { infol.Logf("use config file %q", configFile) cmdArgs = []any{"--config", configFile} } if optArgs := options.toArgs(); len(optArgs) > 0 { cmdArgs = append(cmdArgs, collections.StringSliceToInterfaceSlice(optArgs)...) } var errBuf bytes.Buffer stderr := io.MultiWriter(infow, &errBuf) cmdArgs = append(cmdArgs, hexec.WithStderr(stderr)) cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To)) cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs))) cmd, err := ex.Npx(binaryName, cmdArgs...) if err != nil { if hexec.IsNotFound(err) { // This may be on a CI server etc. Will fall back to pre-built assets. return &herrors.FeatureNotAvailableError{Cause: err} } return err } stdin, err := cmd.StdinPipe() if err != nil { return err } src := ctx.From imp := newImportResolver( ctx.From, ctx.InPath, options.InlineImports, t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager, ) if options.InlineImports.InlineImports { var err error src, err = imp.resolve() if err != nil { return err } } go func() { defer stdin.Close() io.Copy(stdin, src) }() err = cmd.Run() if err != nil { if hexec.IsNotFound(err) { return &herrors.FeatureNotAvailableError{ Cause: err, } } return imp.toFileError(errBuf.String()) } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/cssjs/tailwindcss.go
resources/resource_transformers/cssjs/tailwindcss.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cssjs import ( "bytes" "io" "regexp" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource" "github.com/mitchellh/mapstructure" ) var ( tailwindcssImportRe = regexp.MustCompile(`^tailwindcss/?`) tailwindImportExclude = func(s string) bool { return tailwindcssImportRe.MatchString(s) && !strings.Contains(s, ".") } ) // NewTailwindCSSClient creates a new TailwindCSSClient with the given specification. func NewTailwindCSSClient(rs *resources.Spec) *TailwindCSSClient { return &TailwindCSSClient{rs: rs} } // Client is the client used to do TailwindCSS transformations. type TailwindCSSClient struct { rs *resources.Spec } // Process transforms the given Resource with the TailwindCSS processor. func (c *TailwindCSSClient) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) { return res.Transform(&tailwindcssTransformation{rs: c.rs, optionsm: options}) } type tailwindcssTransformation struct { optionsm map[string]any rs *resources.Spec } func (t *tailwindcssTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("tailwindcss", t.optionsm) } type TailwindCSSOptions struct { Minify bool // Optimize and minify the output Optimize bool // Optimize the output without minifying InlineImports `mapstructure:",squash"` } func (opts TailwindCSSOptions) toArgs() []any { var args []any if opts.Minify { args = append(args, "--minify") } if opts.Optimize { args = append(args, "--optimize") } return args } func (t *tailwindcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { const binaryName = "tailwindcss" options, err := decodeTailwindCSSOptions(t.optionsm) if err != nil { return err } infol := t.rs.Logger.InfoCommand(binaryName) infow := loggers.LevelLoggerToWriter(infol) ex := t.rs.ExecHelper workingDir := t.rs.Cfg.BaseConfig().WorkingDir var cmdArgs []any = []any{ "--input=-", // Read from stdin. "--cwd", workingDir, } cmdArgs = append(cmdArgs, options.toArgs()...) var errBuf bytes.Buffer stderr := io.MultiWriter(infow, &errBuf) cmdArgs = append(cmdArgs, hexec.WithStderr(stderr)) cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To)) cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(workingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs))) cmd, err := ex.Npx(binaryName, cmdArgs...) if err != nil { if hexec.IsNotFound(err) { // This may be on a CI server etc. Will fall back to pre-built assets. return &herrors.FeatureNotAvailableError{Cause: err} } return err } stdin, err := cmd.StdinPipe() if err != nil { return err } src := ctx.From imp := newImportResolver( ctx.From, ctx.InPath, options.InlineImports, t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager, ) if !options.InlineImports.DisableInlineImports { src, err = imp.resolve() if err != nil { return err } } go func() { defer stdin.Close() io.Copy(stdin, src) }() err = cmd.Run() if err != nil { if hexec.IsNotFound(err) { return &herrors.FeatureNotAvailableError{ Cause: err, } } s := errBuf.String() if options.InlineImports.DisableInlineImports && strings.Contains(s, "Can't resolve") { s += "You may want to set the 'disableInlineImports' option to false to inline imports, see https://gohugo.io/functions/css/tailwindcss/#disableinlineimports" } return imp.toFileError(s) } return nil } func decodeTailwindCSSOptions(m map[string]any) (opts TailwindCSSOptions, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) return }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/cssjs/tailwindcss_integration_test.go
resources/resource_transformers/cssjs/tailwindcss_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cssjs_test import ( "testing" "github.com/bep/logg" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugolib" ) func TestTailwindV4Basic(t *testing.T) { if !htesting.IsCI() { t.Skip("Skip long running test when running locally") } files := ` -- hugo.toml -- -- package.json -- { "license": "MIT", "repository": { "type": "git", "url": "https://github.com/bep/hugo-starter-tailwind-basic.git" }, "devDependencies": { "@tailwindcss/cli": "^4.0.1", "tailwindcss": "^4.0.1" }, "name": "hugo-starter-tailwind-basic", "version": "0.1.0" } -- assets/css/styles.css -- @import "tailwindcss"; @theme { --font-family-display: "Satoshi", "sans-serif"; --breakpoint-3xl: 1920px; --color-neon-pink: oklch(71.7% 0.25 360); --color-neon-lime: oklch(91.5% 0.258 129); --color-neon-cyan: oklch(91.3% 0.139 195.8); } -- layouts/home.html -- {{ $css := resources.Get "css/styles.css" | css.TailwindCSS }} CSS: {{ $css.Content | safeCSS }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, NeedsNpmInstall: true, LogLevel: logg.LevelInfo, }).Build() b.AssertFileContent("public/index.html", "/*! tailwindcss v4.") } func TestTailwindCSSNoInlineImportsIssue13719(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] theme = 'my-theme' [[module.mounts]] source = 'assets' target = 'assets' [[module.mounts]] source = 'other' target = 'assets/css' -- assets/css/main.css -- @import "tailwindcss"; @import "colors/red.css"; @import "colors/blue.css"; @import "colors/purple.css"; -- assets/css/colors/red.css -- @import "green.css"; .red {color: red;} -- assets/css/colors/green.css -- .green {color: green;} -- themes/my-theme/assets/css/colors/blue.css -- .blue {color: blue;} -- other/colors/purple.css -- .purple {color: purple;} -- layouts/home.html -- {{ with (templates.Defer (dict "key" "global")) }} {{ with resources.Get "css/main.css" }} {{ $opts := dict "disableInlineImports" true }} {{ with . | css.TailwindCSS $opts }} <link rel="stylesheet" href="{{ .RelPermalink }}"> {{ end }} {{ end }} {{ end }} -- package.json -- { "devDependencies": { "@tailwindcss/cli": "^4.1.7", "tailwindcss": "^4.1.7" } } ` b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, NeedsNpmInstall: true, LogLevel: logg.LevelInfo, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "Can't resolve 'colors/red.css'") b.Assert(err.Error(), qt.Contains, "You may want to set the 'disableInlineImports' option to false") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/cssjs/inline_imports.go
resources/resource_transformers/cssjs/inline_imports.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cssjs import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "path" "path/filepath" "regexp" "strconv" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/identity" "github.com/spf13/afero" ) const importIdentifier = "@import" var ( cssSyntaxErrorRe = regexp.MustCompile(`> (\d+) \|`) shouldImportRe = regexp.MustCompile(`^@import ["'](.*?)["'];?\s*(/\*.*\*/)?$`) ) type fileOffset struct { Filename string Offset int } type importResolver struct { r io.Reader inPath string opts InlineImports contentSeen map[string]bool dependencyManager identity.Manager linemap map[int]fileOffset fs afero.Fs logger loggers.Logger } func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver { return &importResolver{ r: r, dependencyManager: dependencyManager, inPath: inPath, fs: fs, logger: logger, linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool), opts: opts, } } func (imp *importResolver) contentHash(filename string) ([]byte, string) { b, err := afero.ReadFile(imp.fs, filename) if err != nil { return nil, "" } h := sha256.New() h.Write(b) return b, hex.EncodeToString(h.Sum(nil)) } func (imp *importResolver) importRecursive( lineNum int, content string, inPath string, ) (int, string, error) { basePath := path.Dir(inPath) var replacements []string lines := strings.Split(content, "\n") trackLine := func(i, offset int, line string) { // TODO(bep) this is not very efficient. imp.linemap[i+lineNum] = fileOffset{Filename: inPath, Offset: offset} } i := 0 for offset, line := range lines { i++ lineTrimmed := strings.TrimSpace(line) column := strings.Index(line, lineTrimmed) line = lineTrimmed if !imp.shouldImport(line) { trackLine(i, offset, line) } else { path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';") filename := filepath.Join(basePath, path) imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename)) importContent, hash := imp.contentHash(filename) if importContent == nil { if imp.opts.SkipInlineImportsNotFound { trackLine(i, offset, line) continue } pos := text.Position{ Filename: inPath, LineNumber: offset + 1, ColumnNumber: column + 1, } msgDetail := "if this import's source lives in node_modules, enable the skipInlineImportsNotFound option, see https://gohugo.io/functions/css/postcss/#skipinlineimportsnotfound" return 0, "", herrors.NewFileErrorFromFileInPos(fmt.Errorf("failed to resolve CSS @import \"%s\"; %s", filename, msgDetail), pos, imp.fs, nil) } i-- if imp.contentSeen[hash] { i++ // Just replace the line with an empty string. replacements = append(replacements, []string{line, ""}...) trackLine(i, offset, "IMPORT") continue } imp.contentSeen[hash] = true // Handle recursive imports. l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename)) if err != nil { return 0, "", err } trackLine(i, offset, line) i += l importContent = []byte(nested) replacements = append(replacements, []string{line, string(importContent)}...) } } if len(replacements) > 0 { repl := strings.NewReplacer(replacements...) content = repl.Replace(content) } return i, content, nil } func (imp *importResolver) resolve() (io.Reader, error) { content, err := io.ReadAll(imp.r) if err != nil { return nil, err } contents := string(content) _, newContent, err := imp.importRecursive(0, contents, imp.inPath) if err != nil { return nil, err } return strings.NewReader(newContent), nil } // See https://www.w3schools.com/cssref/pr_import_rule.asp // We currently only support simple file imports, no urls, no media queries. // So this is OK: // // @import "navigation.css"; // // This is not: // // @import url("navigation.css"); // @import "mobstyle.css" screen and (max-width: 768px); func (imp *importResolver) shouldImport(s string) bool { if !strings.HasPrefix(s, importIdentifier) { return false } if strings.Contains(s, "url(") { return false } m := shouldImportRe.FindStringSubmatch(s) if m == nil { return false } if len(m) != 3 { return false } if tailwindImportExclude(m[1]) { return false } return true } func (imp *importResolver) toFileError(output string) error { inErr := errors.New(output) match := cssSyntaxErrorRe.FindStringSubmatch(output) if match == nil { return inErr } lineNum, err := strconv.Atoi(match[1]) if err != nil { return inErr } file, ok := imp.linemap[lineNum] if !ok { return inErr } fi, err := imp.fs.Stat(file.Filename) if err != nil { return inErr } meta := fi.(hugofs.FileMetaInfo).Meta() realFilename := meta.Filename f, err := meta.Open() if err != nil { return inErr } defer f.Close() ferr := herrors.NewFileErrorFromName(inErr, realFilename) pos := ferr.Position() pos.LineNumber = file.Offset + 1 return ferr.UpdatePosition(pos).UpdateContent(f, nil) // return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/cssjs/inline_imports_test.go
resources/resource_transformers/cssjs/inline_imports_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cssjs import ( "regexp" "strings" "testing" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/htesting/hqt" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/helpers" "github.com/spf13/afero" qt "github.com/frankban/quicktest" ) // Issue 6166 func TestDecodeOptions(t *testing.T) { c := qt.New(t) opts1, err := decodePostCSSOptions(map[string]any{ "no-map": true, }) c.Assert(err, qt.IsNil) c.Assert(opts1.NoMap, qt.Equals, true) opts2, err := decodePostCSSOptions(map[string]any{ "noMap": true, }) c.Assert(err, qt.IsNil) c.Assert(opts2.NoMap, qt.Equals, true) } func TestShouldImport(t *testing.T) { c := qt.New(t) var imp *importResolver for _, test := range []struct { input string expect bool }{ {input: `@import "navigation.css";`, expect: true}, {input: `@import "navigation.css"; /* Using a string */`, expect: true}, {input: `@import "navigation.css"`, expect: true}, {input: `@import 'navigation.css';`, expect: true}, {input: `@import url("navigation.css");`, expect: false}, {input: `@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,400i,800,800i&display=swap');`, expect: false}, {input: `@import "printstyle.css" print;`, expect: false}, } { c.Assert(imp.shouldImport(test.input), qt.Equals, test.expect) } } func TestShouldImportExcludes(t *testing.T) { c := qt.New(t) var imp *importResolver c.Assert(imp.shouldImport(`@import "navigation.css";`), qt.Equals, true) c.Assert(imp.shouldImport(`@import "tailwindcss";`), qt.Equals, false) c.Assert(imp.shouldImport(`@import "tailwindcss.css";`), qt.Equals, true) c.Assert(imp.shouldImport(`@import "tailwindcss/preflight";`), qt.Equals, false) } func TestImportResolver(t *testing.T) { c := qt.New(t) fs := afero.NewMemMapFs() writeFile := func(name, content string) { c.Assert(afero.WriteFile(fs, name, []byte(content), 0o777), qt.IsNil) } writeFile("a.css", `@import "b.css"; @import "c.css"; A_STYLE1 A_STYLE2 `) writeFile("b.css", `B_STYLE`) writeFile("c.css", "@import \"d.css\"\nC_STYLE") writeFile("d.css", "@import \"a.css\"\n\nD_STYLE") writeFile("e.css", "E_STYLE") mainStyles := strings.NewReader(`@import "a.css"; @import "b.css"; LOCAL_STYLE @import "c.css"; @import "e.css";`) imp := newImportResolver( mainStyles, "styles.css", InlineImports{}, fs, loggers.NewDefault(), identity.NopManager, ) r, err := imp.resolve() c.Assert(err, qt.IsNil) rs := helpers.ReaderToString(r) result := regexp.MustCompile(`\n+`).ReplaceAllString(rs, "\n") c.Assert(result, hqt.IsSameString, `B_STYLE D_STYLE C_STYLE A_STYLE1 A_STYLE2 LOCAL_STYLE E_STYLE`) dline := imp.linemap[3] c.Assert(dline, qt.DeepEquals, fileOffset{ Offset: 1, Filename: "d.css", }) } func BenchmarkImportResolver(b *testing.B) { c := qt.New(b) fs := afero.NewMemMapFs() writeFile := func(name, content string) { c.Assert(afero.WriteFile(fs, name, []byte(content), 0o777), qt.IsNil) } writeFile("a.css", `@import "b.css"; @import "c.css"; A_STYLE1 A_STYLE2 `) writeFile("b.css", `B_STYLE`) writeFile("c.css", "@import \"d.css\"\nC_STYLE"+strings.Repeat("\nSTYLE", 12)) writeFile("d.css", "@import \"a.css\"\n\nD_STYLE"+strings.Repeat("\nSTYLE", 55)) writeFile("e.css", "E_STYLE") mainStyles := `@import "a.css"; @import "b.css"; LOCAL_STYLE @import "c.css"; @import "e.css"; @import "missing.css";` logger := loggers.NewDefault() for b.Loop() { b.StopTimer() imp := newImportResolver( strings.NewReader(mainStyles), "styles.css", InlineImports{}, fs, logger, identity.NopManager, ) b.StartTimer() _, err := imp.resolve() if err != nil { b.Fatal(err) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/cssjs/postcss_integration_test.go
resources/resource_transformers/cssjs/postcss_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cssjs_test import ( "fmt" "path/filepath" "runtime" "strings" "testing" "github.com/bep/logg" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugolib" ) const postCSSIntegrationTestFiles = ` -- assets/css/components/a.css -- /* A comment. */ /* Another comment. */ class-in-a { color: blue; } -- assets/css/components/all.css -- @import "a.css"; @import "b.css"; -- assets/css/components/b.css -- @import "a.css"; class-in-b { color: blue; } -- assets/css/styles.css -- @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } -- hugo.toml -- disablekinds = ['taxonomy', 'term', 'page'] baseURL = "https://example.com" [build] useResourceCacheWhen = 'never' -- content/p1.md -- -- data/hugo.toml -- slogan = "Hugo Rocks!" -- i18n/en.yaml -- hello: other: "Hello" -- i18n/fr.yaml -- hello: other: "Bonjour" -- layouts/home.html -- {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | css.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| -- package.json -- { "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } -- postcss.config.js -- console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); console.error("Hugo PublishDir:", process.env.HUGO_PUBLISHDIR ); // https://github.com/gohugoio/hugo/issues/7656 console.error("package.json:", process.env.HUGO_FILE_PACKAGE_JSON ); console.error("PostCSS Config File:", process.env.HUGO_FILE_POSTCSS_CONFIG_JS ); module.exports = { plugins: [ require('tailwindcss') ] } ` func TestTransformPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("Skip long running test when running locally") } c := qt.New(t) tempDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test") c.Assert(err, qt.IsNil) c.Cleanup(clean) for _, s := range []string{"never", "always"} { repl := strings.NewReplacer( "https://example.com", "https://example.com/foo", "useResourceCacheWhen = 'never'", fmt.Sprintf("useResourceCacheWhen = '%s'", s), ) files := repl.Replace(postCSSIntegrationTestFiles) b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, NeedsOsFS: true, NeedsNpmInstall: true, LogLevel: logg.LevelInfo, WorkingDir: tempDir, TxtarString: files, }).Build() b.AssertFileContent("public/index.html", ` Styles RelPermalink: /foo/css/styles.css Styles Content: Len: 770917| `) if s == "never" { b.AssertLogContains("Hugo Environment: production") b.AssertLogContains("Hugo PublishDir: " + filepath.Join(tempDir, "public")) } } } // 9880 func TestTransformPostCSSError(t *testing.T) { if !htesting.IsCI() { t.Skip("Skip long running test when running locally") } if runtime.GOOS == "windows" { // TODO(bep) This has started to fail on Windows with Go 1.19 on GitHub Actions for some mysterious reason. t.Skip("Skip on Windows") } c := qt.New(t) b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, NeedsOsFS: true, NeedsNpmInstall: true, TxtarString: strings.ReplaceAll(postCSSIntegrationTestFiles, "color: blue;", "@apply foo;"), // Syntax error }).BuildE() ferrs := herrors.UnwrapFileErrors(err) b.Assert(len(ferrs), qt.Equals, 2) b.Assert(err.Error(), qt.Contains, "a.css:4:2") } func TestTransformPostCSSNotInstalledError(t *testing.T) { if !htesting.IsCI() { t.Skip("Skip long running test when running locally") } c := qt.New(t) _, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, NeedsOsFS: true, TxtarString: postCSSIntegrationTestFiles, }).BuildE() ferrs := herrors.UnwrapFileErrors(err) c.Assert(len(ferrs), qt.Equals, 1) c.Assert(err.Error(), qt.Contains, `binary with name "postcss" not found using npx`) } // #9895 func TestTransformPostCSSImportError(t *testing.T) { if !htesting.IsCI() { t.Skip("Skip long running test when running locally") } c := qt.New(t) _, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, NeedsOsFS: true, NeedsNpmInstall: true, LogLevel: logg.LevelInfo, TxtarString: strings.ReplaceAll(postCSSIntegrationTestFiles, `@import "components/all.css";`, `@import "components/doesnotexist.css";`), }).BuildE() ferrs := herrors.UnwrapFileErrors(err) c.Assert(len(ferrs), qt.Equals, 2) c.Assert(err.Error(), qt.Contains, "styles.css:4:3") c.Assert(err.Error(), qt.Contains, filepath.FromSlash(`failed to resolve CSS @import "/css/components/doesnotexist.css"`)) } func TestTransformPostCSSImporSkipInlineImportsNotFound(t *testing.T) { if !htesting.IsCI() { t.Skip("Skip long running test when running locally") } c := qt.New(t) files := strings.ReplaceAll(postCSSIntegrationTestFiles, `@import "components/all.css";`, `@import "components/doesnotexist.css";`) files = strings.ReplaceAll(files, `{{ $options := dict "inlineImports" true }}`, `{{ $options := dict "inlineImports" true "skipInlineImportsNotFound" true }}`) s := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, NeedsOsFS: true, NeedsNpmInstall: true, LogLevel: logg.LevelInfo, TxtarString: files, }).Build() s.AssertFileContent("public/css/styles.css", `@import "components/doesnotexist.css";`) } // Issue 9787 func TestTransformPostCSSResourceCacheWithPathInBaseURL(t *testing.T) { if !htesting.IsCI() { t.Skip("Skip long running test when running locally") } c := qt.New(t) tempDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test") c.Assert(err, qt.IsNil) c.Cleanup(clean) for i := range 2 { files := postCSSIntegrationTestFiles if i == 1 { files = strings.ReplaceAll(files, "https://example.com", "https://example.com/foo") files = strings.ReplaceAll(files, "useResourceCacheWhen = 'never'", " useResourceCacheWhen = 'always'") } b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, NeedsOsFS: true, NeedsNpmInstall: true, LogLevel: logg.LevelInfo, TxtarString: files, WorkingDir: tempDir, }).Build() b.AssertFileContent("public/index.html", ` Styles Content: Len: 770917 `) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/htesting/testhelpers.go
resources/resource_transformers/htesting/testhelpers.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package htesting import ( "path/filepath" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources" "github.com/spf13/afero" ) func NewResourceTransformerForSpec(spec *resources.Spec, filename, content string) (resources.ResourceTransformer, error) { filename = filepath.FromSlash(filename) fs := spec.Fs.Source if err := afero.WriteFile(fs, filename, []byte(content), 0o777); err != nil { return nil, err } var open hugio.OpenReadSeekCloser = func() (hugio.ReadSeekCloser, error) { return fs.Open(filename) } r, err := spec.NewResource(resources.ResourceSourceDescriptor{TargetPath: filepath.FromSlash(filename), OpenReadSeekCloser: open, GroupIdentity: identity.Anonymous}) if err != nil { return nil, err } return r.(resources.ResourceTransformer), nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/minifier/minifier_integration_test.go
resources/resource_transformers/minifier/minifier_integration_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package minifier_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 8954 func TestTransformMinify(t *testing.T) { c := qt.New(t) files := ` -- assets/js/test.js -- new Date(2002, 04, 11) -- hugo.toml -- -- layouts/home.html -- {{ $js := resources.Get "js/test.js" | minify }} <script> {{ $js.Content }} </script> ` b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err, qt.ErrorMatches, "(?s).*legacy octal numbers.*line 1.*") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/minifier/minify.go
resources/resource_transformers/minifier/minify.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package minifier import ( "github.com/gohugoio/hugo/minifiers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource" ) // Client for minification of Resource objects. Supported minifiers are: // css, html, js, json, svg and xml. type Client struct { rs *resources.Spec m minifiers.Client } // New creates a new Client given a specification. Note that it is the media types // configured for the site that is used to match files to the correct minifier. func New(rs *resources.Spec) (*Client, error) { m, err := minifiers.New(rs.MediaTypes(), rs.OutputFormats(), rs.Cfg) if err != nil { return nil, err } return &Client{rs: rs, m: m}, nil } type minifyTransformation struct { rs *resources.Spec m minifiers.Client } func (t *minifyTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("minify") } func (t *minifyTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { ctx.AddOutPathIdentifier(".min") return t.m.Minify(ctx.InMediaType, ctx.To, ctx.From) } func (c *Client) Minify(res resources.ResourceTransformer) (resource.Resource, error) { return res.Transform(&minifyTransformation{ rs: c.rs, m: c.m, }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/minifier/minify_test.go
resources/resource_transformers/minifier/minify_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package minifier import ( "context" "testing" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/resources/resource" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/resources/resource_transformers/htesting" ) func TestTransform(t *testing.T) { c := qt.New(t) d := testconfig.GetTestDeps(nil, nil) t.Cleanup(func() { c.Assert(d.Close(), qt.IsNil) }) client, _ := New(d.ResourceSpec) r, err := htesting.NewResourceTransformerForSpec(d.ResourceSpec, "hugo.html", "<h1> Hugo Rocks! </h1>") c.Assert(err, qt.IsNil) transformed, err := client.Minify(r) c.Assert(err, qt.IsNil) c.Assert(transformed.RelPermalink(), qt.Equals, "/hugo.min.html") content, err := transformed.(resource.ContentProvider).Content(context.Background()) c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "<h1>Hugo Rocks!</h1>") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/babel/babel.go
resources/resource_transformers/babel/babel.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package babel import ( "bytes" "fmt" "io" "os" "path" "path/filepath" "regexp" "strconv" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/resources/internal" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) // Options from https://babeljs.io/docs/en/options type Options struct { Config string // Custom path to config file Minified bool NoComments bool Compact *bool Verbose bool NoBabelrc bool SourceMap string } // DecodeOptions decodes options to and generates command flags func DecodeOptions(m map[string]any) (opts Options, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) return } func (opts Options) toArgs() []any { var args []any // external is not a known constant on the babel command line // .sourceMaps must be a boolean, "inline", "both", or undefined switch opts.SourceMap { case "external": args = append(args, "--source-maps") case "inline": args = append(args, "--source-maps=inline") } if opts.Minified { args = append(args, "--minified") } if opts.NoComments { args = append(args, "--no-comments") } if opts.Compact != nil { args = append(args, "--compact="+strconv.FormatBool(*opts.Compact)) } if opts.Verbose { args = append(args, "--verbose") } if opts.NoBabelrc { args = append(args, "--no-babelrc") } return args } // Client is the client used to do Babel transformations. type Client struct { rs *resources.Spec } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } type babelTransformation struct { options Options rs *resources.Spec } func (t *babelTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("babel", t.options) } // Transform shells out to babel-cli to do the heavy lifting. // For this to work, you need some additional tools. To install them globally: // npm install -g @babel/core @babel/cli // If you want to use presets or plugins such as @babel/preset-env // Then you should install those globally as well. e.g: // npm install -g @babel/preset-env // Instead of installing globally, you can also install everything as a dev-dependency (--save-dev instead of -g) func (t *babelTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { const binaryName = "babel" ex := t.rs.ExecHelper if err := ex.Sec().CheckAllowedExec(binaryName); err != nil { return err } var configFile string infol := t.rs.Logger.InfoCommand(binaryName) infoW := loggers.LevelLoggerToWriter(infol) var errBuf bytes.Buffer if t.options.Config != "" { configFile = t.options.Config } else { configFile = "babel.config.js" } configFile = filepath.Clean(configFile) // We need an absolute filename to the config file. if !filepath.IsAbs(configFile) { configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && t.options.Config != "" { // Only fail if the user specified config file is not found. return fmt.Errorf("babel config %q not found", configFile) } } ctx.ReplaceOutPathExtension(".js") var cmdArgs []any if configFile != "" { infol.Logf("use config file %q", configFile) cmdArgs = []any{"--config-file", configFile} } if optArgs := t.options.toArgs(); len(optArgs) > 0 { cmdArgs = append(cmdArgs, optArgs...) } cmdArgs = append(cmdArgs, "--filename="+ctx.SourcePath) // Create compile into a real temp file: // 1. separate stdout/stderr messages from babel (https://github.com/gohugoio/hugo/issues/8136) // 2. allow generation and retrieval of external source map. compileOutput, err := os.CreateTemp("", "compileOut-*.js") if err != nil { return err } cmdArgs = append(cmdArgs, "--out-file="+compileOutput.Name()) stderr := io.MultiWriter(infoW, &errBuf) cmdArgs = append(cmdArgs, hexec.WithStderr(stderr)) cmdArgs = append(cmdArgs, hexec.WithStdout(stderr)) cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs))) defer func() { compileOutput.Close() os.Remove(compileOutput.Name()) }() // ARGA [--no-install babel --config-file /private/var/folders/_g/j3j21hts4fn7__h04w2x8gb40000gn/T/hugo-test-babel812882892/babel.config.js --source-maps --filename=js/main2.js --out-file=/var/folders/_g/j3j21hts4fn7__h04w2x8gb40000gn/T/compileOut-2237820197.js] // [--no-install babel --config-file /private/var/folders/_g/j3j21hts4fn7__h04w2x8gb40000gn/T/hugo-test-babel332846848/babel.config.js --filename=js/main.js --out-file=/var/folders/_g/j3j21hts4fn7__h04w2x8gb40000gn/T/compileOut-1451390834.js 0x10304ee60 0x10304ed60 0x10304f060] cmd, err := ex.Npx(binaryName, cmdArgs...) if err != nil { if hexec.IsNotFound(err) { // This may be on a CI server etc. Will fall back to pre-built assets. return &herrors.FeatureNotAvailableError{Cause: err} } return err } stdin, err := cmd.StdinPipe() if err != nil { return err } go func() { defer stdin.Close() io.Copy(stdin, ctx.From) }() err = cmd.Run() if err != nil { if hexec.IsNotFound(err) { return &herrors.FeatureNotAvailableError{Cause: err} } return fmt.Errorf(errBuf.String()+": %w", err) } content, err := io.ReadAll(compileOutput) if err != nil { return err } mapFile := compileOutput.Name() + ".map" if _, err := os.Stat(mapFile); err == nil { defer os.Remove(mapFile) sourceMap, err := os.ReadFile(mapFile) if err != nil { return err } if err = ctx.PublishSourceMap(string(sourceMap)); err != nil { return err } targetPath := path.Base(ctx.OutPath) + ".map" re := regexp.MustCompile(`//# sourceMappingURL=.*\n?`) content = []byte(re.ReplaceAllString(string(content), "//# sourceMappingURL="+targetPath+"\n")) } ctx.To.Write(content) return nil } // Process transforms the given Resource with the Babel processor. func (c *Client) Process(res resources.ResourceTransformer, options Options) (resource.Resource, error) { return res.Transform( &babelTransformation{rs: c.rs, options: options}, ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/resource_transformers/babel/babel_integration_test.go
resources/resource_transformers/babel/babel_integration_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package babel_test import ( "testing" "github.com/bep/logg" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugolib" ) func TestTransformBabel(t *testing.T) { if !htesting.IsCI() { t.Skip("Skip long running test when running locally") } files := ` -- assets/js/main.js -- /* A Car */ class Car { constructor(brand) { this.carname = brand; } } -- assets/js/main2.js -- /* A Car2 */ class Car2 { constructor(brand) { this.carname = brand; } } -- babel.config.js -- console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); module.exports = { presets: ["@babel/preset-env"], }; -- hugo.toml -- disablekinds = ['taxonomy', 'term', 'page'] [security] [security.exec] allow = ['^npx$', '^babel$'] -- layouts/home.html -- {{ $options := dict "noComments" true }} {{ $transpiled := resources.Get "js/main.js" | babel -}} Transpiled: {{ $transpiled.Content | safeJS }} {{ $transpiled := resources.Get "js/main2.js" | babel (dict "sourceMap" "inline") -}} Transpiled2: {{ $transpiled.Content | safeJS }} {{ $transpiled := resources.Get "js/main2.js" | babel (dict "sourceMap" "external") -}} Transpiled3: {{ $transpiled.Permalink }} -- package.json -- { "scripts": {}, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5" } } ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, NeedsNpmInstall: true, LogLevel: logg.LevelInfo, }).Build() b.AssertLogContains("babel: Hugo Environment: production") b.AssertFileContent("public/index.html", `var Car2 =`) b.AssertFileContent("public/js/main2.js", `var Car2 =`) b.AssertFileContent("public/js/main2.js.map", `{"version":3,`) b.AssertFileContent("public/index.html", ` //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozL`) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/internal/key_test.go
resources/internal/key_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package internal import ( "testing" qt "github.com/frankban/quicktest" ) type testStruct struct { Name string V1 int64 V2 int32 V3 int V4 uint64 } func TestResourceTransformationKey(t *testing.T) { // We really need this key to be portable across OSes. key := NewResourceTransformationKey("testing", testStruct{Name: "test", V1: int64(10), V2: int32(20), V3: 30, V4: uint64(40)}) c := qt.New(t) c.Assert(key.Value(), qt.Equals, "testing_4231238781487357822") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/internal/resourcepaths.go
resources/internal/resourcepaths.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package internal import ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/common/paths" ) // ResourcePaths holds path information for a resource. // All directories in here have Unix-style slashes, with leading slash, but no trailing slash. // Empty directories are represented with an empty string. type ResourcePaths struct { // This is the directory component for the target file or link. Dir string // Any base directory for the target file. Will be prepended to Dir. BaseDirTarget string // This is the directory component for the link will be prepended to Dir. BaseDirLink string // Set when publishing in a multihost setup. TargetBasePaths []string // This is the File component, e.g. "data.json". File string } func (d ResourcePaths) join(p ...string) string { var s string for i, pp := range p { if pp == "" { continue } if i > 0 && !strings.HasPrefix(pp, "/") { pp = "/" + pp } s += pp } if !strings.HasPrefix(s, "/") { s = "/" + s } return s } func (d ResourcePaths) TargetLink() string { return d.join(d.BaseDirLink, d.Dir, d.File) } func (d ResourcePaths) TargetPath() string { return d.join(d.BaseDirTarget, d.Dir, d.File) } func (d ResourcePaths) Path() string { return d.join(d.Dir, d.File) } func (d ResourcePaths) TargetPaths() []string { if len(d.TargetBasePaths) == 0 { return []string{d.TargetPath()} } var paths []string for _, p := range d.TargetBasePaths { paths = append(paths, p+d.TargetPath()) } return paths } func (d ResourcePaths) TargetFilenames() []string { filenames := d.TargetPaths() for i, p := range filenames { filenames[i] = filepath.FromSlash(p) } return filenames } func (d ResourcePaths) FromTargetPath(targetPath string) ResourcePaths { targetPath = filepath.ToSlash(targetPath) dir, file := path.Split(targetPath) dir = paths.ToSlashPreserveLeading(dir) if dir == "/" { dir = "" } d.Dir = dir d.File = file d.BaseDirLink = "" d.BaseDirTarget = "" return d }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/internal/key.go
resources/internal/key.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package internal import "github.com/gohugoio/hugo/common/hashing" // ResourceTransformationKey are provided by the different transformation implementations. // It identifies the transformation (name) and its configuration (elements). // We combine this in a chain with the rest of the transformations // with the target filename and a content hash of the origin to use as cache key. type ResourceTransformationKey struct { Name string elements []any } // NewResourceTransformationKey creates a new ResourceTransformationKey from the transformation // name and elements. We will create a 64 bit FNV hash from the elements, which when combined // with the other key elements should be unique for all practical applications. func NewResourceTransformationKey(name string, elements ...any) ResourceTransformationKey { return ResourceTransformationKey{Name: name, elements: elements} } // Value returns the Key as a string. // Do not change this without good reasons. func (k ResourceTransformationKey) Value() string { if len(k.elements) == 0 { return k.Name } return k.Name + "_" + hashing.HashString(k.elements...) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/page/page_outputformat.go
resources/page/page_outputformat.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package page contains the core interfaces and types for the Page resource, // a core component in Hugo. package page import ( "strings" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/output" ) // OutputFormats holds a list of the relevant output formats for a given page. type OutputFormats []OutputFormat // OutputFormat links to a representation of a resource. type OutputFormat struct { // Rel contains a value that can be used to construct a rel link. // This is value is fetched from the output format definition. // Note that for pages with only one output format, // this method will always return "canonical". // As an example, the AMP output format will, by default, return "amphtml". // // See: // https://www.ampproject.org/docs/guides/deploy/discovery // // Most other output formats will have "alternate" as value for this. Rel string Format output.Format relPermalink string permalink string } // Name returns this OutputFormat's name, i.e. HTML, AMP, JSON etc. func (o OutputFormat) Name() string { return o.Format.Name } // MediaType returns this OutputFormat's MediaType (MIME type). func (o OutputFormat) MediaType() media.Type { return o.Format.MediaType } // Permalink returns the absolute permalink to this output format. func (o OutputFormat) Permalink() string { return o.permalink } // RelPermalink returns the relative permalink to this output format. func (o OutputFormat) RelPermalink() string { return o.relPermalink } func NewOutputFormat(relPermalink, permalink string, isCanonical bool, f output.Format) OutputFormat { isUserConfigured := true for _, d := range output.DefaultFormats { if strings.EqualFold(d.Name, f.Name) { isUserConfigured = false } } rel := f.Rel // If the output format is the canonical format for the content, we want // to specify this in the "rel" attribute of an HTML "link" element. // However, for custom output formats, we don't want to surprise users by // overwriting "rel" if isCanonical && !isUserConfigured { rel = "canonical" } return OutputFormat{Rel: rel, Format: f, relPermalink: relPermalink, permalink: permalink} } // Get gets a OutputFormat given its name, i.e. json, html etc. // It returns nil if none found. func (o OutputFormats) Get(name string) *OutputFormat { for _, f := range o { if strings.EqualFold(f.Format.Name, name) { return &f } } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/page/page_marshaljson.autogen.go
resources/page/page_marshaljson.autogen.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This file is autogenerated. package page import ( "encoding/json" "github.com/gohugoio/hugo/config" "time" ) func MarshalPageToJSON(p Page) ([]byte, error) { date := p.Date() lastmod := p.Lastmod() publishDate := p.PublishDate() expiryDate := p.ExpiryDate() aliases := p.Aliases() bundleType := p.BundleType() description := p.Description() draft := p.Draft() isHome := p.IsHome() keywords := p.Keywords() kind := p.Kind() layout := p.Layout() linkTitle := p.LinkTitle() isNode := p.IsNode() isPage := p.IsPage() path := p.Path() slug := p.Slug() lang := p.Lang() isSection := p.IsSection() section := p.Section() sitemap := p.Sitemap() typ := p.Type() weight := p.Weight() s := struct { Date time.Time Lastmod time.Time PublishDate time.Time ExpiryDate time.Time Aliases []string BundleType string Description string Draft bool IsHome bool Keywords []string Kind string Layout string LinkTitle string IsNode bool IsPage bool Path string Slug string Lang string IsSection bool Section string Sitemap config.SitemapConfig Type string Weight int }{ Date: date, Lastmod: lastmod, PublishDate: publishDate, ExpiryDate: expiryDate, Aliases: aliases, BundleType: bundleType, Description: description, Draft: draft, IsHome: isHome, Keywords: keywords, Kind: kind, Layout: layout, LinkTitle: linkTitle, IsNode: isNode, IsPage: isPage, Path: path, Slug: slug, Lang: lang, IsSection: isSection, Section: section, Sitemap: sitemap, Type: typ, Weight: weight, } return json.Marshal(&s) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/page/pages_sort.go
resources/page/pages_sort.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package page import ( "context" "sort" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/compare" "github.com/spf13/cast" ) var spc = newPageCache() /* * Implementation of a custom sorter for Pages */ // A pageSorter implements the sort interface for Pages type pageSorter struct { pages Pages by pageBy } // pageBy is a closure used in the Sort.Less method. type pageBy func(p1, p2 Page) bool func getOrdinals(p1, p2 Page) (int, int) { p1o, ok1 := p1.(collections.Order) if !ok1 { return -1, -1 } p2o, ok2 := p2.(collections.Order) if !ok2 { return -1, -1 } return p1o.Ordinal(), p2o.Ordinal() } func getWeight0s(p1, p2 Page) (w1 int, w2 int) { p1w, ok1 := p1.(types.Weight0Provider) if !ok1 { return } p2w, ok2 := p2.(types.Weight0Provider) if !ok2 { return } return p1w.Weight0(), p2w.Weight0() } // Sort stable sorts the pages given the receiver's sort order. func (by pageBy) Sort(pages Pages) { ps := &pageSorter{ pages: pages, by: by, // The Sort method's receiver is the function (closure) that defines the sort order. } sort.Stable(ps) } var ( // DefaultPageSort is the default sort func for pages in Hugo: // Order by Ordinal, Weight, Date, LinkTitle and then full file path. DefaultPageSort = func(p1, p2 Page) bool { o1, o2 := getOrdinals(p1, p2) if o1 != o2 && o1 != -1 && o2 != -1 { return o1 < o2 } // Weight0, as by the weight of the taxonomy entrie in the front matter. w01, w02 := getWeight0s(p1, p2) if w01 != w02 && w01 != -1 && w02 != -1 { return w01 < w02 } if p1.Weight() == p2.Weight() { if p1.Date().Unix() == p2.Date().Unix() { c := collatorStringCompare(func(p Page) string { return p.LinkTitle() }, p1, p2) if c == 0 { // This is the full normalized path, which will contain extension and any language code preserved, // which is what we want for sorting. return compare.LessStrings(p1.PathInfo().Path(), p2.PathInfo().Path()) } return c < 0 } return p1.Date().Unix() > p2.Date().Unix() } if p2.Weight() == 0 { return true } if p1.Weight() == 0 { return false } return p1.Weight() < p2.Weight() } lessPageLanguage = func(p1, p2 Page) bool { if p1.Language().Weight == p2.Language().Weight { if p1.Date().Unix() == p2.Date().Unix() { c := compare.Strings(p1.LinkTitle(), p2.LinkTitle()) if c == 0 { if p1.File() != nil && p2.File() != nil { return compare.LessStrings(p1.File().Filename(), p2.File().Filename()) } } return c < 0 } return p1.Date().Unix() > p2.Date().Unix() } if p2.Language().Weight == 0 { return true } if p1.Language().Weight == 0 { return false } return p1.Language().Weight < p2.Language().Weight } lessPageTitle = func(p1, p2 Page) bool { return collatorStringCompare(func(p Page) string { return p.Title() }, p1, p2) < 0 } lessPageLinkTitle = func(p1, p2 Page) bool { return collatorStringCompare(func(p Page) string { return p.LinkTitle() }, p1, p2) < 0 } lessPageDate = func(p1, p2 Page) bool { return p1.Date().Unix() < p2.Date().Unix() } lessPagePubDate = func(p1, p2 Page) bool { return p1.PublishDate().Unix() < p2.PublishDate().Unix() } lessPageDims = func(p1, p2 Page) bool { d1, d2 := GetSiteVector(p1), GetSiteVector(p2) if n := d1.Compare(d2); n != 0 { return n < 0 } // Fall back to the default sort order. return DefaultPageSort(p1, p2) } ) func (ps *pageSorter) Len() int { return len(ps.pages) } func (ps *pageSorter) Swap(i, j int) { ps.pages[i], ps.pages[j] = ps.pages[j], ps.pages[i] } // Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter. func (ps *pageSorter) Less(i, j int) bool { return ps.by(ps.pages[i], ps.pages[j]) } // Limit limits the number of pages returned to n. func (p Pages) Limit(n int) Pages { if len(p) > n { return p[0:n] } return p } var collatorStringSort = func(getString func(Page) string) func(p Pages) { return func(p Pages) { if len(p) == 0 { return } // Pages may be a mix of multiple languages, so we need to use the language // for the currently rendered Site. currentSite := p[0].Site().Current() coll := langs.GetCollator1(currentSite.Language()) coll.Lock() defer coll.Unlock() sort.SliceStable(p, func(i, j int) bool { return coll.CompareStrings(getString(p[i]), getString(p[j])) < 0 }) } } var collatorStringCompare = func(getString func(Page) string, p1, p2 Page) int { currentSite := p1.Site().Current() coll := langs.GetCollator1(currentSite.Language()) coll.Lock() c := coll.CompareStrings(getString(p1), getString(p2)) coll.Unlock() return c } var collatorStringLess = func(p Page) (less func(s1, s2 string) bool, close func()) { currentSite := p.Site().Current() // Make sure to use the second collator to prevent deadlocks. // See issue 11039. coll := langs.GetCollator2(currentSite.Language()) coll.Lock() return func(s1, s2 string) bool { return coll.CompareStrings(s1, s2) < 1 }, func() { coll.Unlock() } } // ByWeight sorts the Pages by weight and returns a copy. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByWeight() Pages { const key = "pageSort.ByWeight" pages, _ := spc.get(key, pageBy(DefaultPageSort).Sort, p) return pages } // SortByDefault sorts pages by the default sort. func SortByDefault(pages Pages) { pageBy(DefaultPageSort).Sort(pages) } // ByTitle sorts the Pages by title and returns a copy. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByTitle() Pages { const key = "pageSort.ByTitle" pages, _ := spc.get(key, collatorStringSort(func(p Page) string { return p.Title() }), p) return pages } // ByLinkTitle sorts the Pages by link title and returns a copy. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByLinkTitle() Pages { const key = "pageSort.ByLinkTitle" pages, _ := spc.get(key, collatorStringSort(func(p Page) string { return p.LinkTitle() }), p) return pages } // ByDate sorts the Pages by date and returns a copy. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByDate() Pages { const key = "pageSort.ByDate" pages, _ := spc.get(key, pageBy(lessPageDate).Sort, p) return pages } // ByPublishDate sorts the Pages by publish date and returns a copy. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByPublishDate() Pages { const key = "pageSort.ByPublishDate" pages, _ := spc.get(key, pageBy(lessPagePubDate).Sort, p) return pages } // ByExpiryDate sorts the Pages by publish date and returns a copy. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByExpiryDate() Pages { const key = "pageSort.ByExpiryDate" expDate := func(p1, p2 Page) bool { return p1.ExpiryDate().Unix() < p2.ExpiryDate().Unix() } pages, _ := spc.get(key, pageBy(expDate).Sort, p) return pages } // ByLastmod sorts the Pages by the last modification date and returns a copy. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByLastmod() Pages { const key = "pageSort.ByLastmod" date := func(p1, p2 Page) bool { return p1.Lastmod().Unix() < p2.Lastmod().Unix() } pages, _ := spc.get(key, pageBy(date).Sort, p) return pages } // ByLength sorts the Pages by length and returns a copy. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByLength(ctx context.Context) Pages { const key = "pageSort.ByLength" length := func(p1, p2 Page) bool { p1l, ok1 := p1.(resource.LengthProvider) p2l, ok2 := p2.(resource.LengthProvider) if !ok1 { return true } if !ok2 { return false } return p1l.Len(ctx) < p2l.Len(ctx) } pages, _ := spc.get(key, pageBy(length).Sort, p) return pages } // ByLanguage sorts the Pages by the language's Weight. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByLanguage() Pages { const key = "pageSort.ByLanguage" pages, _ := spc.get(key, pageBy(lessPageLanguage).Sort, p) return pages } // SortByLanguage sorts the pages by language. func SortByLanguage(pages Pages) { pageBy(lessPageLanguage).Sort(pages) } // SortByDims sorts the pages by sitesmatrix. func SortByDims(pages Pages) { pageBy(lessPageDims).Sort(pages) } // Reverse reverses the order in Pages and returns a copy. // // Adjacent invocations on the same receiver will return a cached result. // // This may safely be executed in parallel. func (p Pages) Reverse() Pages { const key = "pageSort.Reverse" reverseFunc := func(pages Pages) { for i, j := 0, len(pages)-1; i < j; i, j = i+1, j-1 { pages[i], pages[j] = pages[j], pages[i] } } pages, _ := spc.get(key, reverseFunc, p) return pages } // ByParam sorts the pages according to the given page Params key. // // Adjacent invocations on the same receiver with the same paramsKey will return a cached result. // // This may safely be executed in parallel. func (p Pages) ByParam(paramsKey any) Pages { if len(p) < 2 { return p } paramsKeyStr := cast.ToString(paramsKey) key := "pageSort.ByParam." + paramsKeyStr stringLess, close := collatorStringLess(p[0]) defer close() paramsKeyComparator := func(p1, p2 Page) bool { v1, _ := p1.Param(paramsKeyStr) v2, _ := p2.Param(paramsKeyStr) if v1 == nil { return false } if v2 == nil { return true } isNumeric := func(v any) bool { switch v.(type) { case uint8, uint16, uint32, uint64, int, int8, int16, int32, int64, float32, float64: return true default: return false } } if isNumeric(v1) && isNumeric(v2) { return cast.ToFloat64(v1) < cast.ToFloat64(v2) } s1 := cast.ToString(v1) s2 := cast.ToString(v2) return stringLess(s1, s2) } pages, _ := spc.get(key, pageBy(paramsKeyComparator).Sort, p) return pages }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/page/pages_cache.go
resources/page/pages_cache.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package page import ( "slices" "sync" ) type pageCacheEntry struct { in []Pages out Pages } func (entry pageCacheEntry) matches(pageLists []Pages) bool { if len(entry.in) != len(pageLists) { return false } for i, p := range pageLists { if !pagesEqual(p, entry.in[i]) { return false } } return true } type pageCache struct { sync.RWMutex m map[string][]pageCacheEntry } func newPageCache() *pageCache { return &pageCache{m: make(map[string][]pageCacheEntry)} } func (c *pageCache) clear() { c.Lock() defer c.Unlock() c.m = make(map[string][]pageCacheEntry) } // get/getP gets a Pages slice from the cache matching the given key and // all the provided Pages slices. // If none found in cache, a copy of the first slice is created. // // If an apply func is provided, that func is applied to the newly created copy. // // The getP variant' apply func takes a pointer to Pages. // // The cache and the execution of the apply func is protected by a RWMutex. func (c *pageCache) get(key string, apply func(p Pages), pageLists ...Pages) (Pages, bool) { return c.getP(key, func(p *Pages) { if apply != nil { apply(*p) } }, pageLists...) } func (c *pageCache) getP(key string, apply func(p *Pages), pageLists ...Pages) (Pages, bool) { c.RLock() if cached, ok := c.m[key]; ok { for _, entry := range cached { if entry.matches(pageLists) { c.RUnlock() return entry.out, true } } } c.RUnlock() c.Lock() defer c.Unlock() // double-check if cached, ok := c.m[key]; ok { for _, entry := range cached { if entry.matches(pageLists) { return entry.out, true } } } p := pageLists[0] pagesCopy := slices.Clone(p) if apply != nil { apply(&pagesCopy) } entry := pageCacheEntry{in: pageLists, out: pagesCopy} if v, ok := c.m[key]; ok { c.m[key] = append(v, entry) } else { c.m[key] = []pageCacheEntry{entry} } return pagesCopy, false } // pagesEqual returns whether p1 and p2 are equal. func pagesEqual(p1, p2 Pages) bool { if p1 == nil && p2 == nil { return true } if p1 == nil || p2 == nil { return false } if p1.Len() != p2.Len() { return false } if p1.Len() == 0 { return true } for i := range p1 { if p1[i] != p2[i] { return false } } return true }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/page/page_markup.go
resources/page/page_markup.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package page import ( "context" "html/template" "regexp" "strings" "unicode" "unicode/utf8" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/tpl" ) type Content interface { Content(context.Context) (template.HTML, error) ContentWithoutSummary(context.Context) (template.HTML, error) Summary(context.Context) (Summary, error) Plain(context.Context) string PlainWords(context.Context) []string WordCount(context.Context) int FuzzyWordCount(context.Context) int ReadingTime(context.Context) int Len(context.Context) int } type Markup interface { Render(context.Context) (Content, error) RenderString(ctx context.Context, args ...any) (template.HTML, error) RenderShortcodes(context.Context) (template.HTML, error) Fragments(context.Context) *tableofcontents.Fragments } var _ types.PrintableValueProvider = Summary{} const ( SummaryTypeAuto = "auto" SummaryTypeManual = "manual" SummaryTypeFrontMatter = "frontmatter" ) type Summary struct { Text template.HTML Type string // "auto", "manual" or "frontmatter" Truncated bool } func (s Summary) IsZero() bool { return s.Text == "" } func (s Summary) PrintableValue() any { return s.Text } var _ types.PrintableValueProvider = (*Summary)(nil) type HtmlSummary struct { source string SummaryLowHigh types.LowHigh[string] SummaryEndTag types.LowHigh[string] WrapperStart types.LowHigh[string] WrapperEnd types.LowHigh[string] Divider types.LowHigh[string] } func (s HtmlSummary) wrap(ss string) string { if s.WrapperStart.IsZero() { return ss } return s.source[s.WrapperStart.Low:s.WrapperStart.High] + ss + s.source[s.WrapperEnd.Low:s.WrapperEnd.High] } func (s HtmlSummary) wrapLeft(ss string) string { if s.WrapperStart.IsZero() { return ss } return s.source[s.WrapperStart.Low:s.WrapperStart.High] + ss } func (s HtmlSummary) Value(l types.LowHigh[string]) string { return s.source[l.Low:l.High] } func (s HtmlSummary) trimSpace(ss string) string { return strings.TrimSpace(ss) } func (s HtmlSummary) Content() string { if s.Divider.IsZero() { return s.trimSpace(s.source) } ss := s.source[:s.Divider.Low] ss += s.source[s.Divider.High:] return s.trimSpace(ss) } func (s HtmlSummary) Summary() string { if s.Divider.IsZero() { return s.trimSpace(s.wrap(s.Value(s.SummaryLowHigh))) } ss := s.source[s.SummaryLowHigh.Low:s.Divider.Low] if s.SummaryLowHigh.High > s.Divider.High { ss += s.source[s.Divider.High:s.SummaryLowHigh.High] } if !s.SummaryEndTag.IsZero() { ss += s.Value(s.SummaryEndTag) } return s.trimSpace(s.wrap(ss)) } func (s HtmlSummary) ContentWithoutSummary() string { if s.Divider.IsZero() { if s.SummaryLowHigh.Low == s.WrapperStart.High && s.SummaryLowHigh.High == s.WrapperEnd.Low { return "" } return s.trimSpace(s.wrapLeft(s.source[s.SummaryLowHigh.High:])) } if s.SummaryEndTag.IsZero() { return s.trimSpace(s.wrapLeft(s.source[s.Divider.High:])) } return s.trimSpace(s.wrapLeft(s.source[s.SummaryEndTag.High:])) } func (s HtmlSummary) Truncated() bool { return s.Summary() != s.Content() } func (s *HtmlSummary) resolveParagraphTagAndSetWrapper(mt media.Type) tagReStartEnd { ptag := startEndP switch mt.SubType { case media.DefaultContentTypes.AsciiDoc.SubType: ptag = startEndDiv case media.DefaultContentTypes.ReStructuredText.SubType: const markerStart = "<div class=\"document\">" const markerEnd = "</div>" i1 := strings.Index(s.source, markerStart) i2 := strings.LastIndex(s.source, markerEnd) if i1 > -1 && i2 > -1 { s.WrapperStart = types.LowHigh[string]{Low: 0, High: i1 + len(markerStart)} s.WrapperEnd = types.LowHigh[string]{Low: i2, High: len(s.source)} } } return ptag } // Avoid counting words that are most likely HTML tokens. var ( isProbablyHTMLTag = regexp.MustCompile(`^<\/?[A-Za-z]+>?$`) isProablyHTMLAttribute = regexp.MustCompile(`^[A-Za-z]+=["']`) ) func isProbablyHTMLToken(s string) bool { return s == ">" || isProbablyHTMLTag.MatchString(s) || isProablyHTMLAttribute.MatchString(s) } // ExtractSummaryFromHTML extracts a summary from the given HTML content. func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK bool) (result HtmlSummary) { result.source = input ptag := result.resolveParagraphTagAndSetWrapper(mt) if numWords <= 0 { return result } var count int countWord := func(word string) int { word = strings.TrimSpace(word) if len(word) == 0 { return 0 } if isProbablyHTMLToken(word) { return 0 } if isCJK { word = tpl.StripHTML(word) runeCount := utf8.RuneCountInString(word) if len(word) == runeCount { return 1 } else { return runeCount } } return 1 } high := len(input) if result.WrapperEnd.Low > 0 { high = result.WrapperEnd.Low } for j := result.WrapperStart.High; j < high; { s := input[j:] closingIndex := strings.Index(s, "</"+ptag.tagName+">") if closingIndex == -1 { break } s = s[:closingIndex] // Count the words in the current paragraph. var wi int for i, r := range s { if unicode.IsSpace(r) || (i+utf8.RuneLen(r) == len(s)) { word := s[wi:i] count += countWord(word) wi = i if count >= numWords { break } } } if count >= numWords { result.SummaryLowHigh = types.LowHigh[string]{ Low: result.WrapperStart.High, High: j + closingIndex + len(ptag.tagName) + 3, } return } j += closingIndex + len(ptag.tagName) + 2 } result.SummaryLowHigh = types.LowHigh[string]{ Low: result.WrapperStart.High, High: high, } return } // ExtractSummaryFromHTMLWithDivider extracts a summary from the given HTML content with // a manual summary divider. func ExtractSummaryFromHTMLWithDivider(mt media.Type, input, divider string) (result HtmlSummary) { result.source = input result.Divider.Low = strings.Index(input, divider) result.Divider.High = result.Divider.Low + len(divider) if result.Divider.Low == -1 { // No summary. return } ptag := result.resolveParagraphTagAndSetWrapper(mt) if !mt.IsHTML() { result.Divider, result.SummaryEndTag = expandSummaryDivider(result.source, ptag, result.Divider) } result.SummaryLowHigh = types.LowHigh[string]{ Low: result.WrapperStart.High, High: result.Divider.Low, } return } var ( pOrDiv = regexp.MustCompile(`<p[^>]?>|<div[^>]?>$`) startEndDiv = tagReStartEnd{ startEndOfString: regexp.MustCompile(`<div[^>]*?>$`), endEndOfString: regexp.MustCompile(`</div>$`), tagName: "div", } startEndP = tagReStartEnd{ startEndOfString: regexp.MustCompile(`<p[^>]*?>$`), endEndOfString: regexp.MustCompile(`</p>$`), tagName: "p", } ) type tagReStartEnd struct { startEndOfString *regexp.Regexp endEndOfString *regexp.Regexp tagName string } func expandSummaryDivider(s string, re tagReStartEnd, divider types.LowHigh[string]) (types.LowHigh[string], types.LowHigh[string]) { var endMarkup types.LowHigh[string] if divider.IsZero() { return divider, endMarkup } lo, hi := divider.Low, divider.High var preserveEndMarkup bool // Find the start of the paragraph. for i := lo - 1; i >= 0; i-- { if s[i] == '>' { if match := re.startEndOfString.FindString(s[:i+1]); match != "" { lo = i - len(match) + 1 break } if match := pOrDiv.FindString(s[:i+1]); match != "" { i -= len(match) - 1 continue } } r, _ := utf8.DecodeRuneInString(s[i:]) if !unicode.IsSpace(r) { preserveEndMarkup = true break } } divider.Low = lo // Now walk forward to the end of the paragraph. for ; hi < len(s); hi++ { if s[hi] != '>' { continue } if match := re.endEndOfString.FindString(s[:hi+1]); match != "" { hi++ break } } if preserveEndMarkup { endMarkup.Low = divider.High endMarkup.High = hi } else { divider.High = hi } // Consume trailing newline if any. if divider.High < len(s) && s[divider.High] == '\n' { divider.High++ } return divider, endMarkup }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/page/pages.go
resources/page/pages.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package page import ( "fmt" "math/rand" "github.com/gohugoio/hugo/compare" "github.com/gohugoio/hugo/resources/resource" ) // Pages is a slice of Page objects. This is the most common list type in Hugo. type Pages []Page // String returns a string representation of the list. // For internal use. func (ps Pages) String() string { return fmt.Sprintf("Pages(%d)", len(ps)) } // Used in tests. func (ps Pages) shuffle() { for i := range ps { j := rand.Intn(i + 1) ps[i], ps[j] = ps[j], ps[i] } } // ToResources wraps resource.ResourcesConverter. // For internal use. func (pages Pages) ToResources() resource.Resources { r := make(resource.Resources, len(pages)) for i, p := range pages { r[i] = p } return r } // ToPages tries to convert seq into Pages. func ToPages(seq any) (Pages, error) { if seq == nil { return Pages{}, nil } switch v := seq.(type) { case Pages: return v, nil case *Pages: return *(v), nil case WeightedPages: return v.Pages(), nil case PageGroup: return v.Pages, nil case []Page: pages := make(Pages, len(v)) copy(pages, v) return pages, nil case []any: pages := make(Pages, len(v)) success := true for i, vv := range v { p, ok := vv.(Page) if !ok { success = false break } pages[i] = p } if success { return pages, nil } } return nil, fmt.Errorf("cannot convert type %T to Pages", seq) } // Group groups the pages in in by key. // This implements collections.Grouper. func (p Pages) Group(key any, in any) (any, error) { pages, err := ToPages(in) if err != nil { return PageGroup{}, err } return PageGroup{Key: key, Pages: pages}, nil } // Len returns the number of pages in the list. func (p Pages) Len() int { return len(p) } // ProbablyEq wraps compare.ProbablyEqer // For internal use. func (pages Pages) ProbablyEq(other any) bool { otherPages, ok := other.(Pages) if !ok { return false } if len(pages) != len(otherPages) { return false } step := 1 for i := 0; i < len(pages); i += step { if !pages[i].Eq(otherPages[i]) { return false } if i > 50 { // This is most likely the same. step = 50 } } return true } // PagesFactory somehow creates some Pages. // We do a lot of lazy Pages initialization in Hugo, so we need a type. type PagesFactory func() Pages var ( _ resource.ResourcesConverter = Pages{} _ compare.ProbablyEqer = Pages{} )
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/page/page_matcher_test.go
resources/page/page_matcher_test.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package page import ( "path/filepath" "testing" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/hugolib/sitesmatrix" qt "github.com/frankban/quicktest" ) func TestPageMatcher(t *testing.T) { c := qt.New(t) developmentTestSite := testSite{h: hugo.NewInfo(testConfig{environment: "development"}, nil)} productionTestSite := testSite{h: hugo.NewInfo(testConfig{environment: "production"}, nil)} dec := cascadeConfigDecoder{} p1, p2, p3 := &testPage{path: "/p1", kind: "section", lang: "en", site: developmentTestSite}, &testPage{path: "p2", kind: "page", lang: "no", site: productionTestSite}, &testPage{path: "p3", kind: "page", lang: "en"} c.Run("Matches", func(c *qt.C) { m := PageMatcher{Kind: "section"} c.Assert(m.Matches(p1), qt.Equals, true) c.Assert(m.Matches(p2), qt.Equals, false) m = PageMatcher{Kind: "page"} c.Assert(m.Matches(p1), qt.Equals, false) c.Assert(m.Matches(p2), qt.Equals, true) c.Assert(m.Matches(p3), qt.Equals, true) m = PageMatcher{Kind: "page", Path: "/p2"} c.Assert(m.Matches(p1), qt.Equals, false) c.Assert(m.Matches(p2), qt.Equals, true) c.Assert(m.Matches(p3), qt.Equals, false) m = PageMatcher{Path: "/p*"} c.Assert(m.Matches(p1), qt.Equals, true) c.Assert(m.Matches(p2), qt.Equals, true) c.Assert(m.Matches(p3), qt.Equals, true) m = PageMatcher{Environment: "development"} c.Assert(m.Matches(p1), qt.Equals, true) c.Assert(m.Matches(p2), qt.Equals, false) c.Assert(m.Matches(p3), qt.Equals, false) m = PageMatcher{Environment: "production"} c.Assert(m.Matches(p1), qt.Equals, false) c.Assert(m.Matches(p2), qt.Equals, true) c.Assert(m.Matches(p3), qt.Equals, false) }) c.Run("Decode", func(c *qt.C) { var v PageMatcher c.Assert(dec.decodePageMatcher(map[string]any{"kind": "foo"}, &v), qt.Not(qt.IsNil)) c.Assert(dec.decodePageMatcher(map[string]any{"kind": "{foo,bar}"}, &v), qt.Not(qt.IsNil)) c.Assert(dec.decodePageMatcher(map[string]any{"kind": "taxonomy"}, &v), qt.IsNil) c.Assert(dec.decodePageMatcher(map[string]any{"kind": "{taxonomy,foo}"}, &v), qt.IsNil) c.Assert(dec.decodePageMatcher(map[string]any{"kind": "{taxonomy,term}"}, &v), qt.IsNil) c.Assert(dec.decodePageMatcher(map[string]any{"kind": "*"}, &v), qt.IsNil) c.Assert(dec.decodePageMatcher(map[string]any{"kind": "home", "path": filepath.FromSlash("/a/b/**")}, &v), qt.IsNil) c.Assert(v, qt.DeepEquals, PageMatcher{Kind: "home", Path: "/a/b/**"}) }) c.Run("mapToPageMatcherParamsConfig", func(c *qt.C) { fn := func(m map[string]any) PageMatcherParamsConfig { v, err := dec.mapToPageMatcherParamsConfig(m) c.Assert(err, qt.IsNil) return v } c.Assert(fn(map[string]any{"_target": map[string]any{"kind": "page"}, "foo": "bar"}), qt.DeepEquals, PageMatcherParamsConfig{ Params: maps.Params{}, Fields: maps.Params{ "foo": "bar", }, Target: PageMatcher{Path: "", Kind: "page", Lang: "", Environment: ""}, }) c.Assert(fn(map[string]any{"target": map[string]any{"kind": "page"}, "params": map[string]any{"foo": "bar"}}), qt.DeepEquals, PageMatcherParamsConfig{ Params: maps.Params{ "foo": "bar", }, Fields: maps.Params{}, Target: PageMatcher{Path: "", Kind: "page", Lang: "", Environment: ""}, }) }) } func TestDecodeCascadeConfig(t *testing.T) { c := qt.New(t) in := []map[string]any{ { "params": map[string]any{ "a": "av", }, "target": map[string]any{ "kind": "page", "Environment": "production", }, }, { "params": map[string]any{ "b": "bv", }, "target": map[string]any{ "kind": "page", }, }, } got, err := DecodeCascadeConfig(in) c.Assert(err, qt.IsNil) c.Assert(got, qt.IsNotNil) c.Assert(got.InitConfig(loggers.NewDefault(), nil, nil), qt.IsNil) c.Assert(got.c[0].Config.Cascades, qt.HasLen, 2) first := got.c[0].Config.Cascades[0] c.Assert(first, qt.DeepEquals, PageMatcherParamsConfig{ Params: maps.Params{ "a": "av", }, Fields: maps.Params{}, Target: PageMatcher{ Kind: "page", Sites: sitesmatrix.Sites{}, Environment: "production", }, }) c.Assert(got.c[0].SourceStructure, qt.DeepEquals, []PageMatcherParamsConfig{ { Params: maps.Params{"a": string("av")}, Fields: maps.Params{}, Target: PageMatcher{Kind: "page", Environment: "production"}, }, {Params: maps.Params{"b": string("bv")}, Fields: maps.Params{}, Target: PageMatcher{Kind: "page"}}, }) got, err = DecodeCascadeConfig(nil) c.Assert(err, qt.IsNil) c.Assert(got.InitConfig(loggers.NewDefault(), nil, nil), qt.IsNil) c.Assert(got.Len(), qt.Equals, 0) } func TestDecodeCascadeConfigWithSitesMatrix(t *testing.T) { c := qt.New(t) in := []map[string]any{ { "params": map[string]any{ "a": "av", }, "sites": map[string]any{ "matrix": map[string]any{ "roles": "pro", }, }, "target": map[string]any{ "kind": "page", "Environment": "production", "sites": map[string]any{ "matrix": map[string]any{ "languages": []string{"en", "{no,sv}"}, "versions": "v1**", }, }, }, }, } dims := sitesmatrix.NewTestingDimensions([]string{"en", "no", "sv"}, []string{"v1", "v2"}, []string{"free", "pro"}) got, err := DecodeCascadeConfig(in) c.Assert(err, qt.IsNil) c.Assert(got, qt.IsNotNil) c.Assert(got.InitConfig(loggers.NewDefault(), nil, dims), qt.IsNil) v := got.c[0].Config.Cascades[0] c.Assert(v.Target.Kind, qt.Equals, "page") c.Assert(v.Target.Environment, qt.Equals, "production") matrix := v.Target.SitesMatrixCompiled c.Assert(matrix.HasVector(sitesmatrix.Vector{0, 0, 0}), qt.IsTrue) // en, v1, free c.Assert(matrix.HasVector(sitesmatrix.Vector{0, 1, 0}), qt.IsFalse) // en, v2, free } type testConfig struct { environment string running bool workingDir string multihost bool multilingual bool } func (c testConfig) Environment() string { return c.environment } func (c testConfig) Running() bool { return c.running } func (c testConfig) WorkingDir() string { return c.workingDir } func (c testConfig) IsMultihost() bool { return c.multihost } func (c testConfig) IsMultilingual() bool { return c.multilingual } func TestIsGlobWithExtension(t *testing.T) { c := qt.New(t) c.Assert(isGlobWithExtension("index.md"), qt.Equals, true) c.Assert(isGlobWithExtension("foo/index.html"), qt.Equals, true) c.Assert(isGlobWithExtension("posts/page"), qt.Equals, false) c.Assert(isGlobWithExtension("pa.th/foo"), qt.Equals, false) c.Assert(isGlobWithExtension(""), qt.Equals, false) c.Assert(isGlobWithExtension("*.md?"), qt.Equals, true) c.Assert(isGlobWithExtension("*.md*"), qt.Equals, true) c.Assert(isGlobWithExtension("posts/*"), qt.Equals, false) c.Assert(isGlobWithExtension("*.md"), qt.Equals, true) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/resources/page/pages_prev_next_test.go
resources/page/pages_prev_next_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package page import ( "testing" qt "github.com/frankban/quicktest" "github.com/spf13/cast" ) type pagePNTestObject struct { path string weight int date string } var pagePNTestSources = []pagePNTestObject{ {"/section1/testpage1.md", 5, "2012-04-06"}, {"/section1/testpage2.md", 4, "2012-01-01"}, {"/section1/testpage3.md", 3, "2012-04-06"}, {"/section2/testpage4.md", 2, "2012-03-02"}, {"/section2/testpage5.md", 1, "2012-04-06"}, } func TestPrev(t *testing.T) { t.Parallel() c := qt.New(t) pages := preparePageGroupTestPages(t) c.Assert(pages.Prev(pages[3]), qt.Equals, pages[4]) c.Assert(pages.Prev(pages[1]), qt.Equals, pages[2]) c.Assert(pages.Prev(pages[4]), qt.IsNil) } func TestNext(t *testing.T) { t.Parallel() c := qt.New(t) pages := preparePageGroupTestPages(t) c.Assert(pages.Next(pages[0]), qt.IsNil) c.Assert(pages.Next(pages[1]), qt.Equals, pages[0]) c.Assert(pages.Next(pages[4]), qt.Equals, pages[3]) } func prepareWeightedPagesPrevNext(t *testing.T) WeightedPages { w := WeightedPages{} for _, src := range pagePNTestSources { p := newTestPage() p.path = src.path p.weight = src.weight p.date = cast.ToTime(src.date) p.pubDate = cast.ToTime(src.date) w = append(w, WeightedPage{Weight: p.weight, Page: p}) } w.Sort() return w } func TestWeightedPagesPrev(t *testing.T) { t.Parallel() c := qt.New(t) w := prepareWeightedPagesPrevNext(t) c.Assert(w.Prev(w[0].Page), qt.Equals, w[1].Page) c.Assert(w.Prev(w[1].Page), qt.Equals, w[2].Page) c.Assert(w.Prev(w[4].Page), qt.IsNil) } func TestWeightedPagesNext(t *testing.T) { t.Parallel() c := qt.New(t) w := prepareWeightedPagesPrevNext(t) c.Assert(w.Next(w[0].Page), qt.IsNil) c.Assert(w.Next(w[1].Page), qt.Equals, w[0].Page) c.Assert(w.Next(w[4].Page), qt.Equals, w[3].Page) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false