repo_name
stringlengths
8
38
pr_number
int64
3
47.1k
pr_title
stringlengths
8
175
pr_description
stringlengths
2
19.8k
βŒ€
author
null
date_created
stringlengths
25
25
date_merged
stringlengths
25
25
filepath
stringlengths
6
136
before_content
stringlengths
54
884k
βŒ€
after_content
stringlengths
56
884k
pr_author
stringlengths
3
21
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
comment
stringlengths
2
25.4k
comment_author
stringlengths
3
29
__index_level_0__
int64
0
5.1k
gohugoio/hugo
9,972
resources: Register MediaTypes before build
This fixes an issue with the `resources.GetRemote` call that fails for some media types, even when these are included in the default Hugo configuring. This is because the media types only get registered when running Hugo as a server and after the build is completed. Fixes: #9971
null
2022-06-03 09:17:53+00:00
2022-06-03 19:37:51+00:00
commands/hugo.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 commands defines and implements command-line commands and flags // used by Hugo. Commands and flags are implemented using Cobra. package commands import ( "context" "fmt" "io/ioutil" "os" "os/signal" "path/filepath" "runtime" "runtime/pprof" "runtime/trace" "strings" "sync/atomic" "syscall" "time" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/terminal" "github.com/gohugoio/hugo/hugolib/filesystems" "golang.org/x/sync/errgroup" "github.com/gohugoio/hugo/config" flag "github.com/spf13/pflag" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/livereload" "github.com/gohugoio/hugo/watcher" "github.com/spf13/afero" "github.com/spf13/cobra" "github.com/spf13/fsync" jww "github.com/spf13/jwalterweatherman" ) // The Response value from Execute. type Response struct { // The build Result will only be set in the hugo build command. Result *hugolib.HugoSites // Err is set when the command failed to execute. Err error // The command that was executed. Cmd *cobra.Command } // IsUserError returns true is the Response error is a user error rather than a // system error. func (r Response) IsUserError() bool { return r.Err != nil && isUserError(r.Err) } // Execute adds all child commands to the root command HugoCmd and sets flags appropriately. // The args are usually filled with os.Args[1:]. func Execute(args []string) Response { hugoCmd := newCommandsBuilder().addAll().build() cmd := hugoCmd.getCommand() cmd.SetArgs(args) c, err := cmd.ExecuteC() var resp Response if c == cmd && hugoCmd.c != nil { // Root command executed resp.Result = hugoCmd.c.hugo() } if err == nil { errCount := int(loggers.GlobalErrorCounter.Count()) if errCount > 0 { err = fmt.Errorf("logged %d errors", errCount) } else if resp.Result != nil { errCount = resp.Result.NumLogErrors() if errCount > 0 { err = fmt.Errorf("logged %d errors", errCount) } } } resp.Err = err resp.Cmd = c return resp } // InitializeConfig initializes a config file with sensible default configuration flags. func initializeConfig(mustHaveConfigFile, failOnInitErr, running bool, h *hugoBuilderCommon, f flagsToConfigHandler, cfgInit func(c *commandeer) error) (*commandeer, error) { c, err := newCommandeer(mustHaveConfigFile, failOnInitErr, running, h, f, cfgInit) if err != nil { return nil, err } return c, nil } func (c *commandeer) createLogger(cfg config.Provider) (loggers.Logger, error) { var ( logHandle = ioutil.Discard logThreshold = jww.LevelWarn logFile = cfg.GetString("logFile") outHandle = ioutil.Discard stdoutThreshold = jww.LevelWarn ) if !c.h.quiet { outHandle = os.Stdout } if c.h.verboseLog || c.h.logging || (c.h.logFile != "") { var err error if logFile != "" { logHandle, err = os.OpenFile(logFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return nil, newSystemError("Failed to open log file:", logFile, err) } } else { logHandle, err = ioutil.TempFile("", "hugo") if err != nil { return nil, newSystemError(err) } } } else if !c.h.quiet && cfg.GetBool("verbose") { stdoutThreshold = jww.LevelInfo } if cfg.GetBool("debug") { stdoutThreshold = jww.LevelDebug } if c.h.verboseLog { logThreshold = jww.LevelInfo if cfg.GetBool("debug") { logThreshold = jww.LevelDebug } } loggers.InitGlobalLogger(stdoutThreshold, logThreshold, outHandle, logHandle) helpers.InitLoggers() return loggers.NewLogger(stdoutThreshold, logThreshold, outHandle, logHandle, c.running), nil } func initializeFlags(cmd *cobra.Command, cfg config.Provider) { persFlagKeys := []string{ "debug", "verbose", "logFile", // Moved from vars } flagKeys := []string{ "cleanDestinationDir", "buildDrafts", "buildFuture", "buildExpired", "clock", "uglyURLs", "canonifyURLs", "enableRobotsTXT", "enableGitInfo", "pluralizeListTitles", "preserveTaxonomyNames", "ignoreCache", "forceSyncStatic", "noTimes", "noChmod", "noBuildLock", "ignoreVendorPaths", "templateMetrics", "templateMetricsHints", // Moved from vars. "baseURL", "buildWatch", "cacheDir", "cfgFile", "confirm", "contentDir", "debug", "destination", "disableKinds", "dryRun", "force", "gc", "printI18nWarnings", "printUnusedTemplates", "invalidateCDN", "layoutDir", "logFile", "maxDeletes", "quiet", "renderToMemory", "source", "target", "theme", "themesDir", "verbose", "verboseLog", "duplicateTargetPaths", } for _, key := range persFlagKeys { setValueFromFlag(cmd.PersistentFlags(), key, cfg, "", false) } for _, key := range flagKeys { setValueFromFlag(cmd.Flags(), key, cfg, "", false) } setValueFromFlag(cmd.Flags(), "minify", cfg, "minifyOutput", true) // Set some "config aliases" setValueFromFlag(cmd.Flags(), "destination", cfg, "publishDir", false) setValueFromFlag(cmd.Flags(), "printI18nWarnings", cfg, "logI18nWarnings", false) setValueFromFlag(cmd.Flags(), "printPathWarnings", cfg, "logPathWarnings", false) } func setValueFromFlag(flags *flag.FlagSet, key string, cfg config.Provider, targetKey string, force bool) { key = strings.TrimSpace(key) if (force && flags.Lookup(key) != nil) || flags.Changed(key) { f := flags.Lookup(key) configKey := key if targetKey != "" { configKey = targetKey } // Gotta love this API. switch f.Value.Type() { case "bool": bv, _ := flags.GetBool(key) cfg.Set(configKey, bv) case "string": cfg.Set(configKey, f.Value.String()) case "stringSlice": bv, _ := flags.GetStringSlice(key) cfg.Set(configKey, bv) case "int": iv, _ := flags.GetInt(key) cfg.Set(configKey, iv) default: panic(fmt.Sprintf("update switch with %s", f.Value.Type())) } } } func isTerminal() bool { return terminal.IsTerminal(os.Stdout) } func (c *commandeer) fullBuild(noBuildLock bool) error { var ( g errgroup.Group langCount map[string]uint64 ) if !c.h.quiet { fmt.Println("Start building sites … ") fmt.Println(hugo.BuildVersionString()) if isTerminal() { defer func() { fmt.Print(showCursor + clearLine) }() } } copyStaticFunc := func() error { cnt, err := c.copyStatic() if err != nil { return fmt.Errorf("Error copying static files: %w", err) } langCount = cnt return nil } buildSitesFunc := func() error { if err := c.buildSites(noBuildLock); err != nil { return fmt.Errorf("Error building site: %w", err) } return nil } // Do not copy static files and build sites in parallel if cleanDestinationDir is enabled. // This flag deletes all static resources in /public folder that are missing in /static, // and it does so at the end of copyStatic() call. if c.Cfg.GetBool("cleanDestinationDir") { if err := copyStaticFunc(); err != nil { return err } if err := buildSitesFunc(); err != nil { return err } } else { g.Go(copyStaticFunc) g.Go(buildSitesFunc) if err := g.Wait(); err != nil { return err } } for _, s := range c.hugo().Sites { s.ProcessingStats.Static = langCount[s.Language().Lang] } if c.h.gc { count, err := c.hugo().GC() if err != nil { return err } for _, s := range c.hugo().Sites { // We have no way of knowing what site the garbage belonged to. s.ProcessingStats.Cleaned = uint64(count) } } return nil } func (c *commandeer) initCPUProfile() (func(), error) { if c.h.cpuprofile == "" { return nil, nil } f, err := os.Create(c.h.cpuprofile) if err != nil { return nil, fmt.Errorf("failed to create CPU profile: %w", err) } if err := pprof.StartCPUProfile(f); err != nil { return nil, fmt.Errorf("failed to start CPU profile: %w", err) } return func() { pprof.StopCPUProfile() f.Close() }, nil } func (c *commandeer) initMemProfile() { if c.h.memprofile == "" { return } f, err := os.Create(c.h.memprofile) if err != nil { c.logger.Errorf("could not create memory profile: ", err) } defer f.Close() runtime.GC() // get up-to-date statistics if err := pprof.WriteHeapProfile(f); err != nil { c.logger.Errorf("could not write memory profile: ", err) } } func (c *commandeer) initTraceProfile() (func(), error) { if c.h.traceprofile == "" { return nil, nil } f, err := os.Create(c.h.traceprofile) if err != nil { return nil, fmt.Errorf("failed to create trace file: %w", err) } if err := trace.Start(f); err != nil { return nil, fmt.Errorf("failed to start trace: %w", err) } return func() { trace.Stop() f.Close() }, nil } func (c *commandeer) initMutexProfile() (func(), error) { if c.h.mutexprofile == "" { return nil, nil } f, err := os.Create(c.h.mutexprofile) if err != nil { return nil, err } runtime.SetMutexProfileFraction(1) return func() { pprof.Lookup("mutex").WriteTo(f, 0) f.Close() }, nil } func (c *commandeer) initMemTicker() func() { memticker := time.NewTicker(5 * time.Second) quit := make(chan struct{}) printMem := func() { var m runtime.MemStats runtime.ReadMemStats(&m) fmt.Printf("\n\nAlloc = %v\nTotalAlloc = %v\nSys = %v\nNumGC = %v\n\n", formatByteCount(m.Alloc), formatByteCount(m.TotalAlloc), formatByteCount(m.Sys), m.NumGC) } go func() { for { select { case <-memticker.C: printMem() case <-quit: memticker.Stop() printMem() return } } }() return func() { close(quit) } } func (c *commandeer) initProfiling() (func(), error) { stopCPUProf, err := c.initCPUProfile() if err != nil { return nil, err } stopMutexProf, err := c.initMutexProfile() if err != nil { return nil, err } stopTraceProf, err := c.initTraceProfile() if err != nil { return nil, err } var stopMemTicker func() if c.h.printm { stopMemTicker = c.initMemTicker() } return func() { c.initMemProfile() if stopCPUProf != nil { stopCPUProf() } if stopMutexProf != nil { stopMutexProf() } if stopTraceProf != nil { stopTraceProf() } if stopMemTicker != nil { stopMemTicker() } }, nil } func (c *commandeer) build() error { stopProfiling, err := c.initProfiling() if err != nil { return err } defer func() { if stopProfiling != nil { stopProfiling() } }() if err := c.fullBuild(false); err != nil { return err } if !c.h.quiet { fmt.Println() c.hugo().PrintProcessingStats(os.Stdout) fmt.Println() if createCounter, ok := c.publishDirFs.(hugofs.DuplicatesReporter); ok { dupes := createCounter.ReportDuplicates() if dupes != "" { c.logger.Warnln("Duplicate target paths:", dupes) } } unusedTemplates := c.hugo().Tmpl().(tpl.UnusedTemplatesProvider).UnusedTemplates() for _, unusedTemplate := range unusedTemplates { c.logger.Warnf("Template %s is unused, source file %s", unusedTemplate.Name(), unusedTemplate.Filename()) } } if c.h.buildWatch { watchDirs, err := c.getDirList() if err != nil { return err } baseWatchDir := c.Cfg.GetString("workingDir") rootWatchDirs := getRootWatchDirsStr(baseWatchDir, watchDirs) c.logger.Printf("Watching for changes in %s%s{%s}\n", baseWatchDir, helpers.FilePathSeparator, rootWatchDirs) c.logger.Println("Press Ctrl+C to stop") watcher, err := c.newWatcher(c.h.poll, watchDirs...) checkErr(c.Logger, err) defer watcher.Close() sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) <-sigs } return nil } func (c *commandeer) serverBuild() error { stopProfiling, err := c.initProfiling() if err != nil { return err } defer func() { if stopProfiling != nil { stopProfiling() } }() if err := c.fullBuild(false); err != nil { return err } // TODO(bep) Feedback? if !c.h.quiet { fmt.Println() c.hugo().PrintProcessingStats(os.Stdout) fmt.Println() } return nil } func (c *commandeer) copyStatic() (map[string]uint64, error) { m, err := c.doWithPublishDirs(c.copyStaticTo) if err == nil || os.IsNotExist(err) { return m, nil } return m, err } func (c *commandeer) doWithPublishDirs(f func(sourceFs *filesystems.SourceFilesystem) (uint64, error)) (map[string]uint64, error) { langCount := make(map[string]uint64) staticFilesystems := c.hugo().BaseFs.SourceFilesystems.Static if len(staticFilesystems) == 0 { c.logger.Infoln("No static directories found to sync") return langCount, nil } for lang, fs := range staticFilesystems { cnt, err := f(fs) if err != nil { return langCount, err } if lang == "" { // Not multihost for _, l := range c.languages { langCount[l.Lang] = cnt } } else { langCount[lang] = cnt } } return langCount, nil } type countingStatFs struct { afero.Fs statCounter uint64 } func (fs *countingStatFs) Stat(name string) (os.FileInfo, error) { f, err := fs.Fs.Stat(name) if err == nil { if !f.IsDir() { atomic.AddUint64(&fs.statCounter, 1) } } return f, err } func chmodFilter(dst, src os.FileInfo) bool { // Hugo publishes data from multiple sources, potentially // with overlapping directory structures. We cannot sync permissions // for directories as that would mean that we might end up with write-protected // directories inside /public. // One example of this would be syncing from the Go Module cache, // which have 0555 directories. return src.IsDir() } func (c *commandeer) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint64, error) { publishDir := helpers.FilePathSeparator if sourceFs.PublishFolder != "" { publishDir = filepath.Join(publishDir, sourceFs.PublishFolder) } fs := &countingStatFs{Fs: sourceFs.Fs} syncer := fsync.NewSyncer() syncer.NoTimes = c.Cfg.GetBool("noTimes") syncer.NoChmod = c.Cfg.GetBool("noChmod") syncer.ChmodFilter = chmodFilter syncer.SrcFs = fs syncer.DestFs = c.Fs.PublishDir if c.renderStaticToDisk { syncer.DestFs = c.Fs.PublishDirStatic } // Now that we are using a unionFs for the static directories // We can effectively clean the publishDir on initial sync syncer.Delete = c.Cfg.GetBool("cleanDestinationDir") if syncer.Delete { c.logger.Infoln("removing all files from destination that don't exist in static dirs") syncer.DeleteFilter = func(f os.FileInfo) bool { return f.IsDir() && strings.HasPrefix(f.Name(), ".") } } c.logger.Infoln("syncing static files to", publishDir) // because we are using a baseFs (to get the union right). // set sync src to root err := syncer.Sync(publishDir, helpers.FilePathSeparator) if err != nil { return 0, err } // Sync runs Stat 3 times for every source file (which sounds much) numFiles := fs.statCounter / 3 return numFiles, err } func (c *commandeer) firstPathSpec() *helpers.PathSpec { return c.hugo().Sites[0].PathSpec } func (c *commandeer) timeTrack(start time.Time, name string) { // Note the use of time.Since here and time.Now in the callers. // We have a htime.Sinnce, but that may be adjusted to the future, // and that does not make sense here, esp. when used before the // global Clock is initialized. elapsed := time.Since(start) c.logger.Printf("%s in %v ms", name, int(1000*elapsed.Seconds())) } // getDirList provides NewWatcher() with a list of directories to watch for changes. func (c *commandeer) getDirList() ([]string, error) { var filenames []string walkFn := func(path string, fi hugofs.FileMetaInfo, err error) error { if err != nil { c.logger.Errorln("walker: ", err) return nil } if fi.IsDir() { if fi.Name() == ".git" || fi.Name() == "node_modules" || fi.Name() == "bower_components" { return filepath.SkipDir } filenames = append(filenames, fi.Meta().Filename) } return nil } watchFiles := c.hugo().PathSpec.BaseFs.WatchDirs() for _, fi := range watchFiles { if !fi.IsDir() { filenames = append(filenames, fi.Meta().Filename) continue } w := hugofs.NewWalkway(hugofs.WalkwayConfig{Logger: c.logger, Info: fi, WalkFn: walkFn}) if err := w.Walk(); err != nil { c.logger.Errorln("walker: ", err) } } filenames = helpers.UniqueStringsSorted(filenames) return filenames, nil } func (c *commandeer) buildSites(noBuildLock bool) (err error) { return c.hugo().Build(hugolib.BuildCfg{NoBuildLock: noBuildLock}) } func (c *commandeer) handleBuildErr(err error, msg string) { c.buildErr = err c.logger.Errorln(msg + ": " + cleanErrorLog(err.Error())) } func (c *commandeer) rebuildSites(events []fsnotify.Event) error { if c.buildErr != nil { ferrs := herrors.UnwrapFileErrorsWithErrorContext(c.buildErr) for _, err := range ferrs { events = append(events, fsnotify.Event{Name: err.Position().Filename, Op: fsnotify.Write}) } } c.buildErr = nil visited := c.visitedURLs.PeekAllSet() if c.fastRenderMode { // Make sure we always render the home pages for _, l := range c.languages { langPath := c.hugo().PathSpec.GetLangSubDir(l.Lang) if langPath != "" { langPath = langPath + "/" } home := c.hugo().PathSpec.PrependBasePath("/"+langPath, false) visited[home] = true } } return c.hugo().Build(hugolib.BuildCfg{NoBuildLock: true, RecentlyVisited: visited, ErrRecovery: c.wasError}, events...) } func (c *commandeer) partialReRender(urls ...string) error { defer func() { c.wasError = false }() c.buildErr = nil visited := make(map[string]bool) for _, url := range urls { visited[url] = true } // Note: We do not set NoBuildLock as the file lock is not acquired at this stage. return c.hugo().Build(hugolib.BuildCfg{NoBuildLock: false, RecentlyVisited: visited, PartialReRender: true, ErrRecovery: c.wasError}) } func (c *commandeer) fullRebuild(changeType string) { if changeType == configChangeGoMod { // go.mod may be changed during the build itself, and // we really want to prevent superfluous builds. if !c.fullRebuildSem.TryAcquire(1) { return } c.fullRebuildSem.Release(1) } c.fullRebuildSem.Acquire(context.Background(), 1) go func() { defer c.fullRebuildSem.Release(1) c.printChangeDetected(changeType) defer func() { // Allow any file system events to arrive back. // This will block any rebuild on config changes for the // duration of the sleep. time.Sleep(2 * time.Second) }() defer c.timeTrack(time.Now(), "Rebuilt") c.commandeerHugoState = newCommandeerHugoState() err := c.loadConfig() if err != nil { // Set the processing on pause until the state is recovered. c.paused = true c.handleBuildErr(err, "Failed to reload config") } else { c.paused = false } if !c.paused { _, err := c.copyStatic() if err != nil { c.logger.Errorln(err) return } err = c.buildSites(true) if err != nil { c.logger.Errorln(err) } else if !c.h.buildWatch && !c.Cfg.GetBool("disableLiveReload") { livereload.ForceRefresh() } } }() } // newWatcher creates a new watcher to watch filesystem events. func (c *commandeer) newWatcher(pollIntervalStr string, dirList ...string) (*watcher.Batcher, error) { if runtime.GOOS == "darwin" { tweakLimit() } staticSyncer, err := newStaticSyncer(c) if err != nil { return nil, err } var pollInterval time.Duration poll := pollIntervalStr != "" if poll { pollInterval, err = types.ToDurationE(pollIntervalStr) if err != nil { return nil, fmt.Errorf("invalid value for flag poll: %s", err) } c.logger.Printf("Use watcher with poll interval %v", pollInterval) } if pollInterval == 0 { pollInterval = 500 * time.Millisecond } watcher, err := watcher.New(500*time.Millisecond, pollInterval, poll) if err != nil { return nil, err } spec := c.hugo().Deps.SourceSpec for _, d := range dirList { if d != "" { if spec.IgnoreFile(d) { continue } _ = watcher.Add(d) } } // Identifies changes to config (config.toml) files. configSet := make(map[string]bool) c.logger.Println("Watching for config changes in", strings.Join(c.configFiles, ", ")) for _, configFile := range c.configFiles { watcher.Add(configFile) configSet[configFile] = true } go func() { for { select { case evs := <-watcher.Events: unlock, err := c.buildLock() if err != nil { c.logger.Errorln("Failed to acquire a build lock: %s", err) return } c.handleEvents(watcher, staticSyncer, evs, configSet) if c.showErrorInBrowser && c.errCount() > 0 { // Need to reload browser to show the error livereload.ForceRefresh() } unlock() case err := <-watcher.Errors(): if err != nil && !os.IsNotExist(err) { c.logger.Errorln("Error while watching:", err) } } } }() return watcher, nil } func (c *commandeer) printChangeDetected(typ string) { msg := "\nChange" if typ != "" { msg += " of " + typ } msg += " detected, rebuilding site." c.logger.Println(msg) const layout = "2006-01-02 15:04:05.000 -0700" c.logger.Println(htime.Now().Format(layout)) } const ( configChangeConfig = "config file" configChangeGoMod = "go.mod file" ) func (c *commandeer) handleEvents(watcher *watcher.Batcher, staticSyncer *staticSyncer, evs []fsnotify.Event, configSet map[string]bool) { defer func() { c.wasError = false }() var isHandled bool for _, ev := range evs { isConfig := configSet[ev.Name] configChangeType := configChangeConfig if isConfig { if strings.Contains(ev.Name, "go.mod") { configChangeType = configChangeGoMod } } if !isConfig { // It may be one of the /config folders dirname := filepath.Dir(ev.Name) if dirname != "." && configSet[dirname] { isConfig = true } } if isConfig { isHandled = true if ev.Op&fsnotify.Chmod == fsnotify.Chmod { continue } if ev.Op&fsnotify.Remove == fsnotify.Remove || ev.Op&fsnotify.Rename == fsnotify.Rename { for _, configFile := range c.configFiles { counter := 0 for watcher.Add(configFile) != nil { counter++ if counter >= 100 { break } time.Sleep(100 * time.Millisecond) } } } // Config file(s) changed. Need full rebuild. c.fullRebuild(configChangeType) return } } if isHandled { return } if c.paused { // Wait for the server to get into a consistent state before // we continue with processing. return } if len(evs) > 50 { // This is probably a mass edit of the content dir. // Schedule a full rebuild for when it slows down. c.debounce(func() { c.fullRebuild("") }) return } c.logger.Infoln("Received System Events:", evs) staticEvents := []fsnotify.Event{} dynamicEvents := []fsnotify.Event{} filtered := []fsnotify.Event{} for _, ev := range evs { if c.hugo().ShouldSkipFileChangeEvent(ev) { continue } // Check the most specific first, i.e. files. contentMapped := c.hugo().ContentChanges.GetSymbolicLinkMappings(ev.Name) if len(contentMapped) > 0 { for _, mapped := range contentMapped { filtered = append(filtered, fsnotify.Event{Name: mapped, Op: ev.Op}) } continue } // Check for any symbolic directory mapping. dir, name := filepath.Split(ev.Name) contentMapped = c.hugo().ContentChanges.GetSymbolicLinkMappings(dir) if len(contentMapped) == 0 { filtered = append(filtered, ev) continue } for _, mapped := range contentMapped { mappedFilename := filepath.Join(mapped, name) filtered = append(filtered, fsnotify.Event{Name: mappedFilename, Op: ev.Op}) } } evs = filtered for _, ev := range evs { ext := filepath.Ext(ev.Name) baseName := filepath.Base(ev.Name) istemp := strings.HasSuffix(ext, "~") || (ext == ".swp") || // vim (ext == ".swx") || // vim (ext == ".tmp") || // generic temp file (ext == ".DS_Store") || // OSX Thumbnail baseName == "4913" || // vim strings.HasPrefix(ext, ".goutputstream") || // gnome strings.HasSuffix(ext, "jb_old___") || // intelliJ strings.HasSuffix(ext, "jb_tmp___") || // intelliJ strings.HasSuffix(ext, "jb_bak___") || // intelliJ strings.HasPrefix(ext, ".sb-") || // byword strings.HasPrefix(baseName, ".#") || // emacs strings.HasPrefix(baseName, "#") // emacs if istemp { continue } if c.hugo().Deps.SourceSpec.IgnoreFile(ev.Name) { continue } // Sometimes during rm -rf operations a '"": REMOVE' is triggered. Just ignore these if ev.Name == "" { continue } // Write and rename operations are often followed by CHMOD. // There may be valid use cases for rebuilding the site on CHMOD, // but that will require more complex logic than this simple conditional. // On OS X this seems to be related to Spotlight, see: // https://github.com/go-fsnotify/fsnotify/issues/15 // A workaround is to put your site(s) on the Spotlight exception list, // but that may be a little mysterious for most end users. // So, for now, we skip reload on CHMOD. // We do have to check for WRITE though. On slower laptops a Chmod // could be aggregated with other important events, and we still want // to rebuild on those if ev.Op&(fsnotify.Chmod|fsnotify.Write|fsnotify.Create) == fsnotify.Chmod { continue } walkAdder := func(path string, f hugofs.FileMetaInfo, err error) error { if f.IsDir() { c.logger.Println("adding created directory to watchlist", path) if err := watcher.Add(path); err != nil { return err } } else if !staticSyncer.isStatic(path) { // Hugo's rebuilding logic is entirely file based. When you drop a new folder into // /content on OSX, the above logic will handle future watching of those files, // but the initial CREATE is lost. dynamicEvents = append(dynamicEvents, fsnotify.Event{Name: path, Op: fsnotify.Create}) } return nil } // recursively add new directories to watch list // When mkdir -p is used, only the top directory triggers an event (at least on OSX) if ev.Op&fsnotify.Create == fsnotify.Create { if s, err := c.Fs.Source.Stat(ev.Name); err == nil && s.Mode().IsDir() { _ = helpers.SymbolicWalk(c.Fs.Source, ev.Name, walkAdder) } } if staticSyncer.isStatic(ev.Name) { staticEvents = append(staticEvents, ev) } else { dynamicEvents = append(dynamicEvents, ev) } } if len(staticEvents) > 0 { c.printChangeDetected("Static files") if c.Cfg.GetBool("forceSyncStatic") { c.logger.Printf("Syncing all static files\n") _, err := c.copyStatic() if err != nil { c.logger.Errorln("Error copying static files to publish dir:", err) return } } else { if err := staticSyncer.syncsStaticEvents(staticEvents); err != nil { c.logger.Errorln("Error syncing static files to publish dir:", err) return } } if !c.h.buildWatch && !c.Cfg.GetBool("disableLiveReload") { // Will block forever trying to write to a channel that nobody is reading if livereload isn't initialized // force refresh when more than one file if !c.wasError && len(staticEvents) == 1 { ev := staticEvents[0] path := c.hugo().BaseFs.SourceFilesystems.MakeStaticPathRelative(ev.Name) path = c.firstPathSpec().RelURL(helpers.ToSlashTrimLeading(path), false) livereload.RefreshPath(path) } else { livereload.ForceRefresh() } } } if len(dynamicEvents) > 0 { partitionedEvents := partitionDynamicEvents( c.firstPathSpec().BaseFs.SourceFilesystems, dynamicEvents) doLiveReload := !c.h.buildWatch && !c.Cfg.GetBool("disableLiveReload") onePageName := pickOneWriteOrCreatePath(partitionedEvents.ContentEvents) c.printChangeDetected("") c.changeDetector.PrepareNew() func() { defer c.timeTrack(time.Now(), "Total") if err := c.rebuildSites(dynamicEvents); err != nil { c.handleBuildErr(err, "Rebuild failed") } }() if doLiveReload { if len(partitionedEvents.ContentEvents) == 0 && len(partitionedEvents.AssetEvents) > 0 { if c.wasError { livereload.ForceRefresh() return } changed := c.changeDetector.changed() if c.changeDetector != nil && len(changed) == 0 { // Nothing has changed. return } else if len(changed) == 1 { pathToRefresh := c.firstPathSpec().RelURL(helpers.ToSlashTrimLeading(changed[0]), false) livereload.RefreshPath(pathToRefresh) } else { livereload.ForceRefresh() } } if len(partitionedEvents.ContentEvents) > 0 { navigate := c.Cfg.GetBool("navigateToChanged") // We have fetched the same page above, but it may have // changed. var p page.Page if navigate { if onePageName != "" { p = c.hugo().GetContentPage(onePageName) } } if p != nil { livereload.NavigateToPathForPort(p.RelPermalink(), p.Site().ServerPort()) } else { livereload.ForceRefresh() } } } } } // dynamicEvents contains events that is considered dynamic, as in "not static". // Both of these categories will trigger a new build, but the asset events // does not fit into the "navigate to changed" logic. type dynamicEvents struct { ContentEvents []fsnotify.Event AssetEvents []fsnotify.Event } func partitionDynamicEvents(sourceFs *filesystems.SourceFilesystems, events []fsnotify.Event) (de dynamicEvents) { for _, e := range events { if sourceFs.IsAsset(e.Name) { de.AssetEvents = append(de.AssetEvents, e) } else { de.ContentEvents = append(de.ContentEvents, e) } } return } func pickOneWriteOrCreatePath(events []fsnotify.Event) string { name := "" for _, ev := range events { if ev.Op&fsnotify.Write == fsnotify.Write || ev.Op&fsnotify.Create == fsnotify.Create { if files.IsIndexContentFile(ev.Name) { return ev.Name } if files.IsContentFile(ev.Name) { name = ev.Name } } } return name } func formatByteCount(b uint64) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) }
// 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 commands defines and implements command-line commands and flags // used by Hugo. Commands and flags are implemented using Cobra. package commands import ( "context" "fmt" "io/ioutil" "os" "os/signal" "path/filepath" "runtime" "runtime/pprof" "runtime/trace" "strings" "sync/atomic" "syscall" "time" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/terminal" "github.com/gohugoio/hugo/hugolib/filesystems" "golang.org/x/sync/errgroup" "github.com/gohugoio/hugo/config" flag "github.com/spf13/pflag" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/livereload" "github.com/gohugoio/hugo/watcher" "github.com/spf13/afero" "github.com/spf13/cobra" "github.com/spf13/fsync" jww "github.com/spf13/jwalterweatherman" ) // The Response value from Execute. type Response struct { // The build Result will only be set in the hugo build command. Result *hugolib.HugoSites // Err is set when the command failed to execute. Err error // The command that was executed. Cmd *cobra.Command } // IsUserError returns true is the Response error is a user error rather than a // system error. func (r Response) IsUserError() bool { return r.Err != nil && isUserError(r.Err) } // Execute adds all child commands to the root command HugoCmd and sets flags appropriately. // The args are usually filled with os.Args[1:]. func Execute(args []string) Response { hugoCmd := newCommandsBuilder().addAll().build() cmd := hugoCmd.getCommand() cmd.SetArgs(args) c, err := cmd.ExecuteC() var resp Response if c == cmd && hugoCmd.c != nil { // Root command executed resp.Result = hugoCmd.c.hugo() } if err == nil { errCount := int(loggers.GlobalErrorCounter.Count()) if errCount > 0 { err = fmt.Errorf("logged %d errors", errCount) } else if resp.Result != nil { errCount = resp.Result.NumLogErrors() if errCount > 0 { err = fmt.Errorf("logged %d errors", errCount) } } } resp.Err = err resp.Cmd = c return resp } // InitializeConfig initializes a config file with sensible default configuration flags. func initializeConfig(mustHaveConfigFile, failOnInitErr, running bool, h *hugoBuilderCommon, f flagsToConfigHandler, cfgInit func(c *commandeer) error) (*commandeer, error) { c, err := newCommandeer(mustHaveConfigFile, failOnInitErr, running, h, f, cfgInit) if err != nil { return nil, err } if h := c.hugoTry(); h != nil { for _, s := range h.Sites { s.RegisterMediaTypes() } } return c, nil } func (c *commandeer) createLogger(cfg config.Provider) (loggers.Logger, error) { var ( logHandle = ioutil.Discard logThreshold = jww.LevelWarn logFile = cfg.GetString("logFile") outHandle = ioutil.Discard stdoutThreshold = jww.LevelWarn ) if !c.h.quiet { outHandle = os.Stdout } if c.h.verboseLog || c.h.logging || (c.h.logFile != "") { var err error if logFile != "" { logHandle, err = os.OpenFile(logFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return nil, newSystemError("Failed to open log file:", logFile, err) } } else { logHandle, err = ioutil.TempFile("", "hugo") if err != nil { return nil, newSystemError(err) } } } else if !c.h.quiet && cfg.GetBool("verbose") { stdoutThreshold = jww.LevelInfo } if cfg.GetBool("debug") { stdoutThreshold = jww.LevelDebug } if c.h.verboseLog { logThreshold = jww.LevelInfo if cfg.GetBool("debug") { logThreshold = jww.LevelDebug } } loggers.InitGlobalLogger(stdoutThreshold, logThreshold, outHandle, logHandle) helpers.InitLoggers() return loggers.NewLogger(stdoutThreshold, logThreshold, outHandle, logHandle, c.running), nil } func initializeFlags(cmd *cobra.Command, cfg config.Provider) { persFlagKeys := []string{ "debug", "verbose", "logFile", // Moved from vars } flagKeys := []string{ "cleanDestinationDir", "buildDrafts", "buildFuture", "buildExpired", "clock", "uglyURLs", "canonifyURLs", "enableRobotsTXT", "enableGitInfo", "pluralizeListTitles", "preserveTaxonomyNames", "ignoreCache", "forceSyncStatic", "noTimes", "noChmod", "noBuildLock", "ignoreVendorPaths", "templateMetrics", "templateMetricsHints", // Moved from vars. "baseURL", "buildWatch", "cacheDir", "cfgFile", "confirm", "contentDir", "debug", "destination", "disableKinds", "dryRun", "force", "gc", "printI18nWarnings", "printUnusedTemplates", "invalidateCDN", "layoutDir", "logFile", "maxDeletes", "quiet", "renderToMemory", "source", "target", "theme", "themesDir", "verbose", "verboseLog", "duplicateTargetPaths", } for _, key := range persFlagKeys { setValueFromFlag(cmd.PersistentFlags(), key, cfg, "", false) } for _, key := range flagKeys { setValueFromFlag(cmd.Flags(), key, cfg, "", false) } setValueFromFlag(cmd.Flags(), "minify", cfg, "minifyOutput", true) // Set some "config aliases" setValueFromFlag(cmd.Flags(), "destination", cfg, "publishDir", false) setValueFromFlag(cmd.Flags(), "printI18nWarnings", cfg, "logI18nWarnings", false) setValueFromFlag(cmd.Flags(), "printPathWarnings", cfg, "logPathWarnings", false) } func setValueFromFlag(flags *flag.FlagSet, key string, cfg config.Provider, targetKey string, force bool) { key = strings.TrimSpace(key) if (force && flags.Lookup(key) != nil) || flags.Changed(key) { f := flags.Lookup(key) configKey := key if targetKey != "" { configKey = targetKey } // Gotta love this API. switch f.Value.Type() { case "bool": bv, _ := flags.GetBool(key) cfg.Set(configKey, bv) case "string": cfg.Set(configKey, f.Value.String()) case "stringSlice": bv, _ := flags.GetStringSlice(key) cfg.Set(configKey, bv) case "int": iv, _ := flags.GetInt(key) cfg.Set(configKey, iv) default: panic(fmt.Sprintf("update switch with %s", f.Value.Type())) } } } func isTerminal() bool { return terminal.IsTerminal(os.Stdout) } func (c *commandeer) fullBuild(noBuildLock bool) error { var ( g errgroup.Group langCount map[string]uint64 ) if !c.h.quiet { fmt.Println("Start building sites … ") fmt.Println(hugo.BuildVersionString()) if isTerminal() { defer func() { fmt.Print(showCursor + clearLine) }() } } copyStaticFunc := func() error { cnt, err := c.copyStatic() if err != nil { return fmt.Errorf("Error copying static files: %w", err) } langCount = cnt return nil } buildSitesFunc := func() error { if err := c.buildSites(noBuildLock); err != nil { return fmt.Errorf("Error building site: %w", err) } return nil } // Do not copy static files and build sites in parallel if cleanDestinationDir is enabled. // This flag deletes all static resources in /public folder that are missing in /static, // and it does so at the end of copyStatic() call. if c.Cfg.GetBool("cleanDestinationDir") { if err := copyStaticFunc(); err != nil { return err } if err := buildSitesFunc(); err != nil { return err } } else { g.Go(copyStaticFunc) g.Go(buildSitesFunc) if err := g.Wait(); err != nil { return err } } for _, s := range c.hugo().Sites { s.ProcessingStats.Static = langCount[s.Language().Lang] } if c.h.gc { count, err := c.hugo().GC() if err != nil { return err } for _, s := range c.hugo().Sites { // We have no way of knowing what site the garbage belonged to. s.ProcessingStats.Cleaned = uint64(count) } } return nil } func (c *commandeer) initCPUProfile() (func(), error) { if c.h.cpuprofile == "" { return nil, nil } f, err := os.Create(c.h.cpuprofile) if err != nil { return nil, fmt.Errorf("failed to create CPU profile: %w", err) } if err := pprof.StartCPUProfile(f); err != nil { return nil, fmt.Errorf("failed to start CPU profile: %w", err) } return func() { pprof.StopCPUProfile() f.Close() }, nil } func (c *commandeer) initMemProfile() { if c.h.memprofile == "" { return } f, err := os.Create(c.h.memprofile) if err != nil { c.logger.Errorf("could not create memory profile: ", err) } defer f.Close() runtime.GC() // get up-to-date statistics if err := pprof.WriteHeapProfile(f); err != nil { c.logger.Errorf("could not write memory profile: ", err) } } func (c *commandeer) initTraceProfile() (func(), error) { if c.h.traceprofile == "" { return nil, nil } f, err := os.Create(c.h.traceprofile) if err != nil { return nil, fmt.Errorf("failed to create trace file: %w", err) } if err := trace.Start(f); err != nil { return nil, fmt.Errorf("failed to start trace: %w", err) } return func() { trace.Stop() f.Close() }, nil } func (c *commandeer) initMutexProfile() (func(), error) { if c.h.mutexprofile == "" { return nil, nil } f, err := os.Create(c.h.mutexprofile) if err != nil { return nil, err } runtime.SetMutexProfileFraction(1) return func() { pprof.Lookup("mutex").WriteTo(f, 0) f.Close() }, nil } func (c *commandeer) initMemTicker() func() { memticker := time.NewTicker(5 * time.Second) quit := make(chan struct{}) printMem := func() { var m runtime.MemStats runtime.ReadMemStats(&m) fmt.Printf("\n\nAlloc = %v\nTotalAlloc = %v\nSys = %v\nNumGC = %v\n\n", formatByteCount(m.Alloc), formatByteCount(m.TotalAlloc), formatByteCount(m.Sys), m.NumGC) } go func() { for { select { case <-memticker.C: printMem() case <-quit: memticker.Stop() printMem() return } } }() return func() { close(quit) } } func (c *commandeer) initProfiling() (func(), error) { stopCPUProf, err := c.initCPUProfile() if err != nil { return nil, err } stopMutexProf, err := c.initMutexProfile() if err != nil { return nil, err } stopTraceProf, err := c.initTraceProfile() if err != nil { return nil, err } var stopMemTicker func() if c.h.printm { stopMemTicker = c.initMemTicker() } return func() { c.initMemProfile() if stopCPUProf != nil { stopCPUProf() } if stopMutexProf != nil { stopMutexProf() } if stopTraceProf != nil { stopTraceProf() } if stopMemTicker != nil { stopMemTicker() } }, nil } func (c *commandeer) build() error { stopProfiling, err := c.initProfiling() if err != nil { return err } defer func() { if stopProfiling != nil { stopProfiling() } }() if err := c.fullBuild(false); err != nil { return err } if !c.h.quiet { fmt.Println() c.hugo().PrintProcessingStats(os.Stdout) fmt.Println() if createCounter, ok := c.publishDirFs.(hugofs.DuplicatesReporter); ok { dupes := createCounter.ReportDuplicates() if dupes != "" { c.logger.Warnln("Duplicate target paths:", dupes) } } unusedTemplates := c.hugo().Tmpl().(tpl.UnusedTemplatesProvider).UnusedTemplates() for _, unusedTemplate := range unusedTemplates { c.logger.Warnf("Template %s is unused, source file %s", unusedTemplate.Name(), unusedTemplate.Filename()) } } if c.h.buildWatch { watchDirs, err := c.getDirList() if err != nil { return err } baseWatchDir := c.Cfg.GetString("workingDir") rootWatchDirs := getRootWatchDirsStr(baseWatchDir, watchDirs) c.logger.Printf("Watching for changes in %s%s{%s}\n", baseWatchDir, helpers.FilePathSeparator, rootWatchDirs) c.logger.Println("Press Ctrl+C to stop") watcher, err := c.newWatcher(c.h.poll, watchDirs...) checkErr(c.Logger, err) defer watcher.Close() sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) <-sigs } return nil } func (c *commandeer) serverBuild() error { stopProfiling, err := c.initProfiling() if err != nil { return err } defer func() { if stopProfiling != nil { stopProfiling() } }() if err := c.fullBuild(false); err != nil { return err } // TODO(bep) Feedback? if !c.h.quiet { fmt.Println() c.hugo().PrintProcessingStats(os.Stdout) fmt.Println() } return nil } func (c *commandeer) copyStatic() (map[string]uint64, error) { m, err := c.doWithPublishDirs(c.copyStaticTo) if err == nil || os.IsNotExist(err) { return m, nil } return m, err } func (c *commandeer) doWithPublishDirs(f func(sourceFs *filesystems.SourceFilesystem) (uint64, error)) (map[string]uint64, error) { langCount := make(map[string]uint64) staticFilesystems := c.hugo().BaseFs.SourceFilesystems.Static if len(staticFilesystems) == 0 { c.logger.Infoln("No static directories found to sync") return langCount, nil } for lang, fs := range staticFilesystems { cnt, err := f(fs) if err != nil { return langCount, err } if lang == "" { // Not multihost for _, l := range c.languages { langCount[l.Lang] = cnt } } else { langCount[lang] = cnt } } return langCount, nil } type countingStatFs struct { afero.Fs statCounter uint64 } func (fs *countingStatFs) Stat(name string) (os.FileInfo, error) { f, err := fs.Fs.Stat(name) if err == nil { if !f.IsDir() { atomic.AddUint64(&fs.statCounter, 1) } } return f, err } func chmodFilter(dst, src os.FileInfo) bool { // Hugo publishes data from multiple sources, potentially // with overlapping directory structures. We cannot sync permissions // for directories as that would mean that we might end up with write-protected // directories inside /public. // One example of this would be syncing from the Go Module cache, // which have 0555 directories. return src.IsDir() } func (c *commandeer) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint64, error) { publishDir := helpers.FilePathSeparator if sourceFs.PublishFolder != "" { publishDir = filepath.Join(publishDir, sourceFs.PublishFolder) } fs := &countingStatFs{Fs: sourceFs.Fs} syncer := fsync.NewSyncer() syncer.NoTimes = c.Cfg.GetBool("noTimes") syncer.NoChmod = c.Cfg.GetBool("noChmod") syncer.ChmodFilter = chmodFilter syncer.SrcFs = fs syncer.DestFs = c.Fs.PublishDir if c.renderStaticToDisk { syncer.DestFs = c.Fs.PublishDirStatic } // Now that we are using a unionFs for the static directories // We can effectively clean the publishDir on initial sync syncer.Delete = c.Cfg.GetBool("cleanDestinationDir") if syncer.Delete { c.logger.Infoln("removing all files from destination that don't exist in static dirs") syncer.DeleteFilter = func(f os.FileInfo) bool { return f.IsDir() && strings.HasPrefix(f.Name(), ".") } } c.logger.Infoln("syncing static files to", publishDir) // because we are using a baseFs (to get the union right). // set sync src to root err := syncer.Sync(publishDir, helpers.FilePathSeparator) if err != nil { return 0, err } // Sync runs Stat 3 times for every source file (which sounds much) numFiles := fs.statCounter / 3 return numFiles, err } func (c *commandeer) firstPathSpec() *helpers.PathSpec { return c.hugo().Sites[0].PathSpec } func (c *commandeer) timeTrack(start time.Time, name string) { // Note the use of time.Since here and time.Now in the callers. // We have a htime.Sinnce, but that may be adjusted to the future, // and that does not make sense here, esp. when used before the // global Clock is initialized. elapsed := time.Since(start) c.logger.Printf("%s in %v ms", name, int(1000*elapsed.Seconds())) } // getDirList provides NewWatcher() with a list of directories to watch for changes. func (c *commandeer) getDirList() ([]string, error) { var filenames []string walkFn := func(path string, fi hugofs.FileMetaInfo, err error) error { if err != nil { c.logger.Errorln("walker: ", err) return nil } if fi.IsDir() { if fi.Name() == ".git" || fi.Name() == "node_modules" || fi.Name() == "bower_components" { return filepath.SkipDir } filenames = append(filenames, fi.Meta().Filename) } return nil } watchFiles := c.hugo().PathSpec.BaseFs.WatchDirs() for _, fi := range watchFiles { if !fi.IsDir() { filenames = append(filenames, fi.Meta().Filename) continue } w := hugofs.NewWalkway(hugofs.WalkwayConfig{Logger: c.logger, Info: fi, WalkFn: walkFn}) if err := w.Walk(); err != nil { c.logger.Errorln("walker: ", err) } } filenames = helpers.UniqueStringsSorted(filenames) return filenames, nil } func (c *commandeer) buildSites(noBuildLock bool) (err error) { return c.hugo().Build(hugolib.BuildCfg{NoBuildLock: noBuildLock}) } func (c *commandeer) handleBuildErr(err error, msg string) { c.buildErr = err c.logger.Errorln(msg + ": " + cleanErrorLog(err.Error())) } func (c *commandeer) rebuildSites(events []fsnotify.Event) error { if c.buildErr != nil { ferrs := herrors.UnwrapFileErrorsWithErrorContext(c.buildErr) for _, err := range ferrs { events = append(events, fsnotify.Event{Name: err.Position().Filename, Op: fsnotify.Write}) } } c.buildErr = nil visited := c.visitedURLs.PeekAllSet() if c.fastRenderMode { // Make sure we always render the home pages for _, l := range c.languages { langPath := c.hugo().PathSpec.GetLangSubDir(l.Lang) if langPath != "" { langPath = langPath + "/" } home := c.hugo().PathSpec.PrependBasePath("/"+langPath, false) visited[home] = true } } return c.hugo().Build(hugolib.BuildCfg{NoBuildLock: true, RecentlyVisited: visited, ErrRecovery: c.wasError}, events...) } func (c *commandeer) partialReRender(urls ...string) error { defer func() { c.wasError = false }() c.buildErr = nil visited := make(map[string]bool) for _, url := range urls { visited[url] = true } // Note: We do not set NoBuildLock as the file lock is not acquired at this stage. return c.hugo().Build(hugolib.BuildCfg{NoBuildLock: false, RecentlyVisited: visited, PartialReRender: true, ErrRecovery: c.wasError}) } func (c *commandeer) fullRebuild(changeType string) { if changeType == configChangeGoMod { // go.mod may be changed during the build itself, and // we really want to prevent superfluous builds. if !c.fullRebuildSem.TryAcquire(1) { return } c.fullRebuildSem.Release(1) } c.fullRebuildSem.Acquire(context.Background(), 1) go func() { defer c.fullRebuildSem.Release(1) c.printChangeDetected(changeType) defer func() { // Allow any file system events to arrive back. // This will block any rebuild on config changes for the // duration of the sleep. time.Sleep(2 * time.Second) }() defer c.timeTrack(time.Now(), "Rebuilt") c.commandeerHugoState = newCommandeerHugoState() err := c.loadConfig() if err != nil { // Set the processing on pause until the state is recovered. c.paused = true c.handleBuildErr(err, "Failed to reload config") } else { c.paused = false } if !c.paused { _, err := c.copyStatic() if err != nil { c.logger.Errorln(err) return } err = c.buildSites(true) if err != nil { c.logger.Errorln(err) } else if !c.h.buildWatch && !c.Cfg.GetBool("disableLiveReload") { livereload.ForceRefresh() } } }() } // newWatcher creates a new watcher to watch filesystem events. func (c *commandeer) newWatcher(pollIntervalStr string, dirList ...string) (*watcher.Batcher, error) { if runtime.GOOS == "darwin" { tweakLimit() } staticSyncer, err := newStaticSyncer(c) if err != nil { return nil, err } var pollInterval time.Duration poll := pollIntervalStr != "" if poll { pollInterval, err = types.ToDurationE(pollIntervalStr) if err != nil { return nil, fmt.Errorf("invalid value for flag poll: %s", err) } c.logger.Printf("Use watcher with poll interval %v", pollInterval) } if pollInterval == 0 { pollInterval = 500 * time.Millisecond } watcher, err := watcher.New(500*time.Millisecond, pollInterval, poll) if err != nil { return nil, err } spec := c.hugo().Deps.SourceSpec for _, d := range dirList { if d != "" { if spec.IgnoreFile(d) { continue } _ = watcher.Add(d) } } // Identifies changes to config (config.toml) files. configSet := make(map[string]bool) c.logger.Println("Watching for config changes in", strings.Join(c.configFiles, ", ")) for _, configFile := range c.configFiles { watcher.Add(configFile) configSet[configFile] = true } go func() { for { select { case evs := <-watcher.Events: unlock, err := c.buildLock() if err != nil { c.logger.Errorln("Failed to acquire a build lock: %s", err) return } c.handleEvents(watcher, staticSyncer, evs, configSet) if c.showErrorInBrowser && c.errCount() > 0 { // Need to reload browser to show the error livereload.ForceRefresh() } unlock() case err := <-watcher.Errors(): if err != nil && !os.IsNotExist(err) { c.logger.Errorln("Error while watching:", err) } } } }() return watcher, nil } func (c *commandeer) printChangeDetected(typ string) { msg := "\nChange" if typ != "" { msg += " of " + typ } msg += " detected, rebuilding site." c.logger.Println(msg) const layout = "2006-01-02 15:04:05.000 -0700" c.logger.Println(htime.Now().Format(layout)) } const ( configChangeConfig = "config file" configChangeGoMod = "go.mod file" ) func (c *commandeer) handleEvents(watcher *watcher.Batcher, staticSyncer *staticSyncer, evs []fsnotify.Event, configSet map[string]bool) { defer func() { c.wasError = false }() var isHandled bool for _, ev := range evs { isConfig := configSet[ev.Name] configChangeType := configChangeConfig if isConfig { if strings.Contains(ev.Name, "go.mod") { configChangeType = configChangeGoMod } } if !isConfig { // It may be one of the /config folders dirname := filepath.Dir(ev.Name) if dirname != "." && configSet[dirname] { isConfig = true } } if isConfig { isHandled = true if ev.Op&fsnotify.Chmod == fsnotify.Chmod { continue } if ev.Op&fsnotify.Remove == fsnotify.Remove || ev.Op&fsnotify.Rename == fsnotify.Rename { for _, configFile := range c.configFiles { counter := 0 for watcher.Add(configFile) != nil { counter++ if counter >= 100 { break } time.Sleep(100 * time.Millisecond) } } } // Config file(s) changed. Need full rebuild. c.fullRebuild(configChangeType) return } } if isHandled { return } if c.paused { // Wait for the server to get into a consistent state before // we continue with processing. return } if len(evs) > 50 { // This is probably a mass edit of the content dir. // Schedule a full rebuild for when it slows down. c.debounce(func() { c.fullRebuild("") }) return } c.logger.Infoln("Received System Events:", evs) staticEvents := []fsnotify.Event{} dynamicEvents := []fsnotify.Event{} filtered := []fsnotify.Event{} for _, ev := range evs { if c.hugo().ShouldSkipFileChangeEvent(ev) { continue } // Check the most specific first, i.e. files. contentMapped := c.hugo().ContentChanges.GetSymbolicLinkMappings(ev.Name) if len(contentMapped) > 0 { for _, mapped := range contentMapped { filtered = append(filtered, fsnotify.Event{Name: mapped, Op: ev.Op}) } continue } // Check for any symbolic directory mapping. dir, name := filepath.Split(ev.Name) contentMapped = c.hugo().ContentChanges.GetSymbolicLinkMappings(dir) if len(contentMapped) == 0 { filtered = append(filtered, ev) continue } for _, mapped := range contentMapped { mappedFilename := filepath.Join(mapped, name) filtered = append(filtered, fsnotify.Event{Name: mappedFilename, Op: ev.Op}) } } evs = filtered for _, ev := range evs { ext := filepath.Ext(ev.Name) baseName := filepath.Base(ev.Name) istemp := strings.HasSuffix(ext, "~") || (ext == ".swp") || // vim (ext == ".swx") || // vim (ext == ".tmp") || // generic temp file (ext == ".DS_Store") || // OSX Thumbnail baseName == "4913" || // vim strings.HasPrefix(ext, ".goutputstream") || // gnome strings.HasSuffix(ext, "jb_old___") || // intelliJ strings.HasSuffix(ext, "jb_tmp___") || // intelliJ strings.HasSuffix(ext, "jb_bak___") || // intelliJ strings.HasPrefix(ext, ".sb-") || // byword strings.HasPrefix(baseName, ".#") || // emacs strings.HasPrefix(baseName, "#") // emacs if istemp { continue } if c.hugo().Deps.SourceSpec.IgnoreFile(ev.Name) { continue } // Sometimes during rm -rf operations a '"": REMOVE' is triggered. Just ignore these if ev.Name == "" { continue } // Write and rename operations are often followed by CHMOD. // There may be valid use cases for rebuilding the site on CHMOD, // but that will require more complex logic than this simple conditional. // On OS X this seems to be related to Spotlight, see: // https://github.com/go-fsnotify/fsnotify/issues/15 // A workaround is to put your site(s) on the Spotlight exception list, // but that may be a little mysterious for most end users. // So, for now, we skip reload on CHMOD. // We do have to check for WRITE though. On slower laptops a Chmod // could be aggregated with other important events, and we still want // to rebuild on those if ev.Op&(fsnotify.Chmod|fsnotify.Write|fsnotify.Create) == fsnotify.Chmod { continue } walkAdder := func(path string, f hugofs.FileMetaInfo, err error) error { if f.IsDir() { c.logger.Println("adding created directory to watchlist", path) if err := watcher.Add(path); err != nil { return err } } else if !staticSyncer.isStatic(path) { // Hugo's rebuilding logic is entirely file based. When you drop a new folder into // /content on OSX, the above logic will handle future watching of those files, // but the initial CREATE is lost. dynamicEvents = append(dynamicEvents, fsnotify.Event{Name: path, Op: fsnotify.Create}) } return nil } // recursively add new directories to watch list // When mkdir -p is used, only the top directory triggers an event (at least on OSX) if ev.Op&fsnotify.Create == fsnotify.Create { if s, err := c.Fs.Source.Stat(ev.Name); err == nil && s.Mode().IsDir() { _ = helpers.SymbolicWalk(c.Fs.Source, ev.Name, walkAdder) } } if staticSyncer.isStatic(ev.Name) { staticEvents = append(staticEvents, ev) } else { dynamicEvents = append(dynamicEvents, ev) } } if len(staticEvents) > 0 { c.printChangeDetected("Static files") if c.Cfg.GetBool("forceSyncStatic") { c.logger.Printf("Syncing all static files\n") _, err := c.copyStatic() if err != nil { c.logger.Errorln("Error copying static files to publish dir:", err) return } } else { if err := staticSyncer.syncsStaticEvents(staticEvents); err != nil { c.logger.Errorln("Error syncing static files to publish dir:", err) return } } if !c.h.buildWatch && !c.Cfg.GetBool("disableLiveReload") { // Will block forever trying to write to a channel that nobody is reading if livereload isn't initialized // force refresh when more than one file if !c.wasError && len(staticEvents) == 1 { ev := staticEvents[0] path := c.hugo().BaseFs.SourceFilesystems.MakeStaticPathRelative(ev.Name) path = c.firstPathSpec().RelURL(helpers.ToSlashTrimLeading(path), false) livereload.RefreshPath(path) } else { livereload.ForceRefresh() } } } if len(dynamicEvents) > 0 { partitionedEvents := partitionDynamicEvents( c.firstPathSpec().BaseFs.SourceFilesystems, dynamicEvents) doLiveReload := !c.h.buildWatch && !c.Cfg.GetBool("disableLiveReload") onePageName := pickOneWriteOrCreatePath(partitionedEvents.ContentEvents) c.printChangeDetected("") c.changeDetector.PrepareNew() func() { defer c.timeTrack(time.Now(), "Total") if err := c.rebuildSites(dynamicEvents); err != nil { c.handleBuildErr(err, "Rebuild failed") } }() if doLiveReload { if len(partitionedEvents.ContentEvents) == 0 && len(partitionedEvents.AssetEvents) > 0 { if c.wasError { livereload.ForceRefresh() return } changed := c.changeDetector.changed() if c.changeDetector != nil && len(changed) == 0 { // Nothing has changed. return } else if len(changed) == 1 { pathToRefresh := c.firstPathSpec().RelURL(helpers.ToSlashTrimLeading(changed[0]), false) livereload.RefreshPath(pathToRefresh) } else { livereload.ForceRefresh() } } if len(partitionedEvents.ContentEvents) > 0 { navigate := c.Cfg.GetBool("navigateToChanged") // We have fetched the same page above, but it may have // changed. var p page.Page if navigate { if onePageName != "" { p = c.hugo().GetContentPage(onePageName) } } if p != nil { livereload.NavigateToPathForPort(p.RelPermalink(), p.Site().ServerPort()) } else { livereload.ForceRefresh() } } } } } // dynamicEvents contains events that is considered dynamic, as in "not static". // Both of these categories will trigger a new build, but the asset events // does not fit into the "navigate to changed" logic. type dynamicEvents struct { ContentEvents []fsnotify.Event AssetEvents []fsnotify.Event } func partitionDynamicEvents(sourceFs *filesystems.SourceFilesystems, events []fsnotify.Event) (de dynamicEvents) { for _, e := range events { if sourceFs.IsAsset(e.Name) { de.AssetEvents = append(de.AssetEvents, e) } else { de.ContentEvents = append(de.ContentEvents, e) } } return } func pickOneWriteOrCreatePath(events []fsnotify.Event) string { name := "" for _, ev := range events { if ev.Op&fsnotify.Write == fsnotify.Write || ev.Op&fsnotify.Create == fsnotify.Create { if files.IsIndexContentFile(ev.Name) { return ev.Name } if files.IsContentFile(ev.Name) { name = ev.Name } } } return name } func formatByteCount(b uint64) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) }
vanbroup
bfebd8c02cfc0d4e4786e0f64932d832d3976e92
c7d5f9f067fd6a37ac6b75cb1c02259debd3ff21
I think we have some commands that needs to complete even without a valid config, meaning `c.hugo()` will just block forever. It would ease my mind if you rewrote the above to: ```go if h := c.hugoTry(); h != nil { range h.Sites ... } ...
bep
102
gohugoio/hugo
9,954
common: Add hugo.GoVersion
Closes #9849. This enables `hugo.GoVersion` in templates to access the version of Go that the Hugo binary was built with.
null
2022-05-30 13:15:38+00:00
2022-06-14 07:48:46+00:00
common/hugo/hugo.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 hugo import ( "fmt" "html/template" "os" "path/filepath" "runtime/debug" "sort" "strings" "sync" "time" "github.com/gohugoio/hugo/hugofs/files" "github.com/spf13/afero" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs" ) const ( EnvironmentDevelopment = "development" EnvironmentProduction = "production" ) var ( // vendorInfo contains vendor notes about the current build. vendorInfo string ) // Info contains information about the current Hugo environment type Info struct { CommitHash string BuildDate string // The build environment. // Defaults are "production" (hugo) and "development" (hugo server). // This can also be set by the user. // It can be any string, but it will be all lower case. Environment string deps []*Dependency } // Version returns the current version as a comparable version string. func (i Info) Version() VersionString { return CurrentVersion.Version() } // Generator a Hugo meta generator HTML tag. func (i Info) Generator() template.HTML { return template.HTML(fmt.Sprintf(`<meta name="generator" content="Hugo %s" />`, CurrentVersion.String())) } func (i Info) IsProduction() bool { return i.Environment == EnvironmentProduction } func (i Info) IsExtended() bool { return IsExtended } // Deps gets a list of dependencies for this Hugo build. func (i Info) Deps() []*Dependency { return i.deps } // NewInfo creates a new Hugo Info object. func NewInfo(environment string, deps []*Dependency) Info { if environment == "" { environment = EnvironmentProduction } var ( commitHash string buildDate string ) bi := getBuildInfo() if bi != nil { commitHash = bi.Revision buildDate = bi.RevisionTime } return Info{ CommitHash: commitHash, BuildDate: buildDate, Environment: environment, deps: deps, } } // GetExecEnviron creates and gets the common os/exec environment used in the // external programs we interact with via os/exec, e.g. postcss. func GetExecEnviron(workDir string, cfg config.Provider, fs afero.Fs) []string { var env []string nodepath := filepath.Join(workDir, "node_modules") if np := os.Getenv("NODE_PATH"); np != "" { nodepath = workDir + string(os.PathListSeparator) + np } config.SetEnvVars(&env, "NODE_PATH", nodepath) config.SetEnvVars(&env, "PWD", workDir) config.SetEnvVars(&env, "HUGO_ENVIRONMENT", cfg.GetString("environment")) config.SetEnvVars(&env, "HUGO_ENV", cfg.GetString("environment")) if fs != nil { fis, err := afero.ReadDir(fs, files.FolderJSConfig) if err == nil { for _, fi := range fis { key := fmt.Sprintf("HUGO_FILE_%s", strings.ReplaceAll(strings.ToUpper(fi.Name()), ".", "_")) value := fi.(hugofs.FileMetaInfo).Meta().Filename config.SetEnvVars(&env, key, value) } } } return env } type buildInfo struct { VersionControlSystem string Revision string RevisionTime string Modified bool GoOS string GoArch string *debug.BuildInfo } var bInfo *buildInfo var bInfoInit sync.Once func getBuildInfo() *buildInfo { bInfoInit.Do(func() { bi, ok := debug.ReadBuildInfo() if !ok { return } bInfo = &buildInfo{BuildInfo: bi} for _, s := range bInfo.Settings { switch s.Key { case "vcs": bInfo.VersionControlSystem = s.Value case "vcs.revision": bInfo.Revision = s.Value case "vcs.time": bInfo.RevisionTime = s.Value case "vcs.modified": bInfo.Modified = s.Value == "true" case "GOOS": bInfo.GoOS = s.Value case "GOARCH": bInfo.GoArch = s.Value } } }) return bInfo } // GetDependencyList returns a sorted dependency list on the format package="version". // It includes both Go dependencies and (a manually maintained) list of C(++) dependencies. func GetDependencyList() []string { var deps []string formatDep := func(path, version string) string { return fmt.Sprintf("%s=%q", path, version) } if IsExtended { deps = append( deps, // TODO(bep) consider adding a DepsNonGo() method to these upstream projects. formatDep("github.com/sass/libsass", "3.6.5"), formatDep("github.com/webmproject/libwebp", "v1.2.0"), ) } bi := getBuildInfo() if bi == nil { return deps } for _, dep := range bi.Deps { deps = append(deps, formatDep(dep.Path, dep.Version)) } sort.Strings(deps) return deps } // IsRunningAsTest reports whether we are running as a test. func IsRunningAsTest() bool { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test") { return true } } return false } // Dependency is a single dependency, which can be either a Hugo Module or a local theme. type Dependency struct { // Returns the path to this module. // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", // or the path below your /theme folder, e.g. "mytheme". Path string // The module version. Version string // Whether this dependency is vendored. Vendor bool // Time version was created. Time time.Time // In the dependency tree, this is the first module that defines this module // as a dependency. Owner *Dependency // Replaced by this dependency. Replace *Dependency }
// 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 hugo import ( "fmt" "html/template" "os" "path/filepath" "runtime/debug" "sort" "strings" "sync" "time" "github.com/gohugoio/hugo/hugofs/files" "github.com/spf13/afero" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs" ) const ( EnvironmentDevelopment = "development" EnvironmentProduction = "production" ) var ( // vendorInfo contains vendor notes about the current build. vendorInfo string ) // Info contains information about the current Hugo environment type Info struct { CommitHash string BuildDate string // The build environment. // Defaults are "production" (hugo) and "development" (hugo server). // This can also be set by the user. // It can be any string, but it will be all lower case. Environment string // version of go that the Hugo binary was built with GoVersion string deps []*Dependency } // Version returns the current version as a comparable version string. func (i Info) Version() VersionString { return CurrentVersion.Version() } // Generator a Hugo meta generator HTML tag. func (i Info) Generator() template.HTML { return template.HTML(fmt.Sprintf(`<meta name="generator" content="Hugo %s" />`, CurrentVersion.String())) } func (i Info) IsProduction() bool { return i.Environment == EnvironmentProduction } func (i Info) IsExtended() bool { return IsExtended } // Deps gets a list of dependencies for this Hugo build. func (i Info) Deps() []*Dependency { return i.deps } // NewInfo creates a new Hugo Info object. func NewInfo(environment string, deps []*Dependency) Info { if environment == "" { environment = EnvironmentProduction } var ( commitHash string buildDate string goVersion string ) bi := getBuildInfo() if bi != nil { commitHash = bi.Revision buildDate = bi.RevisionTime goVersion = bi.GoVersion } return Info{ CommitHash: commitHash, BuildDate: buildDate, Environment: environment, deps: deps, GoVersion: goVersion, } } // GetExecEnviron creates and gets the common os/exec environment used in the // external programs we interact with via os/exec, e.g. postcss. func GetExecEnviron(workDir string, cfg config.Provider, fs afero.Fs) []string { var env []string nodepath := filepath.Join(workDir, "node_modules") if np := os.Getenv("NODE_PATH"); np != "" { nodepath = workDir + string(os.PathListSeparator) + np } config.SetEnvVars(&env, "NODE_PATH", nodepath) config.SetEnvVars(&env, "PWD", workDir) config.SetEnvVars(&env, "HUGO_ENVIRONMENT", cfg.GetString("environment")) config.SetEnvVars(&env, "HUGO_ENV", cfg.GetString("environment")) if fs != nil { fis, err := afero.ReadDir(fs, files.FolderJSConfig) if err == nil { for _, fi := range fis { key := fmt.Sprintf("HUGO_FILE_%s", strings.ReplaceAll(strings.ToUpper(fi.Name()), ".", "_")) value := fi.(hugofs.FileMetaInfo).Meta().Filename config.SetEnvVars(&env, key, value) } } } return env } type buildInfo struct { VersionControlSystem string Revision string RevisionTime string Modified bool GoOS string GoArch string *debug.BuildInfo } var bInfo *buildInfo var bInfoInit sync.Once func getBuildInfo() *buildInfo { bInfoInit.Do(func() { bi, ok := debug.ReadBuildInfo() if !ok { return } bInfo = &buildInfo{BuildInfo: bi} for _, s := range bInfo.Settings { switch s.Key { case "vcs": bInfo.VersionControlSystem = s.Value case "vcs.revision": bInfo.Revision = s.Value case "vcs.time": bInfo.RevisionTime = s.Value case "vcs.modified": bInfo.Modified = s.Value == "true" case "GOOS": bInfo.GoOS = s.Value case "GOARCH": bInfo.GoArch = s.Value } } }) return bInfo } // GetDependencyList returns a sorted dependency list on the format package="version". // It includes both Go dependencies and (a manually maintained) list of C(++) dependencies. func GetDependencyList() []string { var deps []string formatDep := func(path, version string) string { return fmt.Sprintf("%s=%q", path, version) } if IsExtended { deps = append( deps, // TODO(bep) consider adding a DepsNonGo() method to these upstream projects. formatDep("github.com/sass/libsass", "3.6.5"), formatDep("github.com/webmproject/libwebp", "v1.2.0"), ) } bi := getBuildInfo() if bi == nil { return deps } for _, dep := range bi.Deps { deps = append(deps, formatDep(dep.Path, dep.Version)) } sort.Strings(deps) return deps } // IsRunningAsTest reports whether we are running as a test. func IsRunningAsTest() bool { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test") { return true } } return false } // Dependency is a single dependency, which can be either a Hugo Module or a local theme. type Dependency struct { // Returns the path to this module. // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", // or the path below your /theme folder, e.g. "mytheme". Path string // The module version. Version string // Whether this dependency is vendored. Vendor bool // Time version was created. Time time.Time // In the dependency tree, this is the first module that defines this module // as a dependency. Owner *Dependency // Replaced by this dependency. Replace *Dependency }
khayyamsaleem
66da1b7b2f8a8bd26ed4a50a54f64489f116f484
09ac73338198ceb143c1e5edc5859ab735cd80bb
* I think it would be better (or at least more consistent) if you just add GoVersion as a field and add it to the constructor. * I think it's more precise to say "that the hugo binary is built with"... * Also, the commit message is not totally in line with the commit message guidelines (does not start with a capital letter after the prefix).
bep
103
gohugoio/hugo
9,954
common: Add hugo.GoVersion
Closes #9849. This enables `hugo.GoVersion` in templates to access the version of Go that the Hugo binary was built with.
null
2022-05-30 13:15:38+00:00
2022-06-14 07:48:46+00:00
common/hugo/hugo.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 hugo import ( "fmt" "html/template" "os" "path/filepath" "runtime/debug" "sort" "strings" "sync" "time" "github.com/gohugoio/hugo/hugofs/files" "github.com/spf13/afero" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs" ) const ( EnvironmentDevelopment = "development" EnvironmentProduction = "production" ) var ( // vendorInfo contains vendor notes about the current build. vendorInfo string ) // Info contains information about the current Hugo environment type Info struct { CommitHash string BuildDate string // The build environment. // Defaults are "production" (hugo) and "development" (hugo server). // This can also be set by the user. // It can be any string, but it will be all lower case. Environment string deps []*Dependency } // Version returns the current version as a comparable version string. func (i Info) Version() VersionString { return CurrentVersion.Version() } // Generator a Hugo meta generator HTML tag. func (i Info) Generator() template.HTML { return template.HTML(fmt.Sprintf(`<meta name="generator" content="Hugo %s" />`, CurrentVersion.String())) } func (i Info) IsProduction() bool { return i.Environment == EnvironmentProduction } func (i Info) IsExtended() bool { return IsExtended } // Deps gets a list of dependencies for this Hugo build. func (i Info) Deps() []*Dependency { return i.deps } // NewInfo creates a new Hugo Info object. func NewInfo(environment string, deps []*Dependency) Info { if environment == "" { environment = EnvironmentProduction } var ( commitHash string buildDate string ) bi := getBuildInfo() if bi != nil { commitHash = bi.Revision buildDate = bi.RevisionTime } return Info{ CommitHash: commitHash, BuildDate: buildDate, Environment: environment, deps: deps, } } // GetExecEnviron creates and gets the common os/exec environment used in the // external programs we interact with via os/exec, e.g. postcss. func GetExecEnviron(workDir string, cfg config.Provider, fs afero.Fs) []string { var env []string nodepath := filepath.Join(workDir, "node_modules") if np := os.Getenv("NODE_PATH"); np != "" { nodepath = workDir + string(os.PathListSeparator) + np } config.SetEnvVars(&env, "NODE_PATH", nodepath) config.SetEnvVars(&env, "PWD", workDir) config.SetEnvVars(&env, "HUGO_ENVIRONMENT", cfg.GetString("environment")) config.SetEnvVars(&env, "HUGO_ENV", cfg.GetString("environment")) if fs != nil { fis, err := afero.ReadDir(fs, files.FolderJSConfig) if err == nil { for _, fi := range fis { key := fmt.Sprintf("HUGO_FILE_%s", strings.ReplaceAll(strings.ToUpper(fi.Name()), ".", "_")) value := fi.(hugofs.FileMetaInfo).Meta().Filename config.SetEnvVars(&env, key, value) } } } return env } type buildInfo struct { VersionControlSystem string Revision string RevisionTime string Modified bool GoOS string GoArch string *debug.BuildInfo } var bInfo *buildInfo var bInfoInit sync.Once func getBuildInfo() *buildInfo { bInfoInit.Do(func() { bi, ok := debug.ReadBuildInfo() if !ok { return } bInfo = &buildInfo{BuildInfo: bi} for _, s := range bInfo.Settings { switch s.Key { case "vcs": bInfo.VersionControlSystem = s.Value case "vcs.revision": bInfo.Revision = s.Value case "vcs.time": bInfo.RevisionTime = s.Value case "vcs.modified": bInfo.Modified = s.Value == "true" case "GOOS": bInfo.GoOS = s.Value case "GOARCH": bInfo.GoArch = s.Value } } }) return bInfo } // GetDependencyList returns a sorted dependency list on the format package="version". // It includes both Go dependencies and (a manually maintained) list of C(++) dependencies. func GetDependencyList() []string { var deps []string formatDep := func(path, version string) string { return fmt.Sprintf("%s=%q", path, version) } if IsExtended { deps = append( deps, // TODO(bep) consider adding a DepsNonGo() method to these upstream projects. formatDep("github.com/sass/libsass", "3.6.5"), formatDep("github.com/webmproject/libwebp", "v1.2.0"), ) } bi := getBuildInfo() if bi == nil { return deps } for _, dep := range bi.Deps { deps = append(deps, formatDep(dep.Path, dep.Version)) } sort.Strings(deps) return deps } // IsRunningAsTest reports whether we are running as a test. func IsRunningAsTest() bool { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test") { return true } } return false } // Dependency is a single dependency, which can be either a Hugo Module or a local theme. type Dependency struct { // Returns the path to this module. // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", // or the path below your /theme folder, e.g. "mytheme". Path string // The module version. Version string // Whether this dependency is vendored. Vendor bool // Time version was created. Time time.Time // In the dependency tree, this is the first module that defines this module // as a dependency. Owner *Dependency // Replaced by this dependency. Replace *Dependency }
// 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 hugo import ( "fmt" "html/template" "os" "path/filepath" "runtime/debug" "sort" "strings" "sync" "time" "github.com/gohugoio/hugo/hugofs/files" "github.com/spf13/afero" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs" ) const ( EnvironmentDevelopment = "development" EnvironmentProduction = "production" ) var ( // vendorInfo contains vendor notes about the current build. vendorInfo string ) // Info contains information about the current Hugo environment type Info struct { CommitHash string BuildDate string // The build environment. // Defaults are "production" (hugo) and "development" (hugo server). // This can also be set by the user. // It can be any string, but it will be all lower case. Environment string // version of go that the Hugo binary was built with GoVersion string deps []*Dependency } // Version returns the current version as a comparable version string. func (i Info) Version() VersionString { return CurrentVersion.Version() } // Generator a Hugo meta generator HTML tag. func (i Info) Generator() template.HTML { return template.HTML(fmt.Sprintf(`<meta name="generator" content="Hugo %s" />`, CurrentVersion.String())) } func (i Info) IsProduction() bool { return i.Environment == EnvironmentProduction } func (i Info) IsExtended() bool { return IsExtended } // Deps gets a list of dependencies for this Hugo build. func (i Info) Deps() []*Dependency { return i.deps } // NewInfo creates a new Hugo Info object. func NewInfo(environment string, deps []*Dependency) Info { if environment == "" { environment = EnvironmentProduction } var ( commitHash string buildDate string goVersion string ) bi := getBuildInfo() if bi != nil { commitHash = bi.Revision buildDate = bi.RevisionTime goVersion = bi.GoVersion } return Info{ CommitHash: commitHash, BuildDate: buildDate, Environment: environment, deps: deps, GoVersion: goVersion, } } // GetExecEnviron creates and gets the common os/exec environment used in the // external programs we interact with via os/exec, e.g. postcss. func GetExecEnviron(workDir string, cfg config.Provider, fs afero.Fs) []string { var env []string nodepath := filepath.Join(workDir, "node_modules") if np := os.Getenv("NODE_PATH"); np != "" { nodepath = workDir + string(os.PathListSeparator) + np } config.SetEnvVars(&env, "NODE_PATH", nodepath) config.SetEnvVars(&env, "PWD", workDir) config.SetEnvVars(&env, "HUGO_ENVIRONMENT", cfg.GetString("environment")) config.SetEnvVars(&env, "HUGO_ENV", cfg.GetString("environment")) if fs != nil { fis, err := afero.ReadDir(fs, files.FolderJSConfig) if err == nil { for _, fi := range fis { key := fmt.Sprintf("HUGO_FILE_%s", strings.ReplaceAll(strings.ToUpper(fi.Name()), ".", "_")) value := fi.(hugofs.FileMetaInfo).Meta().Filename config.SetEnvVars(&env, key, value) } } } return env } type buildInfo struct { VersionControlSystem string Revision string RevisionTime string Modified bool GoOS string GoArch string *debug.BuildInfo } var bInfo *buildInfo var bInfoInit sync.Once func getBuildInfo() *buildInfo { bInfoInit.Do(func() { bi, ok := debug.ReadBuildInfo() if !ok { return } bInfo = &buildInfo{BuildInfo: bi} for _, s := range bInfo.Settings { switch s.Key { case "vcs": bInfo.VersionControlSystem = s.Value case "vcs.revision": bInfo.Revision = s.Value case "vcs.time": bInfo.RevisionTime = s.Value case "vcs.modified": bInfo.Modified = s.Value == "true" case "GOOS": bInfo.GoOS = s.Value case "GOARCH": bInfo.GoArch = s.Value } } }) return bInfo } // GetDependencyList returns a sorted dependency list on the format package="version". // It includes both Go dependencies and (a manually maintained) list of C(++) dependencies. func GetDependencyList() []string { var deps []string formatDep := func(path, version string) string { return fmt.Sprintf("%s=%q", path, version) } if IsExtended { deps = append( deps, // TODO(bep) consider adding a DepsNonGo() method to these upstream projects. formatDep("github.com/sass/libsass", "3.6.5"), formatDep("github.com/webmproject/libwebp", "v1.2.0"), ) } bi := getBuildInfo() if bi == nil { return deps } for _, dep := range bi.Deps { deps = append(deps, formatDep(dep.Path, dep.Version)) } sort.Strings(deps) return deps } // IsRunningAsTest reports whether we are running as a test. func IsRunningAsTest() bool { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test") { return true } } return false } // Dependency is a single dependency, which can be either a Hugo Module or a local theme. type Dependency struct { // Returns the path to this module. // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", // or the path below your /theme folder, e.g. "mytheme". Path string // The module version. Version string // Whether this dependency is vendored. Vendor bool // Time version was created. Time time.Time // In the dependency tree, this is the first module that defines this module // as a dependency. Owner *Dependency // Replaced by this dependency. Replace *Dependency }
khayyamsaleem
66da1b7b2f8a8bd26ed4a50a54f64489f116f484
09ac73338198ceb143c1e5edc5859ab735cd80bb
feedback accommodated, thanks for the speedy review!
khayyamsaleem
104
gohugoio/hugo
9,742
hugo deploy also sets an md5 attribute & checks it
Improves https://github.com/gohugoio/hugo/issues/9735 ### Problem During Hugo deploy when a remote MD5 is invalid (e.g due to multipart etag) hugo reads the entire remote file and calculates the md5 again which can be slow. ### This PR - Updates file upload so that it will also store an md5 hash in the cloud providers attributes. e.g in aws this looks like `x-amz-meta-md5chksum: 26fe392386a8123bf8956a16e08cb841` - Updates the walkremote so that if an MD5 is nonexistent/invalid then it attempts to read the attribute md5 before falling back to reading the entire remote file ### What impact does this have? Hugo deploy will be faster in the diffing stage between remote and local. **_IF_** files come through with `len(obj.MD5) == 0` but store an attribute md5. ### Caveats Only files uploaded with hugo will have this attribute. **Existing users** Existing hugo deploy users running this in a new release would only get the attributes set on files that are uploaded going forward. If they want all files to have the md5 attribute then running with `--force` should work. **Other files in the bucket** If you have files uploaded by another tool in the same bucket that hugo deploy is using and these don't have valid a MD5. Then you can see a perf boost if you manually upload these to have the md5 as an attribute.
null
2022-04-03 13:12:09+00:00
2022-04-05 08:42:54+00:00
deploy/deploy.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. //go:build !nodeploy // +build !nodeploy package deploy import ( "bytes" "compress/gzip" "context" "crypto/md5" "fmt" "io" "io/ioutil" "mime" "os" "path/filepath" "regexp" "runtime" "sort" "strings" "sync" "github.com/dustin/go-humanize" "github.com/gobwas/glob" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/pkg/errors" "github.com/spf13/afero" jww "github.com/spf13/jwalterweatherman" "golang.org/x/text/unicode/norm" "gocloud.dev/blob" _ "gocloud.dev/blob/fileblob" // import _ "gocloud.dev/blob/gcsblob" // import _ "gocloud.dev/blob/s3blob" // import "gocloud.dev/gcerrors" ) // Deployer supports deploying the site to target cloud providers. type Deployer struct { localFs afero.Fs bucket *blob.Bucket target *target // the target to deploy to matchers []*matcher // matchers to apply to uploaded files mediaTypes media.Types // Hugo's MediaType to guess ContentType ordering []*regexp.Regexp // orders uploads quiet bool // true reduces STDOUT confirm bool // true enables confirmation before making changes dryRun bool // true skips conformations and prints changes instead of applying them force bool // true forces upload of all files invalidateCDN bool // true enables invalidate CDN cache (if possible) maxDeletes int // caps the # of files to delete; -1 to disable // For tests... summary deploySummary // summary of latest Deploy results } type deploySummary struct { NumLocal, NumRemote, NumUploads, NumDeletes int } // New constructs a new *Deployer. func New(cfg config.Provider, localFs afero.Fs) (*Deployer, error) { targetName := cfg.GetString("target") // Load the [deployment] section of the config. dcfg, err := decodeConfig(cfg) if err != nil { return nil, err } if len(dcfg.Targets) == 0 { return nil, errors.New("no deployment targets found") } // Find the target to deploy to. var tgt *target if targetName == "" { // Default to the first target. tgt = dcfg.Targets[0] } else { for _, t := range dcfg.Targets { if t.Name == targetName { tgt = t } } if tgt == nil { return nil, fmt.Errorf("deployment target %q not found", targetName) } } return &Deployer{ localFs: localFs, target: tgt, matchers: dcfg.Matchers, ordering: dcfg.ordering, mediaTypes: dcfg.mediaTypes, quiet: cfg.GetBool("quiet"), confirm: cfg.GetBool("confirm"), dryRun: cfg.GetBool("dryRun"), force: cfg.GetBool("force"), invalidateCDN: cfg.GetBool("invalidateCDN"), maxDeletes: cfg.GetInt("maxDeletes"), }, nil } func (d *Deployer) openBucket(ctx context.Context) (*blob.Bucket, error) { if d.bucket != nil { return d.bucket, nil } jww.FEEDBACK.Printf("Deploying to target %q (%s)\n", d.target.Name, d.target.URL) return blob.OpenBucket(ctx, d.target.URL) } // Deploy deploys the site to a target. func (d *Deployer) Deploy(ctx context.Context) error { bucket, err := d.openBucket(ctx) if err != nil { return err } // Load local files from the source directory. var include, exclude glob.Glob if d.target != nil { include, exclude = d.target.includeGlob, d.target.excludeGlob } local, err := walkLocal(d.localFs, d.matchers, include, exclude, d.mediaTypes) if err != nil { return err } jww.INFO.Printf("Found %d local files.\n", len(local)) d.summary.NumLocal = len(local) // Load remote files from the target. remote, err := walkRemote(ctx, bucket, include, exclude) if err != nil { return err } jww.INFO.Printf("Found %d remote files.\n", len(remote)) d.summary.NumRemote = len(remote) // Diff local vs remote to see what changes need to be applied. uploads, deletes := findDiffs(local, remote, d.force) d.summary.NumUploads = len(uploads) d.summary.NumDeletes = len(deletes) if len(uploads)+len(deletes) == 0 { if !d.quiet { jww.FEEDBACK.Println("No changes required.") } return nil } if !d.quiet { jww.FEEDBACK.Println(summarizeChanges(uploads, deletes)) } // Ask for confirmation before proceeding. if d.confirm && !d.dryRun { fmt.Printf("Continue? (Y/n) ") var confirm string if _, err := fmt.Scanln(&confirm); err != nil { return err } if confirm != "" && confirm[0] != 'y' && confirm[0] != 'Y' { return errors.New("aborted") } } // Order the uploads. They are organized in groups; all uploads in a group // must be complete before moving on to the next group. uploadGroups := applyOrdering(d.ordering, uploads) // Apply the changes in parallel, using an inverted worker // pool (https://www.youtube.com/watch?v=5zXAHh5tJqQ&t=26m58s). // sem prevents more than nParallel concurrent goroutines. const nParallel = 10 var errs []error var errMu sync.Mutex // protects errs for _, uploads := range uploadGroups { // Short-circuit for an empty group. if len(uploads) == 0 { continue } // Within the group, apply uploads in parallel. sem := make(chan struct{}, nParallel) for _, upload := range uploads { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would upload: %v\n", upload) } continue } sem <- struct{}{} go func(upload *fileToUpload) { if err := doSingleUpload(ctx, bucket, upload); err != nil { errMu.Lock() defer errMu.Unlock() errs = append(errs, err) } <-sem }(upload) } // Wait for all uploads in the group to finish. for n := nParallel; n > 0; n-- { sem <- struct{}{} } } if d.maxDeletes != -1 && len(deletes) > d.maxDeletes { jww.WARN.Printf("Skipping %d deletes because it is more than --maxDeletes (%d). If this is expected, set --maxDeletes to a larger number, or -1 to disable this check.\n", len(deletes), d.maxDeletes) d.summary.NumDeletes = 0 } else { // Apply deletes in parallel. sort.Slice(deletes, func(i, j int) bool { return deletes[i] < deletes[j] }) sem := make(chan struct{}, nParallel) for _, del := range deletes { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would delete %s\n", del) } continue } sem <- struct{}{} go func(del string) { jww.INFO.Printf("Deleting %s...\n", del) if err := bucket.Delete(ctx, del); err != nil { if gcerrors.Code(err) == gcerrors.NotFound { jww.WARN.Printf("Failed to delete %q because it wasn't found: %v", del, err) } else { errMu.Lock() defer errMu.Unlock() errs = append(errs, err) } } <-sem }(del) } // Wait for all deletes to finish. for n := nParallel; n > 0; n-- { sem <- struct{}{} } } if len(errs) > 0 { if !d.quiet { jww.FEEDBACK.Printf("Encountered %d errors.\n", len(errs)) } return errs[0] } if !d.quiet { jww.FEEDBACK.Println("Success!") } if d.invalidateCDN { if d.target.CloudFrontDistributionID != "" { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would invalidate CloudFront CDN with ID %s\n", d.target.CloudFrontDistributionID) } } else { jww.FEEDBACK.Println("Invalidating CloudFront CDN...") if err := InvalidateCloudFront(ctx, d.target.CloudFrontDistributionID); err != nil { jww.FEEDBACK.Printf("Failed to invalidate CloudFront CDN: %v\n", err) return err } } } if d.target.GoogleCloudCDNOrigin != "" { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would invalidate Google Cloud CDN with origin %s\n", d.target.GoogleCloudCDNOrigin) } } else { jww.FEEDBACK.Println("Invalidating Google Cloud CDN...") if err := InvalidateGoogleCloudCDN(ctx, d.target.GoogleCloudCDNOrigin); err != nil { jww.FEEDBACK.Printf("Failed to invalidate Google Cloud CDN: %v\n", err) return err } } } jww.FEEDBACK.Println("Success!") } return nil } // summarizeChanges creates a text description of the proposed changes. func summarizeChanges(uploads []*fileToUpload, deletes []string) string { uploadSize := int64(0) for _, u := range uploads { uploadSize += u.Local.UploadSize } return fmt.Sprintf("Identified %d file(s) to upload, totaling %s, and %d file(s) to delete.", len(uploads), humanize.Bytes(uint64(uploadSize)), len(deletes)) } // doSingleUpload executes a single file upload. func doSingleUpload(ctx context.Context, bucket *blob.Bucket, upload *fileToUpload) error { jww.INFO.Printf("Uploading %v...\n", upload) opts := &blob.WriterOptions{ CacheControl: upload.Local.CacheControl(), ContentEncoding: upload.Local.ContentEncoding(), ContentType: upload.Local.ContentType(), } w, err := bucket.NewWriter(ctx, upload.Local.SlashPath, opts) if err != nil { return err } r, err := upload.Local.Reader() if err != nil { return err } defer r.Close() _, err = io.Copy(w, r) if err != nil { return err } if err := w.Close(); err != nil { return err } return nil } // localFile represents a local file from the source. Use newLocalFile to // construct one. type localFile struct { // NativePath is the native path to the file (using file.Separator). NativePath string // SlashPath is NativePath converted to use /. SlashPath string // UploadSize is the size of the content to be uploaded. It may not // be the same as the local file size if the content will be // gzipped before upload. UploadSize int64 fs afero.Fs matcher *matcher md5 []byte // cache gzipped bytes.Buffer // cached of gzipped contents if gzipping mediaTypes media.Types } // newLocalFile initializes a *localFile. func newLocalFile(fs afero.Fs, nativePath, slashpath string, m *matcher, mt media.Types) (*localFile, error) { f, err := fs.Open(nativePath) if err != nil { return nil, err } defer f.Close() lf := &localFile{ NativePath: nativePath, SlashPath: slashpath, fs: fs, matcher: m, mediaTypes: mt, } if m != nil && m.Gzip { // We're going to gzip the content. Do it once now, and cache the result // in gzipped. The UploadSize is the size of the gzipped content. gz := gzip.NewWriter(&lf.gzipped) if _, err := io.Copy(gz, f); err != nil { return nil, err } if err := gz.Close(); err != nil { return nil, err } lf.UploadSize = int64(lf.gzipped.Len()) } else { // Raw content. Just get the UploadSize. info, err := f.Stat() if err != nil { return nil, err } lf.UploadSize = info.Size() } return lf, nil } // Reader returns an io.ReadCloser for reading the content to be uploaded. // The caller must call Close on the returned ReaderCloser. // The reader content may not be the same as the local file content due to // gzipping. func (lf *localFile) Reader() (io.ReadCloser, error) { if lf.matcher != nil && lf.matcher.Gzip { // We've got the gzipped contents cached in gzipped. // Note: we can't use lf.gzipped directly as a Reader, since we it discards // data after it is read, and we may read it more than once. return ioutil.NopCloser(bytes.NewReader(lf.gzipped.Bytes())), nil } // Not expected to fail since we did it successfully earlier in newLocalFile, // but could happen due to changes in the underlying filesystem. return lf.fs.Open(lf.NativePath) } // CacheControl returns the Cache-Control header to use for lf, based on the // first matching matcher (if any). func (lf *localFile) CacheControl() string { if lf.matcher == nil { return "" } return lf.matcher.CacheControl } // ContentEncoding returns the Content-Encoding header to use for lf, based // on the matcher's Content-Encoding and Gzip fields. func (lf *localFile) ContentEncoding() string { if lf.matcher == nil { return "" } if lf.matcher.Gzip { return "gzip" } return lf.matcher.ContentEncoding } // ContentType returns the Content-Type header to use for lf. // It first checks if there's a Content-Type header configured via a matching // matcher; if not, it tries to generate one based on the filename extension. // If this fails, the Content-Type will be the empty string. In this case, Go // Cloud will automatically try to infer a Content-Type based on the file // content. func (lf *localFile) ContentType() string { if lf.matcher != nil && lf.matcher.ContentType != "" { return lf.matcher.ContentType } ext := filepath.Ext(lf.NativePath) if mimeType, _, found := lf.mediaTypes.GetFirstBySuffix(strings.TrimPrefix(ext, ".")); found { return mimeType.Type() } return mime.TypeByExtension(ext) } // Force returns true if the file should be forced to re-upload based on the // matching matcher. func (lf *localFile) Force() bool { return lf.matcher != nil && lf.matcher.Force } // MD5 returns an MD5 hash of the content to be uploaded. func (lf *localFile) MD5() []byte { if len(lf.md5) > 0 { return lf.md5 } h := md5.New() r, err := lf.Reader() if err != nil { return nil } defer r.Close() if _, err := io.Copy(h, r); err != nil { return nil } lf.md5 = h.Sum(nil) return lf.md5 } // knownHiddenDirectory checks if the specified name is a well known // hidden directory. func knownHiddenDirectory(name string) bool { knownDirectories := []string{ ".well-known", } for _, dir := range knownDirectories { if name == dir { return true } } return false } // walkLocal walks the source directory and returns a flat list of files, // using localFile.SlashPath as the map keys. func walkLocal(fs afero.Fs, matchers []*matcher, include, exclude glob.Glob, mediaTypes media.Types) (map[string]*localFile, error) { retval := map[string]*localFile{} err := afero.Walk(fs, "", func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { // Skip hidden directories. if path != "" && strings.HasPrefix(info.Name(), ".") { // Except for specific hidden directories if !knownHiddenDirectory(info.Name()) { return filepath.SkipDir } } return nil } // .DS_Store is an internal MacOS attribute file; skip it. if info.Name() == ".DS_Store" { return nil } // When a file system is HFS+, its filepath is in NFD form. if runtime.GOOS == "darwin" { path = norm.NFC.String(path) } // Check include/exclude matchers. slashpath := filepath.ToSlash(path) if include != nil && !include.Match(slashpath) { jww.INFO.Printf(" dropping %q due to include\n", slashpath) return nil } if exclude != nil && exclude.Match(slashpath) { jww.INFO.Printf(" dropping %q due to exclude\n", slashpath) return nil } // Find the first matching matcher (if any). var m *matcher for _, cur := range matchers { if cur.Matches(slashpath) { m = cur break } } lf, err := newLocalFile(fs, path, slashpath, m, mediaTypes) if err != nil { return err } retval[lf.SlashPath] = lf return nil }) if err != nil { return nil, err } return retval, nil } // walkRemote walks the target bucket and returns a flat list. func walkRemote(ctx context.Context, bucket *blob.Bucket, include, exclude glob.Glob) (map[string]*blob.ListObject, error) { retval := map[string]*blob.ListObject{} iter := bucket.List(nil) for { obj, err := iter.Next(ctx) if err == io.EOF { break } if err != nil { return nil, err } // Check include/exclude matchers. if include != nil && !include.Match(obj.Key) { jww.INFO.Printf(" remote dropping %q due to include\n", obj.Key) continue } if exclude != nil && exclude.Match(obj.Key) { jww.INFO.Printf(" remote dropping %q due to exclude\n", obj.Key) continue } // If the remote didn't give us an MD5, compute one. // This can happen for some providers (e.g., fileblob, which uses the // local filesystem), but not for the most common Cloud providers // (S3, GCS, Azure). Although, it can happen for S3 if the blob was uploaded // via a multi-part upload. // Although it's unfortunate to have to read the file, it's likely better // than assuming a delta and re-uploading it. if len(obj.MD5) == 0 { r, err := bucket.NewReader(ctx, obj.Key, nil) if err == nil { h := md5.New() if _, err := io.Copy(h, r); err == nil { obj.MD5 = h.Sum(nil) } r.Close() } } retval[obj.Key] = obj } return retval, nil } // uploadReason is an enum of reasons why a file must be uploaded. type uploadReason string const ( reasonUnknown uploadReason = "unknown" reasonNotFound uploadReason = "not found at target" reasonForce uploadReason = "--force" reasonSize uploadReason = "size differs" reasonMD5Differs uploadReason = "md5 differs" reasonMD5Missing uploadReason = "remote md5 missing" ) // fileToUpload represents a single local file that should be uploaded to // the target. type fileToUpload struct { Local *localFile Reason uploadReason } func (u *fileToUpload) String() string { details := []string{humanize.Bytes(uint64(u.Local.UploadSize))} if s := u.Local.CacheControl(); s != "" { details = append(details, fmt.Sprintf("Cache-Control: %q", s)) } if s := u.Local.ContentEncoding(); s != "" { details = append(details, fmt.Sprintf("Content-Encoding: %q", s)) } if s := u.Local.ContentType(); s != "" { details = append(details, fmt.Sprintf("Content-Type: %q", s)) } return fmt.Sprintf("%s (%s): %v", u.Local.SlashPath, strings.Join(details, ", "), u.Reason) } // findDiffs diffs localFiles vs remoteFiles to see what changes should be // applied to the remote target. It returns a slice of *fileToUpload and a // slice of paths for files to delete. func findDiffs(localFiles map[string]*localFile, remoteFiles map[string]*blob.ListObject, force bool) ([]*fileToUpload, []string) { var uploads []*fileToUpload var deletes []string found := map[string]bool{} for path, lf := range localFiles { upload := false reason := reasonUnknown if remoteFile, ok := remoteFiles[path]; ok { // The file exists in remote. Let's see if we need to upload it anyway. // TODO: We don't register a diff if the metadata (e.g., Content-Type // header) has changed. This would be difficult/expensive to detect; some // providers return metadata along with their "List" result, but others // (notably AWS S3) do not, so gocloud.dev's blob.Bucket doesn't expose // it in the list result. It would require a separate request per blob // to fetch. At least for now, we work around this by documenting it and // providing a "force" flag (to re-upload everything) and a "force" bool // per matcher (to re-upload all files in a matcher whose headers may have // changed). // Idea: extract a sample set of 1 file per extension + 1 file per matcher // and check those files? if force { upload = true reason = reasonForce } else if lf.Force() { upload = true reason = reasonForce } else if lf.UploadSize != remoteFile.Size { upload = true reason = reasonSize } else if len(remoteFile.MD5) == 0 { // This shouldn't happen unless the remote didn't give us an MD5 hash // from List, AND we failed to compute one by reading the remote file. // Default to considering the files different. upload = true reason = reasonMD5Missing } else if !bytes.Equal(lf.MD5(), remoteFile.MD5) { upload = true reason = reasonMD5Differs } else { // Nope! Leave uploaded = false. } found[path] = true } else { // The file doesn't exist in remote. upload = true reason = reasonNotFound } if upload { jww.DEBUG.Printf("%s needs to be uploaded: %v\n", path, reason) uploads = append(uploads, &fileToUpload{lf, reason}) } else { jww.DEBUG.Printf("%s exists at target and does not need to be uploaded", path) } } // Remote files that weren't found locally should be deleted. for path := range remoteFiles { if !found[path] { deletes = append(deletes, path) } } return uploads, deletes } // applyOrdering returns an ordered slice of slices of uploads. // // The returned slice will have length len(ordering)+1. // // The subslice at index i, for i = 0 ... len(ordering)-1, will have all of the // uploads whose Local.SlashPath matched the regex at ordering[i] (but not any // previous ordering regex). // The subslice at index len(ordering) will have the remaining uploads that // didn't match any ordering regex. // // The subslices are sorted by Local.SlashPath. func applyOrdering(ordering []*regexp.Regexp, uploads []*fileToUpload) [][]*fileToUpload { // Sort the whole slice by Local.SlashPath first. sort.Slice(uploads, func(i, j int) bool { return uploads[i].Local.SlashPath < uploads[j].Local.SlashPath }) retval := make([][]*fileToUpload, len(ordering)+1) for _, u := range uploads { matched := false for i, re := range ordering { if re.MatchString(u.Local.SlashPath) { retval[i] = append(retval[i], u) matched = true break } } if !matched { retval[len(ordering)] = append(retval[len(ordering)], u) } } return retval }
// 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. //go:build !nodeploy // +build !nodeploy package deploy import ( "bytes" "compress/gzip" "context" "crypto/md5" "encoding/hex" "fmt" "io" "io/ioutil" "mime" "os" "path/filepath" "regexp" "runtime" "sort" "strings" "sync" "github.com/dustin/go-humanize" "github.com/gobwas/glob" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/pkg/errors" "github.com/spf13/afero" jww "github.com/spf13/jwalterweatherman" "golang.org/x/text/unicode/norm" "gocloud.dev/blob" _ "gocloud.dev/blob/fileblob" // import _ "gocloud.dev/blob/gcsblob" // import _ "gocloud.dev/blob/s3blob" // import "gocloud.dev/gcerrors" ) // Deployer supports deploying the site to target cloud providers. type Deployer struct { localFs afero.Fs bucket *blob.Bucket target *target // the target to deploy to matchers []*matcher // matchers to apply to uploaded files mediaTypes media.Types // Hugo's MediaType to guess ContentType ordering []*regexp.Regexp // orders uploads quiet bool // true reduces STDOUT confirm bool // true enables confirmation before making changes dryRun bool // true skips conformations and prints changes instead of applying them force bool // true forces upload of all files invalidateCDN bool // true enables invalidate CDN cache (if possible) maxDeletes int // caps the # of files to delete; -1 to disable // For tests... summary deploySummary // summary of latest Deploy results } type deploySummary struct { NumLocal, NumRemote, NumUploads, NumDeletes int } const metaMD5Hash = "md5chksum" // the meta key to store md5hash in // New constructs a new *Deployer. func New(cfg config.Provider, localFs afero.Fs) (*Deployer, error) { targetName := cfg.GetString("target") // Load the [deployment] section of the config. dcfg, err := decodeConfig(cfg) if err != nil { return nil, err } if len(dcfg.Targets) == 0 { return nil, errors.New("no deployment targets found") } // Find the target to deploy to. var tgt *target if targetName == "" { // Default to the first target. tgt = dcfg.Targets[0] } else { for _, t := range dcfg.Targets { if t.Name == targetName { tgt = t } } if tgt == nil { return nil, fmt.Errorf("deployment target %q not found", targetName) } } return &Deployer{ localFs: localFs, target: tgt, matchers: dcfg.Matchers, ordering: dcfg.ordering, mediaTypes: dcfg.mediaTypes, quiet: cfg.GetBool("quiet"), confirm: cfg.GetBool("confirm"), dryRun: cfg.GetBool("dryRun"), force: cfg.GetBool("force"), invalidateCDN: cfg.GetBool("invalidateCDN"), maxDeletes: cfg.GetInt("maxDeletes"), }, nil } func (d *Deployer) openBucket(ctx context.Context) (*blob.Bucket, error) { if d.bucket != nil { return d.bucket, nil } jww.FEEDBACK.Printf("Deploying to target %q (%s)\n", d.target.Name, d.target.URL) return blob.OpenBucket(ctx, d.target.URL) } // Deploy deploys the site to a target. func (d *Deployer) Deploy(ctx context.Context) error { bucket, err := d.openBucket(ctx) if err != nil { return err } // Load local files from the source directory. var include, exclude glob.Glob if d.target != nil { include, exclude = d.target.includeGlob, d.target.excludeGlob } local, err := walkLocal(d.localFs, d.matchers, include, exclude, d.mediaTypes) if err != nil { return err } jww.INFO.Printf("Found %d local files.\n", len(local)) d.summary.NumLocal = len(local) // Load remote files from the target. remote, err := walkRemote(ctx, bucket, include, exclude) if err != nil { return err } jww.INFO.Printf("Found %d remote files.\n", len(remote)) d.summary.NumRemote = len(remote) // Diff local vs remote to see what changes need to be applied. uploads, deletes := findDiffs(local, remote, d.force) d.summary.NumUploads = len(uploads) d.summary.NumDeletes = len(deletes) if len(uploads)+len(deletes) == 0 { if !d.quiet { jww.FEEDBACK.Println("No changes required.") } return nil } if !d.quiet { jww.FEEDBACK.Println(summarizeChanges(uploads, deletes)) } // Ask for confirmation before proceeding. if d.confirm && !d.dryRun { fmt.Printf("Continue? (Y/n) ") var confirm string if _, err := fmt.Scanln(&confirm); err != nil { return err } if confirm != "" && confirm[0] != 'y' && confirm[0] != 'Y' { return errors.New("aborted") } } // Order the uploads. They are organized in groups; all uploads in a group // must be complete before moving on to the next group. uploadGroups := applyOrdering(d.ordering, uploads) // Apply the changes in parallel, using an inverted worker // pool (https://www.youtube.com/watch?v=5zXAHh5tJqQ&t=26m58s). // sem prevents more than nParallel concurrent goroutines. const nParallel = 10 var errs []error var errMu sync.Mutex // protects errs for _, uploads := range uploadGroups { // Short-circuit for an empty group. if len(uploads) == 0 { continue } // Within the group, apply uploads in parallel. sem := make(chan struct{}, nParallel) for _, upload := range uploads { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would upload: %v\n", upload) } continue } sem <- struct{}{} go func(upload *fileToUpload) { if err := doSingleUpload(ctx, bucket, upload); err != nil { errMu.Lock() defer errMu.Unlock() errs = append(errs, err) } <-sem }(upload) } // Wait for all uploads in the group to finish. for n := nParallel; n > 0; n-- { sem <- struct{}{} } } if d.maxDeletes != -1 && len(deletes) > d.maxDeletes { jww.WARN.Printf("Skipping %d deletes because it is more than --maxDeletes (%d). If this is expected, set --maxDeletes to a larger number, or -1 to disable this check.\n", len(deletes), d.maxDeletes) d.summary.NumDeletes = 0 } else { // Apply deletes in parallel. sort.Slice(deletes, func(i, j int) bool { return deletes[i] < deletes[j] }) sem := make(chan struct{}, nParallel) for _, del := range deletes { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would delete %s\n", del) } continue } sem <- struct{}{} go func(del string) { jww.INFO.Printf("Deleting %s...\n", del) if err := bucket.Delete(ctx, del); err != nil { if gcerrors.Code(err) == gcerrors.NotFound { jww.WARN.Printf("Failed to delete %q because it wasn't found: %v", del, err) } else { errMu.Lock() defer errMu.Unlock() errs = append(errs, err) } } <-sem }(del) } // Wait for all deletes to finish. for n := nParallel; n > 0; n-- { sem <- struct{}{} } } if len(errs) > 0 { if !d.quiet { jww.FEEDBACK.Printf("Encountered %d errors.\n", len(errs)) } return errs[0] } if !d.quiet { jww.FEEDBACK.Println("Success!") } if d.invalidateCDN { if d.target.CloudFrontDistributionID != "" { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would invalidate CloudFront CDN with ID %s\n", d.target.CloudFrontDistributionID) } } else { jww.FEEDBACK.Println("Invalidating CloudFront CDN...") if err := InvalidateCloudFront(ctx, d.target.CloudFrontDistributionID); err != nil { jww.FEEDBACK.Printf("Failed to invalidate CloudFront CDN: %v\n", err) return err } } } if d.target.GoogleCloudCDNOrigin != "" { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would invalidate Google Cloud CDN with origin %s\n", d.target.GoogleCloudCDNOrigin) } } else { jww.FEEDBACK.Println("Invalidating Google Cloud CDN...") if err := InvalidateGoogleCloudCDN(ctx, d.target.GoogleCloudCDNOrigin); err != nil { jww.FEEDBACK.Printf("Failed to invalidate Google Cloud CDN: %v\n", err) return err } } } jww.FEEDBACK.Println("Success!") } return nil } // summarizeChanges creates a text description of the proposed changes. func summarizeChanges(uploads []*fileToUpload, deletes []string) string { uploadSize := int64(0) for _, u := range uploads { uploadSize += u.Local.UploadSize } return fmt.Sprintf("Identified %d file(s) to upload, totaling %s, and %d file(s) to delete.", len(uploads), humanize.Bytes(uint64(uploadSize)), len(deletes)) } // doSingleUpload executes a single file upload. func doSingleUpload(ctx context.Context, bucket *blob.Bucket, upload *fileToUpload) error { jww.INFO.Printf("Uploading %v...\n", upload) opts := &blob.WriterOptions{ CacheControl: upload.Local.CacheControl(), ContentEncoding: upload.Local.ContentEncoding(), ContentType: upload.Local.ContentType(), Metadata: map[string]string{metaMD5Hash: hex.EncodeToString(upload.Local.MD5())}, } w, err := bucket.NewWriter(ctx, upload.Local.SlashPath, opts) if err != nil { return err } r, err := upload.Local.Reader() if err != nil { return err } defer r.Close() _, err = io.Copy(w, r) if err != nil { return err } if err := w.Close(); err != nil { return err } return nil } // localFile represents a local file from the source. Use newLocalFile to // construct one. type localFile struct { // NativePath is the native path to the file (using file.Separator). NativePath string // SlashPath is NativePath converted to use /. SlashPath string // UploadSize is the size of the content to be uploaded. It may not // be the same as the local file size if the content will be // gzipped before upload. UploadSize int64 fs afero.Fs matcher *matcher md5 []byte // cache gzipped bytes.Buffer // cached of gzipped contents if gzipping mediaTypes media.Types } // newLocalFile initializes a *localFile. func newLocalFile(fs afero.Fs, nativePath, slashpath string, m *matcher, mt media.Types) (*localFile, error) { f, err := fs.Open(nativePath) if err != nil { return nil, err } defer f.Close() lf := &localFile{ NativePath: nativePath, SlashPath: slashpath, fs: fs, matcher: m, mediaTypes: mt, } if m != nil && m.Gzip { // We're going to gzip the content. Do it once now, and cache the result // in gzipped. The UploadSize is the size of the gzipped content. gz := gzip.NewWriter(&lf.gzipped) if _, err := io.Copy(gz, f); err != nil { return nil, err } if err := gz.Close(); err != nil { return nil, err } lf.UploadSize = int64(lf.gzipped.Len()) } else { // Raw content. Just get the UploadSize. info, err := f.Stat() if err != nil { return nil, err } lf.UploadSize = info.Size() } return lf, nil } // Reader returns an io.ReadCloser for reading the content to be uploaded. // The caller must call Close on the returned ReaderCloser. // The reader content may not be the same as the local file content due to // gzipping. func (lf *localFile) Reader() (io.ReadCloser, error) { if lf.matcher != nil && lf.matcher.Gzip { // We've got the gzipped contents cached in gzipped. // Note: we can't use lf.gzipped directly as a Reader, since we it discards // data after it is read, and we may read it more than once. return ioutil.NopCloser(bytes.NewReader(lf.gzipped.Bytes())), nil } // Not expected to fail since we did it successfully earlier in newLocalFile, // but could happen due to changes in the underlying filesystem. return lf.fs.Open(lf.NativePath) } // CacheControl returns the Cache-Control header to use for lf, based on the // first matching matcher (if any). func (lf *localFile) CacheControl() string { if lf.matcher == nil { return "" } return lf.matcher.CacheControl } // ContentEncoding returns the Content-Encoding header to use for lf, based // on the matcher's Content-Encoding and Gzip fields. func (lf *localFile) ContentEncoding() string { if lf.matcher == nil { return "" } if lf.matcher.Gzip { return "gzip" } return lf.matcher.ContentEncoding } // ContentType returns the Content-Type header to use for lf. // It first checks if there's a Content-Type header configured via a matching // matcher; if not, it tries to generate one based on the filename extension. // If this fails, the Content-Type will be the empty string. In this case, Go // Cloud will automatically try to infer a Content-Type based on the file // content. func (lf *localFile) ContentType() string { if lf.matcher != nil && lf.matcher.ContentType != "" { return lf.matcher.ContentType } ext := filepath.Ext(lf.NativePath) if mimeType, _, found := lf.mediaTypes.GetFirstBySuffix(strings.TrimPrefix(ext, ".")); found { return mimeType.Type() } return mime.TypeByExtension(ext) } // Force returns true if the file should be forced to re-upload based on the // matching matcher. func (lf *localFile) Force() bool { return lf.matcher != nil && lf.matcher.Force } // MD5 returns an MD5 hash of the content to be uploaded. func (lf *localFile) MD5() []byte { if len(lf.md5) > 0 { return lf.md5 } h := md5.New() r, err := lf.Reader() if err != nil { return nil } defer r.Close() if _, err := io.Copy(h, r); err != nil { return nil } lf.md5 = h.Sum(nil) return lf.md5 } // knownHiddenDirectory checks if the specified name is a well known // hidden directory. func knownHiddenDirectory(name string) bool { knownDirectories := []string{ ".well-known", } for _, dir := range knownDirectories { if name == dir { return true } } return false } // walkLocal walks the source directory and returns a flat list of files, // using localFile.SlashPath as the map keys. func walkLocal(fs afero.Fs, matchers []*matcher, include, exclude glob.Glob, mediaTypes media.Types) (map[string]*localFile, error) { retval := map[string]*localFile{} err := afero.Walk(fs, "", func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { // Skip hidden directories. if path != "" && strings.HasPrefix(info.Name(), ".") { // Except for specific hidden directories if !knownHiddenDirectory(info.Name()) { return filepath.SkipDir } } return nil } // .DS_Store is an internal MacOS attribute file; skip it. if info.Name() == ".DS_Store" { return nil } // When a file system is HFS+, its filepath is in NFD form. if runtime.GOOS == "darwin" { path = norm.NFC.String(path) } // Check include/exclude matchers. slashpath := filepath.ToSlash(path) if include != nil && !include.Match(slashpath) { jww.INFO.Printf(" dropping %q due to include\n", slashpath) return nil } if exclude != nil && exclude.Match(slashpath) { jww.INFO.Printf(" dropping %q due to exclude\n", slashpath) return nil } // Find the first matching matcher (if any). var m *matcher for _, cur := range matchers { if cur.Matches(slashpath) { m = cur break } } lf, err := newLocalFile(fs, path, slashpath, m, mediaTypes) if err != nil { return err } retval[lf.SlashPath] = lf return nil }) if err != nil { return nil, err } return retval, nil } // walkRemote walks the target bucket and returns a flat list. func walkRemote(ctx context.Context, bucket *blob.Bucket, include, exclude glob.Glob) (map[string]*blob.ListObject, error) { retval := map[string]*blob.ListObject{} iter := bucket.List(nil) for { obj, err := iter.Next(ctx) if err == io.EOF { break } if err != nil { return nil, err } // Check include/exclude matchers. if include != nil && !include.Match(obj.Key) { jww.INFO.Printf(" remote dropping %q due to include\n", obj.Key) continue } if exclude != nil && exclude.Match(obj.Key) { jww.INFO.Printf(" remote dropping %q due to exclude\n", obj.Key) continue } // If the remote didn't give us an MD5, use remote attributes MD5, if that doesn't exist compute one. // This can happen for some providers (e.g., fileblob, which uses the // local filesystem), but not for the most common Cloud providers // (S3, GCS, Azure). Although, it can happen for S3 if the blob was uploaded // via a multi-part upload. // Although it's unfortunate to have to read the file, it's likely better // than assuming a delta and re-uploading it. if len(obj.MD5) == 0 { var attrMD5 []byte attrs, err := bucket.Attributes(ctx, obj.Key) if err == nil { md5String, exists := attrs.Metadata[metaMD5Hash] if exists { attrMD5, _ = hex.DecodeString(md5String) } } if len(attrMD5) == 0 { r, err := bucket.NewReader(ctx, obj.Key, nil) if err == nil { h := md5.New() if _, err := io.Copy(h, r); err == nil { obj.MD5 = h.Sum(nil) } r.Close() } } else { obj.MD5 = attrMD5 } } retval[obj.Key] = obj } return retval, nil } // uploadReason is an enum of reasons why a file must be uploaded. type uploadReason string const ( reasonUnknown uploadReason = "unknown" reasonNotFound uploadReason = "not found at target" reasonForce uploadReason = "--force" reasonSize uploadReason = "size differs" reasonMD5Differs uploadReason = "md5 differs" reasonMD5Missing uploadReason = "remote md5 missing" ) // fileToUpload represents a single local file that should be uploaded to // the target. type fileToUpload struct { Local *localFile Reason uploadReason } func (u *fileToUpload) String() string { details := []string{humanize.Bytes(uint64(u.Local.UploadSize))} if s := u.Local.CacheControl(); s != "" { details = append(details, fmt.Sprintf("Cache-Control: %q", s)) } if s := u.Local.ContentEncoding(); s != "" { details = append(details, fmt.Sprintf("Content-Encoding: %q", s)) } if s := u.Local.ContentType(); s != "" { details = append(details, fmt.Sprintf("Content-Type: %q", s)) } return fmt.Sprintf("%s (%s): %v", u.Local.SlashPath, strings.Join(details, ", "), u.Reason) } // findDiffs diffs localFiles vs remoteFiles to see what changes should be // applied to the remote target. It returns a slice of *fileToUpload and a // slice of paths for files to delete. func findDiffs(localFiles map[string]*localFile, remoteFiles map[string]*blob.ListObject, force bool) ([]*fileToUpload, []string) { var uploads []*fileToUpload var deletes []string found := map[string]bool{} for path, lf := range localFiles { upload := false reason := reasonUnknown if remoteFile, ok := remoteFiles[path]; ok { // The file exists in remote. Let's see if we need to upload it anyway. // TODO: We don't register a diff if the metadata (e.g., Content-Type // header) has changed. This would be difficult/expensive to detect; some // providers return metadata along with their "List" result, but others // (notably AWS S3) do not, so gocloud.dev's blob.Bucket doesn't expose // it in the list result. It would require a separate request per blob // to fetch. At least for now, we work around this by documenting it and // providing a "force" flag (to re-upload everything) and a "force" bool // per matcher (to re-upload all files in a matcher whose headers may have // changed). // Idea: extract a sample set of 1 file per extension + 1 file per matcher // and check those files? if force { upload = true reason = reasonForce } else if lf.Force() { upload = true reason = reasonForce } else if lf.UploadSize != remoteFile.Size { upload = true reason = reasonSize } else if len(remoteFile.MD5) == 0 { // This shouldn't happen unless the remote didn't give us an MD5 hash // from List, AND we failed to compute one by reading the remote file. // Default to considering the files different. upload = true reason = reasonMD5Missing } else if !bytes.Equal(lf.MD5(), remoteFile.MD5) { upload = true reason = reasonMD5Differs } else { // Nope! Leave uploaded = false. } found[path] = true } else { // The file doesn't exist in remote. upload = true reason = reasonNotFound } if upload { jww.DEBUG.Printf("%s needs to be uploaded: %v\n", path, reason) uploads = append(uploads, &fileToUpload{lf, reason}) } else { jww.DEBUG.Printf("%s exists at target and does not need to be uploaded", path) } } // Remote files that weren't found locally should be deleted. for path := range remoteFiles { if !found[path] { deletes = append(deletes, path) } } return uploads, deletes } // applyOrdering returns an ordered slice of slices of uploads. // // The returned slice will have length len(ordering)+1. // // The subslice at index i, for i = 0 ... len(ordering)-1, will have all of the // uploads whose Local.SlashPath matched the regex at ordering[i] (but not any // previous ordering regex). // The subslice at index len(ordering) will have the remaining uploads that // didn't match any ordering regex. // // The subslices are sorted by Local.SlashPath. func applyOrdering(ordering []*regexp.Regexp, uploads []*fileToUpload) [][]*fileToUpload { // Sort the whole slice by Local.SlashPath first. sort.Slice(uploads, func(i, j int) bool { return uploads[i].Local.SlashPath < uploads[j].Local.SlashPath }) retval := make([][]*fileToUpload, len(ordering)+1) for _, u := range uploads { matched := false for i, re := range ordering { if re.MatchString(u.Local.SlashPath) { retval[i] = append(retval[i], u) matched = true break } } if !matched { retval[len(ordering)] = append(retval[len(ordering)], u) } } return retval }
davidejones
a6e2e38bb2283cf0d9d682a22e1f47e2615652c0
d0657a436ed9d629ecc2186558504521c30132ee
Can make this a const, no? Also, I don't think you need to ToLower it down below, since it's a const.
vangent
105
gohugoio/hugo
9,742
hugo deploy also sets an md5 attribute & checks it
Improves https://github.com/gohugoio/hugo/issues/9735 ### Problem During Hugo deploy when a remote MD5 is invalid (e.g due to multipart etag) hugo reads the entire remote file and calculates the md5 again which can be slow. ### This PR - Updates file upload so that it will also store an md5 hash in the cloud providers attributes. e.g in aws this looks like `x-amz-meta-md5chksum: 26fe392386a8123bf8956a16e08cb841` - Updates the walkremote so that if an MD5 is nonexistent/invalid then it attempts to read the attribute md5 before falling back to reading the entire remote file ### What impact does this have? Hugo deploy will be faster in the diffing stage between remote and local. **_IF_** files come through with `len(obj.MD5) == 0` but store an attribute md5. ### Caveats Only files uploaded with hugo will have this attribute. **Existing users** Existing hugo deploy users running this in a new release would only get the attributes set on files that are uploaded going forward. If they want all files to have the md5 attribute then running with `--force` should work. **Other files in the bucket** If you have files uploaded by another tool in the same bucket that hugo deploy is using and these don't have valid a MD5. Then you can see a perf boost if you manually upload these to have the md5 as an attribute.
null
2022-04-03 13:12:09+00:00
2022-04-05 08:42:54+00:00
deploy/deploy.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. //go:build !nodeploy // +build !nodeploy package deploy import ( "bytes" "compress/gzip" "context" "crypto/md5" "fmt" "io" "io/ioutil" "mime" "os" "path/filepath" "regexp" "runtime" "sort" "strings" "sync" "github.com/dustin/go-humanize" "github.com/gobwas/glob" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/pkg/errors" "github.com/spf13/afero" jww "github.com/spf13/jwalterweatherman" "golang.org/x/text/unicode/norm" "gocloud.dev/blob" _ "gocloud.dev/blob/fileblob" // import _ "gocloud.dev/blob/gcsblob" // import _ "gocloud.dev/blob/s3blob" // import "gocloud.dev/gcerrors" ) // Deployer supports deploying the site to target cloud providers. type Deployer struct { localFs afero.Fs bucket *blob.Bucket target *target // the target to deploy to matchers []*matcher // matchers to apply to uploaded files mediaTypes media.Types // Hugo's MediaType to guess ContentType ordering []*regexp.Regexp // orders uploads quiet bool // true reduces STDOUT confirm bool // true enables confirmation before making changes dryRun bool // true skips conformations and prints changes instead of applying them force bool // true forces upload of all files invalidateCDN bool // true enables invalidate CDN cache (if possible) maxDeletes int // caps the # of files to delete; -1 to disable // For tests... summary deploySummary // summary of latest Deploy results } type deploySummary struct { NumLocal, NumRemote, NumUploads, NumDeletes int } // New constructs a new *Deployer. func New(cfg config.Provider, localFs afero.Fs) (*Deployer, error) { targetName := cfg.GetString("target") // Load the [deployment] section of the config. dcfg, err := decodeConfig(cfg) if err != nil { return nil, err } if len(dcfg.Targets) == 0 { return nil, errors.New("no deployment targets found") } // Find the target to deploy to. var tgt *target if targetName == "" { // Default to the first target. tgt = dcfg.Targets[0] } else { for _, t := range dcfg.Targets { if t.Name == targetName { tgt = t } } if tgt == nil { return nil, fmt.Errorf("deployment target %q not found", targetName) } } return &Deployer{ localFs: localFs, target: tgt, matchers: dcfg.Matchers, ordering: dcfg.ordering, mediaTypes: dcfg.mediaTypes, quiet: cfg.GetBool("quiet"), confirm: cfg.GetBool("confirm"), dryRun: cfg.GetBool("dryRun"), force: cfg.GetBool("force"), invalidateCDN: cfg.GetBool("invalidateCDN"), maxDeletes: cfg.GetInt("maxDeletes"), }, nil } func (d *Deployer) openBucket(ctx context.Context) (*blob.Bucket, error) { if d.bucket != nil { return d.bucket, nil } jww.FEEDBACK.Printf("Deploying to target %q (%s)\n", d.target.Name, d.target.URL) return blob.OpenBucket(ctx, d.target.URL) } // Deploy deploys the site to a target. func (d *Deployer) Deploy(ctx context.Context) error { bucket, err := d.openBucket(ctx) if err != nil { return err } // Load local files from the source directory. var include, exclude glob.Glob if d.target != nil { include, exclude = d.target.includeGlob, d.target.excludeGlob } local, err := walkLocal(d.localFs, d.matchers, include, exclude, d.mediaTypes) if err != nil { return err } jww.INFO.Printf("Found %d local files.\n", len(local)) d.summary.NumLocal = len(local) // Load remote files from the target. remote, err := walkRemote(ctx, bucket, include, exclude) if err != nil { return err } jww.INFO.Printf("Found %d remote files.\n", len(remote)) d.summary.NumRemote = len(remote) // Diff local vs remote to see what changes need to be applied. uploads, deletes := findDiffs(local, remote, d.force) d.summary.NumUploads = len(uploads) d.summary.NumDeletes = len(deletes) if len(uploads)+len(deletes) == 0 { if !d.quiet { jww.FEEDBACK.Println("No changes required.") } return nil } if !d.quiet { jww.FEEDBACK.Println(summarizeChanges(uploads, deletes)) } // Ask for confirmation before proceeding. if d.confirm && !d.dryRun { fmt.Printf("Continue? (Y/n) ") var confirm string if _, err := fmt.Scanln(&confirm); err != nil { return err } if confirm != "" && confirm[0] != 'y' && confirm[0] != 'Y' { return errors.New("aborted") } } // Order the uploads. They are organized in groups; all uploads in a group // must be complete before moving on to the next group. uploadGroups := applyOrdering(d.ordering, uploads) // Apply the changes in parallel, using an inverted worker // pool (https://www.youtube.com/watch?v=5zXAHh5tJqQ&t=26m58s). // sem prevents more than nParallel concurrent goroutines. const nParallel = 10 var errs []error var errMu sync.Mutex // protects errs for _, uploads := range uploadGroups { // Short-circuit for an empty group. if len(uploads) == 0 { continue } // Within the group, apply uploads in parallel. sem := make(chan struct{}, nParallel) for _, upload := range uploads { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would upload: %v\n", upload) } continue } sem <- struct{}{} go func(upload *fileToUpload) { if err := doSingleUpload(ctx, bucket, upload); err != nil { errMu.Lock() defer errMu.Unlock() errs = append(errs, err) } <-sem }(upload) } // Wait for all uploads in the group to finish. for n := nParallel; n > 0; n-- { sem <- struct{}{} } } if d.maxDeletes != -1 && len(deletes) > d.maxDeletes { jww.WARN.Printf("Skipping %d deletes because it is more than --maxDeletes (%d). If this is expected, set --maxDeletes to a larger number, or -1 to disable this check.\n", len(deletes), d.maxDeletes) d.summary.NumDeletes = 0 } else { // Apply deletes in parallel. sort.Slice(deletes, func(i, j int) bool { return deletes[i] < deletes[j] }) sem := make(chan struct{}, nParallel) for _, del := range deletes { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would delete %s\n", del) } continue } sem <- struct{}{} go func(del string) { jww.INFO.Printf("Deleting %s...\n", del) if err := bucket.Delete(ctx, del); err != nil { if gcerrors.Code(err) == gcerrors.NotFound { jww.WARN.Printf("Failed to delete %q because it wasn't found: %v", del, err) } else { errMu.Lock() defer errMu.Unlock() errs = append(errs, err) } } <-sem }(del) } // Wait for all deletes to finish. for n := nParallel; n > 0; n-- { sem <- struct{}{} } } if len(errs) > 0 { if !d.quiet { jww.FEEDBACK.Printf("Encountered %d errors.\n", len(errs)) } return errs[0] } if !d.quiet { jww.FEEDBACK.Println("Success!") } if d.invalidateCDN { if d.target.CloudFrontDistributionID != "" { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would invalidate CloudFront CDN with ID %s\n", d.target.CloudFrontDistributionID) } } else { jww.FEEDBACK.Println("Invalidating CloudFront CDN...") if err := InvalidateCloudFront(ctx, d.target.CloudFrontDistributionID); err != nil { jww.FEEDBACK.Printf("Failed to invalidate CloudFront CDN: %v\n", err) return err } } } if d.target.GoogleCloudCDNOrigin != "" { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would invalidate Google Cloud CDN with origin %s\n", d.target.GoogleCloudCDNOrigin) } } else { jww.FEEDBACK.Println("Invalidating Google Cloud CDN...") if err := InvalidateGoogleCloudCDN(ctx, d.target.GoogleCloudCDNOrigin); err != nil { jww.FEEDBACK.Printf("Failed to invalidate Google Cloud CDN: %v\n", err) return err } } } jww.FEEDBACK.Println("Success!") } return nil } // summarizeChanges creates a text description of the proposed changes. func summarizeChanges(uploads []*fileToUpload, deletes []string) string { uploadSize := int64(0) for _, u := range uploads { uploadSize += u.Local.UploadSize } return fmt.Sprintf("Identified %d file(s) to upload, totaling %s, and %d file(s) to delete.", len(uploads), humanize.Bytes(uint64(uploadSize)), len(deletes)) } // doSingleUpload executes a single file upload. func doSingleUpload(ctx context.Context, bucket *blob.Bucket, upload *fileToUpload) error { jww.INFO.Printf("Uploading %v...\n", upload) opts := &blob.WriterOptions{ CacheControl: upload.Local.CacheControl(), ContentEncoding: upload.Local.ContentEncoding(), ContentType: upload.Local.ContentType(), } w, err := bucket.NewWriter(ctx, upload.Local.SlashPath, opts) if err != nil { return err } r, err := upload.Local.Reader() if err != nil { return err } defer r.Close() _, err = io.Copy(w, r) if err != nil { return err } if err := w.Close(); err != nil { return err } return nil } // localFile represents a local file from the source. Use newLocalFile to // construct one. type localFile struct { // NativePath is the native path to the file (using file.Separator). NativePath string // SlashPath is NativePath converted to use /. SlashPath string // UploadSize is the size of the content to be uploaded. It may not // be the same as the local file size if the content will be // gzipped before upload. UploadSize int64 fs afero.Fs matcher *matcher md5 []byte // cache gzipped bytes.Buffer // cached of gzipped contents if gzipping mediaTypes media.Types } // newLocalFile initializes a *localFile. func newLocalFile(fs afero.Fs, nativePath, slashpath string, m *matcher, mt media.Types) (*localFile, error) { f, err := fs.Open(nativePath) if err != nil { return nil, err } defer f.Close() lf := &localFile{ NativePath: nativePath, SlashPath: slashpath, fs: fs, matcher: m, mediaTypes: mt, } if m != nil && m.Gzip { // We're going to gzip the content. Do it once now, and cache the result // in gzipped. The UploadSize is the size of the gzipped content. gz := gzip.NewWriter(&lf.gzipped) if _, err := io.Copy(gz, f); err != nil { return nil, err } if err := gz.Close(); err != nil { return nil, err } lf.UploadSize = int64(lf.gzipped.Len()) } else { // Raw content. Just get the UploadSize. info, err := f.Stat() if err != nil { return nil, err } lf.UploadSize = info.Size() } return lf, nil } // Reader returns an io.ReadCloser for reading the content to be uploaded. // The caller must call Close on the returned ReaderCloser. // The reader content may not be the same as the local file content due to // gzipping. func (lf *localFile) Reader() (io.ReadCloser, error) { if lf.matcher != nil && lf.matcher.Gzip { // We've got the gzipped contents cached in gzipped. // Note: we can't use lf.gzipped directly as a Reader, since we it discards // data after it is read, and we may read it more than once. return ioutil.NopCloser(bytes.NewReader(lf.gzipped.Bytes())), nil } // Not expected to fail since we did it successfully earlier in newLocalFile, // but could happen due to changes in the underlying filesystem. return lf.fs.Open(lf.NativePath) } // CacheControl returns the Cache-Control header to use for lf, based on the // first matching matcher (if any). func (lf *localFile) CacheControl() string { if lf.matcher == nil { return "" } return lf.matcher.CacheControl } // ContentEncoding returns the Content-Encoding header to use for lf, based // on the matcher's Content-Encoding and Gzip fields. func (lf *localFile) ContentEncoding() string { if lf.matcher == nil { return "" } if lf.matcher.Gzip { return "gzip" } return lf.matcher.ContentEncoding } // ContentType returns the Content-Type header to use for lf. // It first checks if there's a Content-Type header configured via a matching // matcher; if not, it tries to generate one based on the filename extension. // If this fails, the Content-Type will be the empty string. In this case, Go // Cloud will automatically try to infer a Content-Type based on the file // content. func (lf *localFile) ContentType() string { if lf.matcher != nil && lf.matcher.ContentType != "" { return lf.matcher.ContentType } ext := filepath.Ext(lf.NativePath) if mimeType, _, found := lf.mediaTypes.GetFirstBySuffix(strings.TrimPrefix(ext, ".")); found { return mimeType.Type() } return mime.TypeByExtension(ext) } // Force returns true if the file should be forced to re-upload based on the // matching matcher. func (lf *localFile) Force() bool { return lf.matcher != nil && lf.matcher.Force } // MD5 returns an MD5 hash of the content to be uploaded. func (lf *localFile) MD5() []byte { if len(lf.md5) > 0 { return lf.md5 } h := md5.New() r, err := lf.Reader() if err != nil { return nil } defer r.Close() if _, err := io.Copy(h, r); err != nil { return nil } lf.md5 = h.Sum(nil) return lf.md5 } // knownHiddenDirectory checks if the specified name is a well known // hidden directory. func knownHiddenDirectory(name string) bool { knownDirectories := []string{ ".well-known", } for _, dir := range knownDirectories { if name == dir { return true } } return false } // walkLocal walks the source directory and returns a flat list of files, // using localFile.SlashPath as the map keys. func walkLocal(fs afero.Fs, matchers []*matcher, include, exclude glob.Glob, mediaTypes media.Types) (map[string]*localFile, error) { retval := map[string]*localFile{} err := afero.Walk(fs, "", func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { // Skip hidden directories. if path != "" && strings.HasPrefix(info.Name(), ".") { // Except for specific hidden directories if !knownHiddenDirectory(info.Name()) { return filepath.SkipDir } } return nil } // .DS_Store is an internal MacOS attribute file; skip it. if info.Name() == ".DS_Store" { return nil } // When a file system is HFS+, its filepath is in NFD form. if runtime.GOOS == "darwin" { path = norm.NFC.String(path) } // Check include/exclude matchers. slashpath := filepath.ToSlash(path) if include != nil && !include.Match(slashpath) { jww.INFO.Printf(" dropping %q due to include\n", slashpath) return nil } if exclude != nil && exclude.Match(slashpath) { jww.INFO.Printf(" dropping %q due to exclude\n", slashpath) return nil } // Find the first matching matcher (if any). var m *matcher for _, cur := range matchers { if cur.Matches(slashpath) { m = cur break } } lf, err := newLocalFile(fs, path, slashpath, m, mediaTypes) if err != nil { return err } retval[lf.SlashPath] = lf return nil }) if err != nil { return nil, err } return retval, nil } // walkRemote walks the target bucket and returns a flat list. func walkRemote(ctx context.Context, bucket *blob.Bucket, include, exclude glob.Glob) (map[string]*blob.ListObject, error) { retval := map[string]*blob.ListObject{} iter := bucket.List(nil) for { obj, err := iter.Next(ctx) if err == io.EOF { break } if err != nil { return nil, err } // Check include/exclude matchers. if include != nil && !include.Match(obj.Key) { jww.INFO.Printf(" remote dropping %q due to include\n", obj.Key) continue } if exclude != nil && exclude.Match(obj.Key) { jww.INFO.Printf(" remote dropping %q due to exclude\n", obj.Key) continue } // If the remote didn't give us an MD5, compute one. // This can happen for some providers (e.g., fileblob, which uses the // local filesystem), but not for the most common Cloud providers // (S3, GCS, Azure). Although, it can happen for S3 if the blob was uploaded // via a multi-part upload. // Although it's unfortunate to have to read the file, it's likely better // than assuming a delta and re-uploading it. if len(obj.MD5) == 0 { r, err := bucket.NewReader(ctx, obj.Key, nil) if err == nil { h := md5.New() if _, err := io.Copy(h, r); err == nil { obj.MD5 = h.Sum(nil) } r.Close() } } retval[obj.Key] = obj } return retval, nil } // uploadReason is an enum of reasons why a file must be uploaded. type uploadReason string const ( reasonUnknown uploadReason = "unknown" reasonNotFound uploadReason = "not found at target" reasonForce uploadReason = "--force" reasonSize uploadReason = "size differs" reasonMD5Differs uploadReason = "md5 differs" reasonMD5Missing uploadReason = "remote md5 missing" ) // fileToUpload represents a single local file that should be uploaded to // the target. type fileToUpload struct { Local *localFile Reason uploadReason } func (u *fileToUpload) String() string { details := []string{humanize.Bytes(uint64(u.Local.UploadSize))} if s := u.Local.CacheControl(); s != "" { details = append(details, fmt.Sprintf("Cache-Control: %q", s)) } if s := u.Local.ContentEncoding(); s != "" { details = append(details, fmt.Sprintf("Content-Encoding: %q", s)) } if s := u.Local.ContentType(); s != "" { details = append(details, fmt.Sprintf("Content-Type: %q", s)) } return fmt.Sprintf("%s (%s): %v", u.Local.SlashPath, strings.Join(details, ", "), u.Reason) } // findDiffs diffs localFiles vs remoteFiles to see what changes should be // applied to the remote target. It returns a slice of *fileToUpload and a // slice of paths for files to delete. func findDiffs(localFiles map[string]*localFile, remoteFiles map[string]*blob.ListObject, force bool) ([]*fileToUpload, []string) { var uploads []*fileToUpload var deletes []string found := map[string]bool{} for path, lf := range localFiles { upload := false reason := reasonUnknown if remoteFile, ok := remoteFiles[path]; ok { // The file exists in remote. Let's see if we need to upload it anyway. // TODO: We don't register a diff if the metadata (e.g., Content-Type // header) has changed. This would be difficult/expensive to detect; some // providers return metadata along with their "List" result, but others // (notably AWS S3) do not, so gocloud.dev's blob.Bucket doesn't expose // it in the list result. It would require a separate request per blob // to fetch. At least for now, we work around this by documenting it and // providing a "force" flag (to re-upload everything) and a "force" bool // per matcher (to re-upload all files in a matcher whose headers may have // changed). // Idea: extract a sample set of 1 file per extension + 1 file per matcher // and check those files? if force { upload = true reason = reasonForce } else if lf.Force() { upload = true reason = reasonForce } else if lf.UploadSize != remoteFile.Size { upload = true reason = reasonSize } else if len(remoteFile.MD5) == 0 { // This shouldn't happen unless the remote didn't give us an MD5 hash // from List, AND we failed to compute one by reading the remote file. // Default to considering the files different. upload = true reason = reasonMD5Missing } else if !bytes.Equal(lf.MD5(), remoteFile.MD5) { upload = true reason = reasonMD5Differs } else { // Nope! Leave uploaded = false. } found[path] = true } else { // The file doesn't exist in remote. upload = true reason = reasonNotFound } if upload { jww.DEBUG.Printf("%s needs to be uploaded: %v\n", path, reason) uploads = append(uploads, &fileToUpload{lf, reason}) } else { jww.DEBUG.Printf("%s exists at target and does not need to be uploaded", path) } } // Remote files that weren't found locally should be deleted. for path := range remoteFiles { if !found[path] { deletes = append(deletes, path) } } return uploads, deletes } // applyOrdering returns an ordered slice of slices of uploads. // // The returned slice will have length len(ordering)+1. // // The subslice at index i, for i = 0 ... len(ordering)-1, will have all of the // uploads whose Local.SlashPath matched the regex at ordering[i] (but not any // previous ordering regex). // The subslice at index len(ordering) will have the remaining uploads that // didn't match any ordering regex. // // The subslices are sorted by Local.SlashPath. func applyOrdering(ordering []*regexp.Regexp, uploads []*fileToUpload) [][]*fileToUpload { // Sort the whole slice by Local.SlashPath first. sort.Slice(uploads, func(i, j int) bool { return uploads[i].Local.SlashPath < uploads[j].Local.SlashPath }) retval := make([][]*fileToUpload, len(ordering)+1) for _, u := range uploads { matched := false for i, re := range ordering { if re.MatchString(u.Local.SlashPath) { retval[i] = append(retval[i], u) matched = true break } } if !matched { retval[len(ordering)] = append(retval[len(ordering)], u) } } return retval }
// 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. //go:build !nodeploy // +build !nodeploy package deploy import ( "bytes" "compress/gzip" "context" "crypto/md5" "encoding/hex" "fmt" "io" "io/ioutil" "mime" "os" "path/filepath" "regexp" "runtime" "sort" "strings" "sync" "github.com/dustin/go-humanize" "github.com/gobwas/glob" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/pkg/errors" "github.com/spf13/afero" jww "github.com/spf13/jwalterweatherman" "golang.org/x/text/unicode/norm" "gocloud.dev/blob" _ "gocloud.dev/blob/fileblob" // import _ "gocloud.dev/blob/gcsblob" // import _ "gocloud.dev/blob/s3blob" // import "gocloud.dev/gcerrors" ) // Deployer supports deploying the site to target cloud providers. type Deployer struct { localFs afero.Fs bucket *blob.Bucket target *target // the target to deploy to matchers []*matcher // matchers to apply to uploaded files mediaTypes media.Types // Hugo's MediaType to guess ContentType ordering []*regexp.Regexp // orders uploads quiet bool // true reduces STDOUT confirm bool // true enables confirmation before making changes dryRun bool // true skips conformations and prints changes instead of applying them force bool // true forces upload of all files invalidateCDN bool // true enables invalidate CDN cache (if possible) maxDeletes int // caps the # of files to delete; -1 to disable // For tests... summary deploySummary // summary of latest Deploy results } type deploySummary struct { NumLocal, NumRemote, NumUploads, NumDeletes int } const metaMD5Hash = "md5chksum" // the meta key to store md5hash in // New constructs a new *Deployer. func New(cfg config.Provider, localFs afero.Fs) (*Deployer, error) { targetName := cfg.GetString("target") // Load the [deployment] section of the config. dcfg, err := decodeConfig(cfg) if err != nil { return nil, err } if len(dcfg.Targets) == 0 { return nil, errors.New("no deployment targets found") } // Find the target to deploy to. var tgt *target if targetName == "" { // Default to the first target. tgt = dcfg.Targets[0] } else { for _, t := range dcfg.Targets { if t.Name == targetName { tgt = t } } if tgt == nil { return nil, fmt.Errorf("deployment target %q not found", targetName) } } return &Deployer{ localFs: localFs, target: tgt, matchers: dcfg.Matchers, ordering: dcfg.ordering, mediaTypes: dcfg.mediaTypes, quiet: cfg.GetBool("quiet"), confirm: cfg.GetBool("confirm"), dryRun: cfg.GetBool("dryRun"), force: cfg.GetBool("force"), invalidateCDN: cfg.GetBool("invalidateCDN"), maxDeletes: cfg.GetInt("maxDeletes"), }, nil } func (d *Deployer) openBucket(ctx context.Context) (*blob.Bucket, error) { if d.bucket != nil { return d.bucket, nil } jww.FEEDBACK.Printf("Deploying to target %q (%s)\n", d.target.Name, d.target.URL) return blob.OpenBucket(ctx, d.target.URL) } // Deploy deploys the site to a target. func (d *Deployer) Deploy(ctx context.Context) error { bucket, err := d.openBucket(ctx) if err != nil { return err } // Load local files from the source directory. var include, exclude glob.Glob if d.target != nil { include, exclude = d.target.includeGlob, d.target.excludeGlob } local, err := walkLocal(d.localFs, d.matchers, include, exclude, d.mediaTypes) if err != nil { return err } jww.INFO.Printf("Found %d local files.\n", len(local)) d.summary.NumLocal = len(local) // Load remote files from the target. remote, err := walkRemote(ctx, bucket, include, exclude) if err != nil { return err } jww.INFO.Printf("Found %d remote files.\n", len(remote)) d.summary.NumRemote = len(remote) // Diff local vs remote to see what changes need to be applied. uploads, deletes := findDiffs(local, remote, d.force) d.summary.NumUploads = len(uploads) d.summary.NumDeletes = len(deletes) if len(uploads)+len(deletes) == 0 { if !d.quiet { jww.FEEDBACK.Println("No changes required.") } return nil } if !d.quiet { jww.FEEDBACK.Println(summarizeChanges(uploads, deletes)) } // Ask for confirmation before proceeding. if d.confirm && !d.dryRun { fmt.Printf("Continue? (Y/n) ") var confirm string if _, err := fmt.Scanln(&confirm); err != nil { return err } if confirm != "" && confirm[0] != 'y' && confirm[0] != 'Y' { return errors.New("aborted") } } // Order the uploads. They are organized in groups; all uploads in a group // must be complete before moving on to the next group. uploadGroups := applyOrdering(d.ordering, uploads) // Apply the changes in parallel, using an inverted worker // pool (https://www.youtube.com/watch?v=5zXAHh5tJqQ&t=26m58s). // sem prevents more than nParallel concurrent goroutines. const nParallel = 10 var errs []error var errMu sync.Mutex // protects errs for _, uploads := range uploadGroups { // Short-circuit for an empty group. if len(uploads) == 0 { continue } // Within the group, apply uploads in parallel. sem := make(chan struct{}, nParallel) for _, upload := range uploads { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would upload: %v\n", upload) } continue } sem <- struct{}{} go func(upload *fileToUpload) { if err := doSingleUpload(ctx, bucket, upload); err != nil { errMu.Lock() defer errMu.Unlock() errs = append(errs, err) } <-sem }(upload) } // Wait for all uploads in the group to finish. for n := nParallel; n > 0; n-- { sem <- struct{}{} } } if d.maxDeletes != -1 && len(deletes) > d.maxDeletes { jww.WARN.Printf("Skipping %d deletes because it is more than --maxDeletes (%d). If this is expected, set --maxDeletes to a larger number, or -1 to disable this check.\n", len(deletes), d.maxDeletes) d.summary.NumDeletes = 0 } else { // Apply deletes in parallel. sort.Slice(deletes, func(i, j int) bool { return deletes[i] < deletes[j] }) sem := make(chan struct{}, nParallel) for _, del := range deletes { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would delete %s\n", del) } continue } sem <- struct{}{} go func(del string) { jww.INFO.Printf("Deleting %s...\n", del) if err := bucket.Delete(ctx, del); err != nil { if gcerrors.Code(err) == gcerrors.NotFound { jww.WARN.Printf("Failed to delete %q because it wasn't found: %v", del, err) } else { errMu.Lock() defer errMu.Unlock() errs = append(errs, err) } } <-sem }(del) } // Wait for all deletes to finish. for n := nParallel; n > 0; n-- { sem <- struct{}{} } } if len(errs) > 0 { if !d.quiet { jww.FEEDBACK.Printf("Encountered %d errors.\n", len(errs)) } return errs[0] } if !d.quiet { jww.FEEDBACK.Println("Success!") } if d.invalidateCDN { if d.target.CloudFrontDistributionID != "" { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would invalidate CloudFront CDN with ID %s\n", d.target.CloudFrontDistributionID) } } else { jww.FEEDBACK.Println("Invalidating CloudFront CDN...") if err := InvalidateCloudFront(ctx, d.target.CloudFrontDistributionID); err != nil { jww.FEEDBACK.Printf("Failed to invalidate CloudFront CDN: %v\n", err) return err } } } if d.target.GoogleCloudCDNOrigin != "" { if d.dryRun { if !d.quiet { jww.FEEDBACK.Printf("[DRY RUN] Would invalidate Google Cloud CDN with origin %s\n", d.target.GoogleCloudCDNOrigin) } } else { jww.FEEDBACK.Println("Invalidating Google Cloud CDN...") if err := InvalidateGoogleCloudCDN(ctx, d.target.GoogleCloudCDNOrigin); err != nil { jww.FEEDBACK.Printf("Failed to invalidate Google Cloud CDN: %v\n", err) return err } } } jww.FEEDBACK.Println("Success!") } return nil } // summarizeChanges creates a text description of the proposed changes. func summarizeChanges(uploads []*fileToUpload, deletes []string) string { uploadSize := int64(0) for _, u := range uploads { uploadSize += u.Local.UploadSize } return fmt.Sprintf("Identified %d file(s) to upload, totaling %s, and %d file(s) to delete.", len(uploads), humanize.Bytes(uint64(uploadSize)), len(deletes)) } // doSingleUpload executes a single file upload. func doSingleUpload(ctx context.Context, bucket *blob.Bucket, upload *fileToUpload) error { jww.INFO.Printf("Uploading %v...\n", upload) opts := &blob.WriterOptions{ CacheControl: upload.Local.CacheControl(), ContentEncoding: upload.Local.ContentEncoding(), ContentType: upload.Local.ContentType(), Metadata: map[string]string{metaMD5Hash: hex.EncodeToString(upload.Local.MD5())}, } w, err := bucket.NewWriter(ctx, upload.Local.SlashPath, opts) if err != nil { return err } r, err := upload.Local.Reader() if err != nil { return err } defer r.Close() _, err = io.Copy(w, r) if err != nil { return err } if err := w.Close(); err != nil { return err } return nil } // localFile represents a local file from the source. Use newLocalFile to // construct one. type localFile struct { // NativePath is the native path to the file (using file.Separator). NativePath string // SlashPath is NativePath converted to use /. SlashPath string // UploadSize is the size of the content to be uploaded. It may not // be the same as the local file size if the content will be // gzipped before upload. UploadSize int64 fs afero.Fs matcher *matcher md5 []byte // cache gzipped bytes.Buffer // cached of gzipped contents if gzipping mediaTypes media.Types } // newLocalFile initializes a *localFile. func newLocalFile(fs afero.Fs, nativePath, slashpath string, m *matcher, mt media.Types) (*localFile, error) { f, err := fs.Open(nativePath) if err != nil { return nil, err } defer f.Close() lf := &localFile{ NativePath: nativePath, SlashPath: slashpath, fs: fs, matcher: m, mediaTypes: mt, } if m != nil && m.Gzip { // We're going to gzip the content. Do it once now, and cache the result // in gzipped. The UploadSize is the size of the gzipped content. gz := gzip.NewWriter(&lf.gzipped) if _, err := io.Copy(gz, f); err != nil { return nil, err } if err := gz.Close(); err != nil { return nil, err } lf.UploadSize = int64(lf.gzipped.Len()) } else { // Raw content. Just get the UploadSize. info, err := f.Stat() if err != nil { return nil, err } lf.UploadSize = info.Size() } return lf, nil } // Reader returns an io.ReadCloser for reading the content to be uploaded. // The caller must call Close on the returned ReaderCloser. // The reader content may not be the same as the local file content due to // gzipping. func (lf *localFile) Reader() (io.ReadCloser, error) { if lf.matcher != nil && lf.matcher.Gzip { // We've got the gzipped contents cached in gzipped. // Note: we can't use lf.gzipped directly as a Reader, since we it discards // data after it is read, and we may read it more than once. return ioutil.NopCloser(bytes.NewReader(lf.gzipped.Bytes())), nil } // Not expected to fail since we did it successfully earlier in newLocalFile, // but could happen due to changes in the underlying filesystem. return lf.fs.Open(lf.NativePath) } // CacheControl returns the Cache-Control header to use for lf, based on the // first matching matcher (if any). func (lf *localFile) CacheControl() string { if lf.matcher == nil { return "" } return lf.matcher.CacheControl } // ContentEncoding returns the Content-Encoding header to use for lf, based // on the matcher's Content-Encoding and Gzip fields. func (lf *localFile) ContentEncoding() string { if lf.matcher == nil { return "" } if lf.matcher.Gzip { return "gzip" } return lf.matcher.ContentEncoding } // ContentType returns the Content-Type header to use for lf. // It first checks if there's a Content-Type header configured via a matching // matcher; if not, it tries to generate one based on the filename extension. // If this fails, the Content-Type will be the empty string. In this case, Go // Cloud will automatically try to infer a Content-Type based on the file // content. func (lf *localFile) ContentType() string { if lf.matcher != nil && lf.matcher.ContentType != "" { return lf.matcher.ContentType } ext := filepath.Ext(lf.NativePath) if mimeType, _, found := lf.mediaTypes.GetFirstBySuffix(strings.TrimPrefix(ext, ".")); found { return mimeType.Type() } return mime.TypeByExtension(ext) } // Force returns true if the file should be forced to re-upload based on the // matching matcher. func (lf *localFile) Force() bool { return lf.matcher != nil && lf.matcher.Force } // MD5 returns an MD5 hash of the content to be uploaded. func (lf *localFile) MD5() []byte { if len(lf.md5) > 0 { return lf.md5 } h := md5.New() r, err := lf.Reader() if err != nil { return nil } defer r.Close() if _, err := io.Copy(h, r); err != nil { return nil } lf.md5 = h.Sum(nil) return lf.md5 } // knownHiddenDirectory checks if the specified name is a well known // hidden directory. func knownHiddenDirectory(name string) bool { knownDirectories := []string{ ".well-known", } for _, dir := range knownDirectories { if name == dir { return true } } return false } // walkLocal walks the source directory and returns a flat list of files, // using localFile.SlashPath as the map keys. func walkLocal(fs afero.Fs, matchers []*matcher, include, exclude glob.Glob, mediaTypes media.Types) (map[string]*localFile, error) { retval := map[string]*localFile{} err := afero.Walk(fs, "", func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { // Skip hidden directories. if path != "" && strings.HasPrefix(info.Name(), ".") { // Except for specific hidden directories if !knownHiddenDirectory(info.Name()) { return filepath.SkipDir } } return nil } // .DS_Store is an internal MacOS attribute file; skip it. if info.Name() == ".DS_Store" { return nil } // When a file system is HFS+, its filepath is in NFD form. if runtime.GOOS == "darwin" { path = norm.NFC.String(path) } // Check include/exclude matchers. slashpath := filepath.ToSlash(path) if include != nil && !include.Match(slashpath) { jww.INFO.Printf(" dropping %q due to include\n", slashpath) return nil } if exclude != nil && exclude.Match(slashpath) { jww.INFO.Printf(" dropping %q due to exclude\n", slashpath) return nil } // Find the first matching matcher (if any). var m *matcher for _, cur := range matchers { if cur.Matches(slashpath) { m = cur break } } lf, err := newLocalFile(fs, path, slashpath, m, mediaTypes) if err != nil { return err } retval[lf.SlashPath] = lf return nil }) if err != nil { return nil, err } return retval, nil } // walkRemote walks the target bucket and returns a flat list. func walkRemote(ctx context.Context, bucket *blob.Bucket, include, exclude glob.Glob) (map[string]*blob.ListObject, error) { retval := map[string]*blob.ListObject{} iter := bucket.List(nil) for { obj, err := iter.Next(ctx) if err == io.EOF { break } if err != nil { return nil, err } // Check include/exclude matchers. if include != nil && !include.Match(obj.Key) { jww.INFO.Printf(" remote dropping %q due to include\n", obj.Key) continue } if exclude != nil && exclude.Match(obj.Key) { jww.INFO.Printf(" remote dropping %q due to exclude\n", obj.Key) continue } // If the remote didn't give us an MD5, use remote attributes MD5, if that doesn't exist compute one. // This can happen for some providers (e.g., fileblob, which uses the // local filesystem), but not for the most common Cloud providers // (S3, GCS, Azure). Although, it can happen for S3 if the blob was uploaded // via a multi-part upload. // Although it's unfortunate to have to read the file, it's likely better // than assuming a delta and re-uploading it. if len(obj.MD5) == 0 { var attrMD5 []byte attrs, err := bucket.Attributes(ctx, obj.Key) if err == nil { md5String, exists := attrs.Metadata[metaMD5Hash] if exists { attrMD5, _ = hex.DecodeString(md5String) } } if len(attrMD5) == 0 { r, err := bucket.NewReader(ctx, obj.Key, nil) if err == nil { h := md5.New() if _, err := io.Copy(h, r); err == nil { obj.MD5 = h.Sum(nil) } r.Close() } } else { obj.MD5 = attrMD5 } } retval[obj.Key] = obj } return retval, nil } // uploadReason is an enum of reasons why a file must be uploaded. type uploadReason string const ( reasonUnknown uploadReason = "unknown" reasonNotFound uploadReason = "not found at target" reasonForce uploadReason = "--force" reasonSize uploadReason = "size differs" reasonMD5Differs uploadReason = "md5 differs" reasonMD5Missing uploadReason = "remote md5 missing" ) // fileToUpload represents a single local file that should be uploaded to // the target. type fileToUpload struct { Local *localFile Reason uploadReason } func (u *fileToUpload) String() string { details := []string{humanize.Bytes(uint64(u.Local.UploadSize))} if s := u.Local.CacheControl(); s != "" { details = append(details, fmt.Sprintf("Cache-Control: %q", s)) } if s := u.Local.ContentEncoding(); s != "" { details = append(details, fmt.Sprintf("Content-Encoding: %q", s)) } if s := u.Local.ContentType(); s != "" { details = append(details, fmt.Sprintf("Content-Type: %q", s)) } return fmt.Sprintf("%s (%s): %v", u.Local.SlashPath, strings.Join(details, ", "), u.Reason) } // findDiffs diffs localFiles vs remoteFiles to see what changes should be // applied to the remote target. It returns a slice of *fileToUpload and a // slice of paths for files to delete. func findDiffs(localFiles map[string]*localFile, remoteFiles map[string]*blob.ListObject, force bool) ([]*fileToUpload, []string) { var uploads []*fileToUpload var deletes []string found := map[string]bool{} for path, lf := range localFiles { upload := false reason := reasonUnknown if remoteFile, ok := remoteFiles[path]; ok { // The file exists in remote. Let's see if we need to upload it anyway. // TODO: We don't register a diff if the metadata (e.g., Content-Type // header) has changed. This would be difficult/expensive to detect; some // providers return metadata along with their "List" result, but others // (notably AWS S3) do not, so gocloud.dev's blob.Bucket doesn't expose // it in the list result. It would require a separate request per blob // to fetch. At least for now, we work around this by documenting it and // providing a "force" flag (to re-upload everything) and a "force" bool // per matcher (to re-upload all files in a matcher whose headers may have // changed). // Idea: extract a sample set of 1 file per extension + 1 file per matcher // and check those files? if force { upload = true reason = reasonForce } else if lf.Force() { upload = true reason = reasonForce } else if lf.UploadSize != remoteFile.Size { upload = true reason = reasonSize } else if len(remoteFile.MD5) == 0 { // This shouldn't happen unless the remote didn't give us an MD5 hash // from List, AND we failed to compute one by reading the remote file. // Default to considering the files different. upload = true reason = reasonMD5Missing } else if !bytes.Equal(lf.MD5(), remoteFile.MD5) { upload = true reason = reasonMD5Differs } else { // Nope! Leave uploaded = false. } found[path] = true } else { // The file doesn't exist in remote. upload = true reason = reasonNotFound } if upload { jww.DEBUG.Printf("%s needs to be uploaded: %v\n", path, reason) uploads = append(uploads, &fileToUpload{lf, reason}) } else { jww.DEBUG.Printf("%s exists at target and does not need to be uploaded", path) } } // Remote files that weren't found locally should be deleted. for path := range remoteFiles { if !found[path] { deletes = append(deletes, path) } } return uploads, deletes } // applyOrdering returns an ordered slice of slices of uploads. // // The returned slice will have length len(ordering)+1. // // The subslice at index i, for i = 0 ... len(ordering)-1, will have all of the // uploads whose Local.SlashPath matched the regex at ordering[i] (but not any // previous ordering regex). // The subslice at index len(ordering) will have the remaining uploads that // didn't match any ordering regex. // // The subslices are sorted by Local.SlashPath. func applyOrdering(ordering []*regexp.Regexp, uploads []*fileToUpload) [][]*fileToUpload { // Sort the whole slice by Local.SlashPath first. sort.Slice(uploads, func(i, j int) bool { return uploads[i].Local.SlashPath < uploads[j].Local.SlashPath }) retval := make([][]*fileToUpload, len(ordering)+1) for _, u := range uploads { matched := false for i, re := range ordering { if re.MatchString(u.Local.SlashPath) { retval[i] = append(retval[i], u) matched = true break } } if !matched { retval[len(ordering)] = append(retval[len(ordering)], u) } } return retval }
davidejones
a6e2e38bb2283cf0d9d682a22e1f47e2615652c0
d0657a436ed9d629ecc2186558504521c30132ee
The `err` here is never used, so it would be more clear to use `_` instead.
vangent
106
gohugoio/hugo
9,710
tpl/crypto: Add optional encoding arg to hmac function
Closes #9709
null
2022-03-23 16:55:47+00:00
2022-03-23 18:42:57+00:00
docs/content/en/functions/hmac.md
--- title: hmac linktitle: hmac description: Compute the cryptographic checksum of a message. date: 2020-05-29 publishdate: 2020-05-29 lastmod: 2020-05-29 categories: [functions] menu: docs: parent: "functions" keywords: [hmac,checksum] signature: ["hmac HASH_TYPE KEY MESSAGE"] workson: [] hugoversion: relatedfuncs: [hmac] deprecated: false aliases: [hmac] --- `hmac` returns a cryptographic hash that uses a key to sign a message. ``` {{ hmac "sha256" "Secret key" "Hello world, gophers!"}}, <!-- returns the string "b6d11b6c53830b9d87036272ca9fe9d19306b8f9d8aa07b15da27d89e6e34f40" ``` Supported hash functions: * md5 * sha1 * sha256 * sha512
--- title: hmac linktitle: hmac description: Returns a cryptographic hash that uses a key to sign a message. date: 2020-05-29 publishdate: 2020-05-29 lastmod: 2020-05-29 categories: [functions] menu: docs: parent: "functions" keywords: [hmac,checksum] signature: ["crypto.HMAC HASH_TYPE KEY MESSAGE [ENCODING]","hmac HASH_TYPE KEY MESSAGE [ENCODING]" ] workson: [] hugoversion: relatedfuncs: [hmac] deprecated: false aliases: [] --- Set the `HASH_TYPE` argument to `md5`, `sha1`, `sha256`, or `sha512`. Set the optional `ENCODING` argument to either `hex` (default) or `binary`. ```go-html-template {{ hmac "sha256" "Secret key" "Secret message" }} 5cceb491f45f8b154e20f3b0a30ed3a6ff3027d373f85c78ffe8983180b03c84 {{ hmac "sha256" "Secret key" "Secret message" "hex" }} 5cceb491f45f8b154e20f3b0a30ed3a6ff3027d373f85c78ffe8983180b03c84 {{ hmac "sha256" "Secret key" "Secret message" "binary" | base64Encode }} XM60kfRfixVOIPOwow7Tpv8wJ9Nz+Fx4/+iYMYCwPIQ= ```
jmooring
a461e9d01a95089eca571d3a49642b01d9173c18
94e8a907694406da67e29ab376db393e199fe1cc
You could save a step and have encoding BASE64 as one of the options here.
carlmjohnson
107
gohugoio/hugo
9,637
Fix potential infinite recursion in link render hooks
Fixes #8959
null
2022-03-09 15:18:26+00:00
2022-03-10 07:19:04+00:00
markup/goldmark/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 goldmark_test import ( "fmt" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
// 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 goldmark_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Iisse #8959 func TestHookInfiniteRecursion(t *testing.T) { t.Parallel() for _, renderFunc := range []string{"markdownify", ".Page.RenderString"} { t.Run(renderFunc, func(t *testing.T) { files := ` -- config.toml -- -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org [email protected] ` files = strings.ReplaceAll(files, "RENDERFUNC", renderFunc) b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "text is already rendered, repeating it may cause infinite recursion") }) } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
bep
5697348e1732a5f64ee7467283eb0335f2ec36e8
4e14cf7607ad3afdbf65272cd5bb61dba4b415da
@jmooring do you agree with this behaviour?
bep
108
gohugoio/hugo
9,637
Fix potential infinite recursion in link render hooks
Fixes #8959
null
2022-03-09 15:18:26+00:00
2022-03-10 07:19:04+00:00
markup/goldmark/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 goldmark_test import ( "fmt" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
// 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 goldmark_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Iisse #8959 func TestHookInfiniteRecursion(t *testing.T) { t.Parallel() for _, renderFunc := range []string{"markdownify", ".Page.RenderString"} { t.Run(renderFunc, func(t *testing.T) { files := ` -- config.toml -- -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org [email protected] ` files = strings.ReplaceAll(files, "RENDERFUNC", renderFunc) b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "text is already rendered, repeating it may cause infinite recursion") }) } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
bep
5697348e1732a5f64ee7467283eb0335f2ec36e8
4e14cf7607ad3afdbf65272cd5bb61dba4b415da
Yes, but when I build from this PR I don't see a change. Also, should this trigger the error? ```text {{ "foo" | .RenderString | .RenderString }} {{ "foo" | markdownify | markdownify }} ```
jmooring
109
gohugoio/hugo
9,637
Fix potential infinite recursion in link render hooks
Fixes #8959
null
2022-03-09 15:18:26+00:00
2022-03-10 07:19:04+00:00
markup/goldmark/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 goldmark_test import ( "fmt" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
// 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 goldmark_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Iisse #8959 func TestHookInfiniteRecursion(t *testing.T) { t.Parallel() for _, renderFunc := range []string{"markdownify", ".Page.RenderString"} { t.Run(renderFunc, func(t *testing.T) { files := ` -- config.toml -- -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org [email protected] ` files = strings.ReplaceAll(files, "RENDERFUNC", renderFunc) b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "text is already rendered, repeating it may cause infinite recursion") }) } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
bep
5697348e1732a5f64ee7467283eb0335f2ec36e8
4e14cf7607ad3afdbf65272cd5bb61dba4b415da
No, I have only changed the hook interface(s) re `Text()`. This issue is about "link render hooks", right?
bep
110
gohugoio/hugo
9,637
Fix potential infinite recursion in link render hooks
Fixes #8959
null
2022-03-09 15:18:26+00:00
2022-03-10 07:19:04+00:00
markup/goldmark/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 goldmark_test import ( "fmt" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
// 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 goldmark_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Iisse #8959 func TestHookInfiniteRecursion(t *testing.T) { t.Parallel() for _, renderFunc := range []string{"markdownify", ".Page.RenderString"} { t.Run(renderFunc, func(t *testing.T) { files := ` -- config.toml -- -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org [email protected] ` files = strings.ReplaceAll(files, "RENDERFUNC", renderFunc) b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "text is already rendered, repeating it may cause infinite recursion") }) } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
bep
5697348e1732a5f64ee7467283eb0335f2ec36e8
4e14cf7607ad3afdbf65272cd5bb61dba4b415da
I get the "infinite recursion" message with this in render-link.html ``` <a href="{{ .Destination | safeURL }}" >{{ .Text | .Page.RenderString }}</a> ``` But I should also see the message when I do this: ``` <a href="{{ .Destination | safeURL }}" >{{ .Text | markdownify }}</a> ```
jmooring
111
gohugoio/hugo
9,637
Fix potential infinite recursion in link render hooks
Fixes #8959
null
2022-03-09 15:18:26+00:00
2022-03-10 07:19:04+00:00
markup/goldmark/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 goldmark_test import ( "fmt" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
// 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 goldmark_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Iisse #8959 func TestHookInfiniteRecursion(t *testing.T) { t.Parallel() for _, renderFunc := range []string{"markdownify", ".Page.RenderString"} { t.Run(renderFunc, func(t *testing.T) { files := ` -- config.toml -- -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org [email protected] ` files = strings.ReplaceAll(files, "RENDERFUNC", renderFunc) b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "text is already rendered, repeating it may cause infinite recursion") }) } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
bep
5697348e1732a5f64ee7467283eb0335f2ec36e8
4e14cf7607ad3afdbf65272cd5bb61dba4b415da
Yes you should, and I kind of assumed that it should without adding a test for it. I will fix it in a minute.
bep
112
gohugoio/hugo
9,637
Fix potential infinite recursion in link render hooks
Fixes #8959
null
2022-03-09 15:18:26+00:00
2022-03-10 07:19:04+00:00
markup/goldmark/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 goldmark_test import ( "fmt" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
// 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 goldmark_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Iisse #8959 func TestHookInfiniteRecursion(t *testing.T) { t.Parallel() for _, renderFunc := range []string{"markdownify", ".Page.RenderString"} { t.Run(renderFunc, func(t *testing.T) { files := ` -- config.toml -- -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org [email protected] ` files = strings.ReplaceAll(files, "RENDERFUNC", renderFunc) b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "text is already rendered, repeating it may cause infinite recursion") }) } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
bep
5697348e1732a5f64ee7467283eb0335f2ec36e8
4e14cf7607ad3afdbf65272cd5bb61dba4b415da
I have pushed a commit that fixes markdownify, too (and added a test, there was a typecast there that I didn't know about).
bep
113
gohugoio/hugo
9,637
Fix potential infinite recursion in link render hooks
Fixes #8959
null
2022-03-09 15:18:26+00:00
2022-03-10 07:19:04+00:00
markup/goldmark/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 goldmark_test import ( "fmt" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
// 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 goldmark_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Code Fences Simple Attributes Β§Β§AΒ§bash { .myclass id="myid" } LINE1 Β§Β§AΒ§ ## Code Fences Line Numbers Β§Β§Β§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/_default/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEbash #!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var" FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } // Iisse #8959 func TestHookInfiniteRecursion(t *testing.T) { t.Parallel() for _, renderFunc := range []string{"markdownify", ".Page.RenderString"} { t.Run(renderFunc, func(t *testing.T) { files := ` -- config.toml -- -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org [email protected] ` files = strings.ReplaceAll(files, "RENDERFUNC", renderFunc) b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "text is already rendered, repeating it may cause infinite recursion") }) } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- config.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } }
bep
5697348e1732a5f64ee7467283eb0335f2ec36e8
4e14cf7607ad3afdbf65272cd5bb61dba4b415da
Nice! Thank you for this.
jmooring
114
gohugoio/hugo
9,624
Cache reflect.MethodByName
The isolated benchmark for the function is obviously much faster: ```bash name old time/op new time/op delta GetMethodByName-10 1.21Β΅s Β± 7% 0.23Β΅s Β± 5% -81.42% (p=0.029 n=4+4) name old alloc/op new alloc/op delta GetMethodByName-10 680B Β± 0% 0B -100.00% (p=0.029 n=4+4) name old allocs/op new allocs/op delta GetMethodByName-10 20.0 Β± 0% 0.0 -100.00% (p=0.029 n=4+4) ``` But more pleasing is the overall performance looking at the site benchmarks: ```bash name old time/op new time/op delta SiteNew/Regular_Bundle_with_image-10 6.25ms Β± 2% 6.10ms Β± 2% ~ (p=0.057 n=4+4) SiteNew/Regular_Bundle_with_JSON_file-10 6.30ms Β± 2% 5.66ms Β±11% ~ (p=0.057 n=4+4) SiteNew/Regular_Tags_and_categories-10 22.2ms Β± 2% 17.4ms Β± 1% -21.88% (p=0.029 n=4+4) SiteNew/Regular_Canonify_URLs-10 108ms Β± 0% 107ms Β± 0% -1.20% (p=0.029 n=4+4) SiteNew/Regular_Deep_content_tree-10 36.1ms Β± 1% 33.8ms Β± 1% -6.44% (p=0.029 n=4+4) SiteNew/Regular_TOML_front_matter-10 24.9ms Β± 1% 22.6ms Β± 1% -9.30% (p=0.029 n=4+4) SiteNew/Regular_Many_HTML_templates-10 17.9ms Β± 1% 16.7ms Β± 1% -6.43% (p=0.029 n=4+4) SiteNew/Regular_Page_collections-10 23.3ms Β± 1% 22.0ms Β± 0% -5.58% (p=0.029 n=4+4) SiteNew/Regular_List_terms-10 8.00ms Β± 1% 7.63ms Β± 0% -4.62% (p=0.029 n=4+4) name old alloc/op new alloc/op delta SiteNew/Regular_Bundle_with_image-10 2.10MB Β± 0% 2.07MB Β± 0% -1.46% (p=0.029 n=4+4) SiteNew/Regular_Bundle_with_JSON_file-10 1.88MB Β± 0% 1.85MB Β± 0% -1.76% (p=0.029 n=4+4) SiteNew/Regular_Tags_and_categories-10 13.5MB Β± 0% 11.6MB Β± 0% -13.99% (p=0.029 n=4+4) SiteNew/Regular_Canonify_URLs-10 96.1MB Β± 0% 95.8MB Β± 0% -0.40% (p=0.029 n=4+4) SiteNew/Regular_Deep_content_tree-10 28.4MB Β± 0% 27.3MB Β± 0% -3.83% (p=0.029 n=4+4) SiteNew/Regular_TOML_front_matter-10 16.9MB Β± 0% 15.1MB Β± 0% -10.58% (p=0.029 n=4+4) SiteNew/Regular_Many_HTML_templates-10 8.98MB Β± 0% 8.44MB Β± 0% -6.04% (p=0.029 n=4+4) SiteNew/Regular_Page_collections-10 17.1MB Β± 0% 16.5MB Β± 0% -3.91% (p=0.029 n=4+4) SiteNew/Regular_List_terms-10 3.92MB Β± 0% 3.72MB Β± 0% -5.03% (p=0.029 n=4+4) name old allocs/op new allocs/op delta SiteNew/Regular_Bundle_with_image-10 25.8k Β± 0% 24.9k Β± 0% -3.49% (p=0.029 n=4+4) SiteNew/Regular_Bundle_with_JSON_file-10 25.8k Β± 0% 24.9k Β± 0% -3.49% (p=0.029 n=4+4) SiteNew/Regular_Tags_and_categories-10 288k Β± 0% 233k Β± 0% -18.90% (p=0.029 n=4+4) SiteNew/Regular_Canonify_URLs-10 375k Β± 0% 364k Β± 0% -2.80% (p=0.029 n=4+4) SiteNew/Regular_Deep_content_tree-10 314k Β± 0% 283k Β± 0% -9.77% (p=0.029 n=4+4) SiteNew/Regular_TOML_front_matter-10 302k Β± 0% 252k Β± 0% -16.55% (p=0.029 n=4+4) SiteNew/Regular_Many_HTML_templates-10 133k Β± 0% 117k Β± 0% -11.81% (p=0.029 n=4+4) SiteNew/Regular_Page_collections-10 202k Β± 0% 183k Β± 0% -9.55% (p=0.029 n=4+4) SiteNew/Regular_List_terms-10 55.6k Β± 0% 49.8k Β± 0% -10.40% (p=0.029 n=4+4) ``` Thanks to @quasilyte for the suggestion. Fixes 9386
null
2022-03-08 10:03:55+00:00
2022-03-08 18:36:56+00:00
common/hreflect/helpers.go
// Copyright 2019 The Hugo Authors. All rights reserved. // Some functions in this file (see comments) is based on the Go source code, // copyright The Go Authors and governed by a BSD-style license. // // 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 hreflect contains reflect helpers. package hreflect import ( "context" "reflect" "github.com/gohugoio/hugo/common/types" ) // TODO(bep) replace the private versions in /tpl with these. // IsNumber returns whether the given kind is a number. func IsNumber(kind reflect.Kind) bool { return IsInt(kind) || IsUint(kind) || IsFloat(kind) } // IsInt returns whether the given kind is an int. func IsInt(kind reflect.Kind) bool { switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return true default: return false } } // IsUint returns whether the given kind is an uint. func IsUint(kind reflect.Kind) bool { switch kind { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return true default: return false } } // IsFloat returns whether the given kind is a float. func IsFloat(kind reflect.Kind) bool { switch kind { case reflect.Float32, reflect.Float64: return true default: return false } } // IsTruthful returns whether in represents a truthful value. // See IsTruthfulValue func IsTruthful(in interface{}) bool { switch v := in.(type) { case reflect.Value: return IsTruthfulValue(v) default: return IsTruthfulValue(reflect.ValueOf(in)) } } var zeroType = reflect.TypeOf((*types.Zeroer)(nil)).Elem() // IsTruthfulValue returns whether the given value has a meaningful truth value. // This is based on template.IsTrue in Go's stdlib, but also considers // IsZero and any interface value will be unwrapped before it's considered // for truthfulness. // // Based on: // https://github.com/golang/go/blob/178a2c42254166cffed1b25fb1d3c7a5727cada6/src/text/template/exec.go#L306 func IsTruthfulValue(val reflect.Value) (truth bool) { val = indirectInterface(val) if !val.IsValid() { // Something like var x interface{}, never set. It's a form of nil. return } if val.Type().Implements(zeroType) { return !val.Interface().(types.Zeroer).IsZero() } switch val.Kind() { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: truth = val.Len() > 0 case reflect.Bool: truth = val.Bool() case reflect.Complex64, reflect.Complex128: truth = val.Complex() != 0 case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface: truth = !val.IsNil() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: truth = val.Int() != 0 case reflect.Float32, reflect.Float64: truth = val.Float() != 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: truth = val.Uint() != 0 case reflect.Struct: truth = true // Struct values are always true. default: return } return } // Based on: https://github.com/golang/go/blob/178a2c42254166cffed1b25fb1d3c7a5727cada6/src/text/template/exec.go#L931 func indirectInterface(v reflect.Value) reflect.Value { if v.Kind() != reflect.Interface { return v } if v.IsNil() { return reflect.Value{} } return v.Elem() } var ContextInterface = reflect.TypeOf((*context.Context)(nil)).Elem()
// Copyright 2019 The Hugo Authors. All rights reserved. // Some functions in this file (see comments) is based on the Go source code, // copyright The Go Authors and governed by a BSD-style license. // // 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 hreflect contains reflect helpers. package hreflect import ( "context" "reflect" "sync" "github.com/gohugoio/hugo/common/types" ) // TODO(bep) replace the private versions in /tpl with these. // IsNumber returns whether the given kind is a number. func IsNumber(kind reflect.Kind) bool { return IsInt(kind) || IsUint(kind) || IsFloat(kind) } // IsInt returns whether the given kind is an int. func IsInt(kind reflect.Kind) bool { switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return true default: return false } } // IsUint returns whether the given kind is an uint. func IsUint(kind reflect.Kind) bool { switch kind { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return true default: return false } } // IsFloat returns whether the given kind is a float. func IsFloat(kind reflect.Kind) bool { switch kind { case reflect.Float32, reflect.Float64: return true default: return false } } // IsTruthful returns whether in represents a truthful value. // See IsTruthfulValue func IsTruthful(in interface{}) bool { switch v := in.(type) { case reflect.Value: return IsTruthfulValue(v) default: return IsTruthfulValue(reflect.ValueOf(in)) } } var zeroType = reflect.TypeOf((*types.Zeroer)(nil)).Elem() // IsTruthfulValue returns whether the given value has a meaningful truth value. // This is based on template.IsTrue in Go's stdlib, but also considers // IsZero and any interface value will be unwrapped before it's considered // for truthfulness. // // Based on: // https://github.com/golang/go/blob/178a2c42254166cffed1b25fb1d3c7a5727cada6/src/text/template/exec.go#L306 func IsTruthfulValue(val reflect.Value) (truth bool) { val = indirectInterface(val) if !val.IsValid() { // Something like var x interface{}, never set. It's a form of nil. return } if val.Type().Implements(zeroType) { return !val.Interface().(types.Zeroer).IsZero() } switch val.Kind() { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: truth = val.Len() > 0 case reflect.Bool: truth = val.Bool() case reflect.Complex64, reflect.Complex128: truth = val.Complex() != 0 case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface: truth = !val.IsNil() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: truth = val.Int() != 0 case reflect.Float32, reflect.Float64: truth = val.Float() != 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: truth = val.Uint() != 0 case reflect.Struct: truth = true // Struct values are always true. default: return } return } type methodKey struct { typ reflect.Type name string } type methods struct { sync.RWMutex cache map[methodKey]int } var methodCache = &methods{cache: make(map[methodKey]int)} // GetMethodByName is the samve as reflect.Value.MethodByName, but it caches the // type lookup. func GetMethodByName(v reflect.Value, name string) reflect.Value { index := GetMethodIndexByName(v.Type(), name) if index == -1 { return reflect.Value{} } return v.Method(index) } // GetMethodIndexByName returns the index of the method with the given name, or // -1 if no such method exists. func GetMethodIndexByName(tp reflect.Type, name string) int { k := methodKey{tp, name} methodCache.RLock() index, found := methodCache.cache[k] methodCache.RUnlock() if found { return index } methodCache.Lock() defer methodCache.Unlock() m, ok := tp.MethodByName(name) index = m.Index if !ok { index = -1 } methodCache.cache[k] = index if !ok { return -1 } return m.Index } // Based on: https://github.com/golang/go/blob/178a2c42254166cffed1b25fb1d3c7a5727cada6/src/text/template/exec.go#L931 func indirectInterface(v reflect.Value) reflect.Value { if v.Kind() != reflect.Interface { return v } if v.IsNil() { return reflect.Value{} } return v.Elem() } var ContextInterface = reflect.TypeOf((*context.Context)(nil)).Elem()
bep
ff02d41721a32485c2f232d542d841e78f83fa9b
4576c82ed462bc9c3934f76181101df1c5a4157e
@quasilyte does this implementation make sense to you?
bep
115
gohugoio/hugo
9,579
The final batch of codeblock adjustments
Closes #9573
null
2022-02-27 16:09:54+00:00
2022-02-27 18:51:40+00:00
markup/goldmark/codeblocks/integration_test.go
// Copyright 2022 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 codeblocks_test import ( "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.SVG 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram Β§Β§Β§goat { width="600" } ---> Β§Β§Β§ ## Go Code Β§Β§Β§go fmt.Println("Hello, World!"); Β§Β§Β§ ## Golang Code Β§Β§Β§golang fmt.Println("Hello, Golang!"); Β§Β§Β§ ## Bash Code Β§Β§Β§bash { linenos=inline,hl_lines=[2,"5-6"],linenostart=32 class=blue } echo "l1"; echo "l2"; echo "l3"; echo "l4"; echo "l5"; echo "l6"; echo "l7"; echo "l8"; Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` Goat SVG:<svg class='diagram' Goat Attribute: 600| Go Language: go| Go Code: fmt.Println("Hello, World!"); Go Code: fmt.Println("Hello, Golang!"); Go Language: golang| `, "Goat SVG:<svg class='diagram' xmlns='http://www.w3.org/2000/svg' version='1.1' height='25' width='40'", "Goat Attribute: 600|", "<h2 id=\"go-code\">Go Code</h2>\nGo Code: fmt.Println(\"Hello, World!\");\n|\nGo Language: go|", "<h2 id=\"golang-code\">Golang Code</h2>\nGo Code: fmt.Println(\"Hello, Golang!\");\n|\nGo Language: golang|", "<h2 id=\"bash-code\">Bash Code</h2>\n<div class=\"highlight blue\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"ln\">32</span><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;l1&#34;</span><span class=\"p\">;</span>\n</span></span><span class=\"line hl\"><span class=\"ln\">33</span>", ) } func TestHighlightCodeblock(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code Β§Β§Β§go fmt.Println("Hello, World!"); Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "Inner: |<span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span>|", "Wrapped: |<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-go\" data-lang=\"go\"><span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span></code></pre></div>|", ) } func TestCodeChomp(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- Β§Β§Β§bash echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code Β§Β§Β§ echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code Β§Β§Β§LANGUAGE {style=monokai} echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Options: {{ .Options }}| ` testLanguage := func(language, expect string) { b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: strings.ReplaceAll(files, "LANGUAGE", language), }, ).Build() b.AssertFileContent("public/p1/index.html", expect) } testLanguage("bash", "Attributes: map[]|Options: map[style:monokai]|") testLanguage("hugo", "Attributes: map[style:monokai]|Options: map[]|") }
// Copyright 2022 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 codeblocks_test import ( "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram Β§Β§Β§goat { width="600" } ---> Β§Β§Β§ ## Go Code Β§Β§Β§go fmt.Println("Hello, World!"); Β§Β§Β§ ## Golang Code Β§Β§Β§golang fmt.Println("Hello, Golang!"); Β§Β§Β§ ## Bash Code Β§Β§Β§bash { linenos=inline,hl_lines=[2,"5-6"],linenostart=32 class=blue } echo "l1"; echo "l2"; echo "l3"; echo "l4"; echo "l5"; echo "l6"; echo "l7"; echo "l8"; Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` Goat SVG:<svg class='diagram' Goat Attribute: 600| Go Language: go| Go Code: fmt.Println("Hello, World!"); Go Code: fmt.Println("Hello, Golang!"); Go Language: golang| `, "Goat SVG:<svg class='diagram' xmlns='http://www.w3.org/2000/svg' version='1.1' height='25' width='40'", "Goat Attribute: 600|", "<h2 id=\"go-code\">Go Code</h2>\nGo Code: fmt.Println(\"Hello, World!\");\n|\nGo Language: go|", "<h2 id=\"golang-code\">Golang Code</h2>\nGo Code: fmt.Println(\"Hello, Golang!\");\n|\nGo Language: golang|", "<h2 id=\"bash-code\">Bash Code</h2>\n<div class=\"highlight blue\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"ln\">32</span><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;l1&#34;</span><span class=\"p\">;</span>\n</span></span><span class=\"line hl\"><span class=\"ln\">33</span>", ) } func TestHighlightCodeblock(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code Β§Β§Β§go fmt.Println("Hello, World!"); Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "Inner: |<span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span>|", "Wrapped: |<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-go\" data-lang=\"go\"><span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span></code></pre></div>|", ) } func TestCodeChomp(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- Β§Β§Β§bash echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code Β§Β§Β§ echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code Β§Β§Β§LANGUAGE {style=monokai} echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Options: {{ .Options }}| ` testLanguage := func(language, expect string) { b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: strings.ReplaceAll(files, "LANGUAGE", language), }, ).Build() b.AssertFileContent("public/p1/index.html", expect) } testLanguage("bash", "Attributes: map[]|Options: map[style:monokai]|") testLanguage("hugo", "Attributes: map[style:monokai]|Options: map[]|") }
bep
3ad39001df84c01a5da8ec7e008ee3835e1a7c4e
fd0c1a5e9b59954c3a09bbff45306272d5c229df
@jmooring do you agree with my definition of `Inner` here? I think this would provide the max amount of flexibility.
bep
116
gohugoio/hugo
9,579
The final batch of codeblock adjustments
Closes #9573
null
2022-02-27 16:09:54+00:00
2022-02-27 18:51:40+00:00
markup/goldmark/codeblocks/integration_test.go
// Copyright 2022 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 codeblocks_test import ( "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.SVG 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram Β§Β§Β§goat { width="600" } ---> Β§Β§Β§ ## Go Code Β§Β§Β§go fmt.Println("Hello, World!"); Β§Β§Β§ ## Golang Code Β§Β§Β§golang fmt.Println("Hello, Golang!"); Β§Β§Β§ ## Bash Code Β§Β§Β§bash { linenos=inline,hl_lines=[2,"5-6"],linenostart=32 class=blue } echo "l1"; echo "l2"; echo "l3"; echo "l4"; echo "l5"; echo "l6"; echo "l7"; echo "l8"; Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` Goat SVG:<svg class='diagram' Goat Attribute: 600| Go Language: go| Go Code: fmt.Println("Hello, World!"); Go Code: fmt.Println("Hello, Golang!"); Go Language: golang| `, "Goat SVG:<svg class='diagram' xmlns='http://www.w3.org/2000/svg' version='1.1' height='25' width='40'", "Goat Attribute: 600|", "<h2 id=\"go-code\">Go Code</h2>\nGo Code: fmt.Println(\"Hello, World!\");\n|\nGo Language: go|", "<h2 id=\"golang-code\">Golang Code</h2>\nGo Code: fmt.Println(\"Hello, Golang!\");\n|\nGo Language: golang|", "<h2 id=\"bash-code\">Bash Code</h2>\n<div class=\"highlight blue\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"ln\">32</span><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;l1&#34;</span><span class=\"p\">;</span>\n</span></span><span class=\"line hl\"><span class=\"ln\">33</span>", ) } func TestHighlightCodeblock(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code Β§Β§Β§go fmt.Println("Hello, World!"); Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "Inner: |<span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span>|", "Wrapped: |<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-go\" data-lang=\"go\"><span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span></code></pre></div>|", ) } func TestCodeChomp(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- Β§Β§Β§bash echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code Β§Β§Β§ echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code Β§Β§Β§LANGUAGE {style=monokai} echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Options: {{ .Options }}| ` testLanguage := func(language, expect string) { b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: strings.ReplaceAll(files, "LANGUAGE", language), }, ).Build() b.AssertFileContent("public/p1/index.html", expect) } testLanguage("bash", "Attributes: map[]|Options: map[style:monokai]|") testLanguage("hugo", "Attributes: map[style:monokai]|Options: map[]|") }
// Copyright 2022 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 codeblocks_test import ( "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram Β§Β§Β§goat { width="600" } ---> Β§Β§Β§ ## Go Code Β§Β§Β§go fmt.Println("Hello, World!"); Β§Β§Β§ ## Golang Code Β§Β§Β§golang fmt.Println("Hello, Golang!"); Β§Β§Β§ ## Bash Code Β§Β§Β§bash { linenos=inline,hl_lines=[2,"5-6"],linenostart=32 class=blue } echo "l1"; echo "l2"; echo "l3"; echo "l4"; echo "l5"; echo "l6"; echo "l7"; echo "l8"; Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", ` Goat SVG:<svg class='diagram' Goat Attribute: 600| Go Language: go| Go Code: fmt.Println("Hello, World!"); Go Code: fmt.Println("Hello, Golang!"); Go Language: golang| `, "Goat SVG:<svg class='diagram' xmlns='http://www.w3.org/2000/svg' version='1.1' height='25' width='40'", "Goat Attribute: 600|", "<h2 id=\"go-code\">Go Code</h2>\nGo Code: fmt.Println(\"Hello, World!\");\n|\nGo Language: go|", "<h2 id=\"golang-code\">Golang Code</h2>\nGo Code: fmt.Println(\"Hello, Golang!\");\n|\nGo Language: golang|", "<h2 id=\"bash-code\">Bash Code</h2>\n<div class=\"highlight blue\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"ln\">32</span><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;l1&#34;</span><span class=\"p\">;</span>\n</span></span><span class=\"line hl\"><span class=\"ln\">33</span>", ) } func TestHighlightCodeblock(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code Β§Β§Β§go fmt.Println("Hello, World!"); Β§Β§Β§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "Inner: |<span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span>|", "Wrapped: |<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-go\" data-lang=\"go\"><span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span></code></pre></div>|", ) } func TestCodeChomp(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- Β§Β§Β§bash echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code Β§Β§Β§ echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code Β§Β§Β§LANGUAGE {style=monokai} echo "p1"; Β§Β§Β§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Options: {{ .Options }}| ` testLanguage := func(language, expect string) { b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: strings.ReplaceAll(files, "LANGUAGE", language), }, ).Build() b.AssertFileContent("public/p1/index.html", expect) } testLanguage("bash", "Attributes: map[]|Options: map[style:monokai]|") testLanguage("hugo", "Attributes: map[style:monokai]|Options: map[]|") }
bep
3ad39001df84c01a5da8ec7e008ee3835e1a7c4e
fd0c1a5e9b59954c3a09bbff45306272d5c229df
I think so, but I'm not going to be able to try this out for a few hours. I say merge and revisit tomorrow if necessary.
jmooring
117
gohugoio/hugo
9,562
Add test for line anchor attributes with code fences
Fixes https://github.com/gohugoio/hugo/issues/9385.
null
2022-02-24 19:16:42+00:00
2022-02-24 21:54:50+00:00
markup/goldmark/convert_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 goldmark import ( "fmt" "strings" "testing" "github.com/spf13/cast" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) func convert(c *qt.C, mconf markup_config.Config, content string) converter.Result { p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) c.Assert(err, qt.IsNil) h := highlight.New(mconf.Highlight) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } conv, err := p.New(converter.DocumentContext{DocumentID: "thedoc"}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{RenderTOC: true, Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return b } func TestConvert(t *testing.T) { c := qt.New(t) // Smoke test of the default configuration. content := ` ## Links https://github.com/gohugoio/hugo/issues/6528 [Live Demo here!](https://docuapi.netlify.com/) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") <https://foo.bar/> https://bar.baz/ <[email protected]> <mailto:[email protected]> ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Custom ID {#custom} ## Auto ID * Autolink: https://gohugo.io/ * Strikethrough:~~Hi~~ Hello, world! ## Table | foo | bar | | --- | --- | | baz | bim | ## Task Lists (default on) - [x] Finish my changes[^1] - [ ] Push my commits to GitHub - [ ] Open a pull request ## Smartypants (default on) * Straight double "quotes" and single 'quotes' into β€œcurly” quote HTML entities * Dashes (β€œ--” and β€œ---”) into en- and em-dash entities * Three consecutive dots (β€œ...”) into an ellipsis entity * Apostrophes are also converted: "That was back in the '90s, that's a long time ago" ## Footnotes That's some text with a footnote.[^1] ## Definition Lists date : the datetime assigned to this page. description : the description for the content. ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ [^1]: And that's the footnote. ` // Code fences content = strings.Replace(content, "Β§Β§Β§", "```", -1) mconf := markup_config.Default mconf.Highlight.NoClasses = false mconf.Goldmark.Renderer.Unsafe = true b := convert(c, mconf, content) got := string(b.Bytes()) fmt.Println(got) // Links c.Assert(got, qt.Contains, `<a href="https://docuapi.netlify.com/">Live Demo here!</a>`) c.Assert(got, qt.Contains, `<a href="https://foo.bar/">https://foo.bar/</a>`) c.Assert(got, qt.Contains, `<a href="https://bar.baz/">https://bar.baz/</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">[email protected]</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">mailto:[email protected]</a></p>`) // Header IDs c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-1">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-2">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) // Code fences c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>") c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>") // Extensions c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`) c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`) c.Assert(got, qt.Contains, `<th>foo</th>`) c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox"> Push my commits to GitHub</li>`) c.Assert(got, qt.Contains, `Straight double &ldquo;quotes&rdquo; and single &lsquo;quotes&rsquo;`) c.Assert(got, qt.Contains, `Dashes (β€œ&ndash;” and β€œ&mdash;”) `) c.Assert(got, qt.Contains, `Three consecutive dots (β€œ&hellip;”)`) c.Assert(got, qt.Contains, `&ldquo;That was back in the &rsquo;90s, that&rsquo;s a long time ago&rdquo;`) c.Assert(got, qt.Contains, `footnote.<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`) c.Assert(got, qt.Contains, `<section class="footnotes" role="doc-endnotes">`) c.Assert(got, qt.Contains, `<dt>date</dt>`) toc, ok := b.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) tocHTML := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(tocHTML, qt.Contains, "TableOfContents") } func TestConvertAutoIDAsciiOnly(t *testing.T) { c := qt.New(t) content := ` ## God is Good: η₯žηœŸηΎŽε₯½ ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeGitHubAscii b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"god-is-good-\">") } func TestConvertAutoIDBlackfriday(t *testing.T) { c := qt.New(t) content := ` ## Let's try this, shall we? ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeBlackfriday b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"let-s-try-this-shall-we\">") } func TestConvertAttributes(t *testing.T) { c := qt.New(t) withBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = false } withTitleAndBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = true } for _, test := range []struct { name string withConfig func(conf *markup_config.Config) input string expect interface{} }{ { "Title", nil, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n", }, { "Blockquote", withBlockAttributes, "> foo\n> bar\n{#id .className attrName=attrValue class=\"class1 class2\"}\n", "<blockquote id=\"id\" class=\"className class1 class2\"><p>foo\nbar</p>\n</blockquote>\n", }, /*{ // TODO(bep) this needs an upstream fix, see https://github.com/yuin/goldmark/issues/195 "Code block, CodeFences=false", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = false }, "```bash\necho 'foo';\n```\n{.myclass}", "TODO", },*/ { "Code block, CodeFences=true", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {.myclass id=\"myid\"}\necho 'foo';\n````\n", "<div class=\"highlight myclass\" id=\"myid\"><pre style", }, { "Code block, CodeFences=true,linenos=table", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {linenos=table .myclass id=\"myid\"}\necho 'foo';\n````\n{ .adfadf }", []string{ "div class=\"highlight myclass\" id=\"myid\"><div s", "table style", }, }, { "Paragraph", withBlockAttributes, "\nHi there.\n{.myclass }", "<p class=\"myclass\">Hi there.</p>\n", }, { "Ordered list", withBlockAttributes, "\n1. First\n2. Second\n{.myclass }", "<ol class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ol>\n", }, { "Unordered list", withBlockAttributes, "\n* First\n* Second\n{.myclass }", "<ul class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ul>\n", }, { "Unordered list, indented", withBlockAttributes, `* Fruit * Apple * Orange * Banana {.fruits} * Dairy * Milk * Cheese {.dairies} {.list}`, []string{"<ul class=\"list\">\n<li>Fruit\n<ul class=\"fruits\">", "<li>Dairy\n<ul class=\"dairies\">"}, }, { "Table", withBlockAttributes, `| A | B | | ------------- |:-------------:| -----:| | AV | BV | {.myclass }`, "<table class=\"myclass\">\n<thead>", }, { "Title and Blockquote", withTitleAndBlockAttributes, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}\n> foo\n> bar\n{.myclass}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n<blockquote class=\"myclass\"><p>foo\nbar</p>\n</blockquote>\n", }, } { c.Run(test.name, func(c *qt.C) { mconf := markup_config.Default if test.withConfig != nil { test.withConfig(&mconf) } b := convert(c, mconf, test.input) got := string(b.Bytes()) for _, s := range cast.ToStringSlice(test.expect) { c.Assert(got, qt.Contains, s) } }) } } func TestConvertIssues(t *testing.T) { c := qt.New(t) // https://github.com/gohugoio/hugo/issues/7619 c.Run("Hyphen in HTML attributes", func(c *qt.C) { mconf := markup_config.Default mconf.Goldmark.Renderer.Unsafe = true input := `<custom-element> <div>This will be "slotted" into the custom element.</div> </custom-element> ` b := convert(c, mconf, input) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<custom-element>\n <div>This will be \"slotted\" into the custom element.</div>\n</custom-element>\n") }) } func TestCodeFence(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` convertForConfig := func(c *qt.C, conf highlight.Config, code, language string) string { mconf := markup_config.Default mconf.Highlight = conf p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) h := highlight.New(conf) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } content := "```" + language + "\n" + code + "\n```" c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return string(b.Bytes()) } c.Run("Basic", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "bash") // TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func. c.Assert(result, qt.Equals, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;Hugo Rocks!&#34;</span>\n</span></span></code></pre></div>") result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code class=\"language-unknown\" data-lang=\"unknown\">echo &#34;Hugo Rocks!&#34;\n</code></pre>") }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`) c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result = convertForConfig(c, cfg, lines, "bash {linenos=inline,hl_lines=[2]}") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result = convertForConfig(c, cfg, lines, "bash {linenos=true,hl_lines=[2]}") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=false,hl_lines=[2]}") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=table}") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<pre tabindex=\"0\"><code>LINE1\n") }) c.Run("No language, guess syntax", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.GuessSyntax = true cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") }) }
// 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 goldmark import ( "fmt" "strings" "testing" "github.com/spf13/cast" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) func convert(c *qt.C, mconf markup_config.Config, content string) converter.Result { p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) c.Assert(err, qt.IsNil) h := highlight.New(mconf.Highlight) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } conv, err := p.New(converter.DocumentContext{DocumentID: "thedoc"}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{RenderTOC: true, Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return b } func TestConvert(t *testing.T) { c := qt.New(t) // Smoke test of the default configuration. content := ` ## Links https://github.com/gohugoio/hugo/issues/6528 [Live Demo here!](https://docuapi.netlify.com/) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") <https://foo.bar/> https://bar.baz/ <[email protected]> <mailto:[email protected]> ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Custom ID {#custom} ## Auto ID * Autolink: https://gohugo.io/ * Strikethrough:~~Hi~~ Hello, world! ## Table | foo | bar | | --- | --- | | baz | bim | ## Task Lists (default on) - [x] Finish my changes[^1] - [ ] Push my commits to GitHub - [ ] Open a pull request ## Smartypants (default on) * Straight double "quotes" and single 'quotes' into β€œcurly” quote HTML entities * Dashes (β€œ--” and β€œ---”) into en- and em-dash entities * Three consecutive dots (β€œ...”) into an ellipsis entity * Apostrophes are also converted: "That was back in the '90s, that's a long time ago" ## Footnotes That's some text with a footnote.[^1] ## Definition Lists date : the datetime assigned to this page. description : the description for the content. ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ [^1]: And that's the footnote. ` // Code fences content = strings.Replace(content, "Β§Β§Β§", "```", -1) mconf := markup_config.Default mconf.Highlight.NoClasses = false mconf.Goldmark.Renderer.Unsafe = true b := convert(c, mconf, content) got := string(b.Bytes()) fmt.Println(got) // Links c.Assert(got, qt.Contains, `<a href="https://docuapi.netlify.com/">Live Demo here!</a>`) c.Assert(got, qt.Contains, `<a href="https://foo.bar/">https://foo.bar/</a>`) c.Assert(got, qt.Contains, `<a href="https://bar.baz/">https://bar.baz/</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">[email protected]</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">mailto:[email protected]</a></p>`) // Header IDs c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-1">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-2">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) // Code fences c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>") c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>") // Extensions c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`) c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`) c.Assert(got, qt.Contains, `<th>foo</th>`) c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox"> Push my commits to GitHub</li>`) c.Assert(got, qt.Contains, `Straight double &ldquo;quotes&rdquo; and single &lsquo;quotes&rsquo;`) c.Assert(got, qt.Contains, `Dashes (β€œ&ndash;” and β€œ&mdash;”) `) c.Assert(got, qt.Contains, `Three consecutive dots (β€œ&hellip;”)`) c.Assert(got, qt.Contains, `&ldquo;That was back in the &rsquo;90s, that&rsquo;s a long time ago&rdquo;`) c.Assert(got, qt.Contains, `footnote.<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`) c.Assert(got, qt.Contains, `<section class="footnotes" role="doc-endnotes">`) c.Assert(got, qt.Contains, `<dt>date</dt>`) toc, ok := b.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) tocHTML := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(tocHTML, qt.Contains, "TableOfContents") } func TestConvertAutoIDAsciiOnly(t *testing.T) { c := qt.New(t) content := ` ## God is Good: η₯žηœŸηΎŽε₯½ ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeGitHubAscii b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"god-is-good-\">") } func TestConvertAutoIDBlackfriday(t *testing.T) { c := qt.New(t) content := ` ## Let's try this, shall we? ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeBlackfriday b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"let-s-try-this-shall-we\">") } func TestConvertAttributes(t *testing.T) { c := qt.New(t) withBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = false } withTitleAndBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = true } for _, test := range []struct { name string withConfig func(conf *markup_config.Config) input string expect interface{} }{ { "Title", nil, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n", }, { "Blockquote", withBlockAttributes, "> foo\n> bar\n{#id .className attrName=attrValue class=\"class1 class2\"}\n", "<blockquote id=\"id\" class=\"className class1 class2\"><p>foo\nbar</p>\n</blockquote>\n", }, /*{ // TODO(bep) this needs an upstream fix, see https://github.com/yuin/goldmark/issues/195 "Code block, CodeFences=false", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = false }, "```bash\necho 'foo';\n```\n{.myclass}", "TODO", },*/ { "Code block, CodeFences=true", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {.myclass id=\"myid\"}\necho 'foo';\n````\n", "<div class=\"highlight myclass\" id=\"myid\"><pre style", }, { "Code block, CodeFences=true,linenos=table", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {linenos=table .myclass id=\"myid\"}\necho 'foo';\n````\n{ .adfadf }", []string{ "div class=\"highlight myclass\" id=\"myid\"><div s", "table style", }, }, { "Code block, CodeFences=true,lineanchors", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true conf.Highlight.NoClasses = false }, "```bash {linenos=table, anchorlinenos=true, lineanchors=org-coderef--xyz}\necho 'foo';\n```", "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class=\"lnt\" id=\"org-coderef--xyz-1\"><a style=\"outline: none; text-decoration:none; color:inherit\" href=\"#org-coderef--xyz-1\">1</a>\n</span></code></pre></td>\n<td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s1\">&#39;foo&#39;</span><span class=\"p\">;</span>\n</span></span></code></pre></td></tr></table>\n</div>\n</div>", }, { "Paragraph", withBlockAttributes, "\nHi there.\n{.myclass }", "<p class=\"myclass\">Hi there.</p>\n", }, { "Ordered list", withBlockAttributes, "\n1. First\n2. Second\n{.myclass }", "<ol class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ol>\n", }, { "Unordered list", withBlockAttributes, "\n* First\n* Second\n{.myclass }", "<ul class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ul>\n", }, { "Unordered list, indented", withBlockAttributes, `* Fruit * Apple * Orange * Banana {.fruits} * Dairy * Milk * Cheese {.dairies} {.list}`, []string{"<ul class=\"list\">\n<li>Fruit\n<ul class=\"fruits\">", "<li>Dairy\n<ul class=\"dairies\">"}, }, { "Table", withBlockAttributes, `| A | B | | ------------- |:-------------:| -----:| | AV | BV | {.myclass }`, "<table class=\"myclass\">\n<thead>", }, { "Title and Blockquote", withTitleAndBlockAttributes, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}\n> foo\n> bar\n{.myclass}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n<blockquote class=\"myclass\"><p>foo\nbar</p>\n</blockquote>\n", }, } { c.Run(test.name, func(c *qt.C) { mconf := markup_config.Default if test.withConfig != nil { test.withConfig(&mconf) } b := convert(c, mconf, test.input) got := string(b.Bytes()) for _, s := range cast.ToStringSlice(test.expect) { c.Assert(got, qt.Contains, s) } }) } } func TestConvertIssues(t *testing.T) { c := qt.New(t) // https://github.com/gohugoio/hugo/issues/7619 c.Run("Hyphen in HTML attributes", func(c *qt.C) { mconf := markup_config.Default mconf.Goldmark.Renderer.Unsafe = true input := `<custom-element> <div>This will be "slotted" into the custom element.</div> </custom-element> ` b := convert(c, mconf, input) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<custom-element>\n <div>This will be \"slotted\" into the custom element.</div>\n</custom-element>\n") }) } func TestCodeFence(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` convertForConfig := func(c *qt.C, conf highlight.Config, code, language string) string { mconf := markup_config.Default mconf.Highlight = conf p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) h := highlight.New(conf) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } content := "```" + language + "\n" + code + "\n```" c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return string(b.Bytes()) } c.Run("Basic", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "bash") // TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func. c.Assert(result, qt.Equals, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;Hugo Rocks!&#34;</span>\n</span></span></code></pre></div>") result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code class=\"language-unknown\" data-lang=\"unknown\">echo &#34;Hugo Rocks!&#34;\n</code></pre>") }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`) c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result = convertForConfig(c, cfg, lines, "bash {linenos=inline,hl_lines=[2]}") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result = convertForConfig(c, cfg, lines, "bash {linenos=true,hl_lines=[2]}") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=false,hl_lines=[2]}") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=table}") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<pre tabindex=\"0\"><code>LINE1\n") }) c.Run("No language, guess syntax", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.GuessSyntax = true cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") }) }
kaushalmodi
7248f43188c159519e1427a290267f7f69f91ded
6bffcdbd26d90dc4670cdf31f7ee622a297607af
@bep I see that in other tests, you use `"table style"` instead of this verbose expected string. How do I convert this to use `"table style"`? Thanks!
kaushalmodi
118
gohugoio/hugo
9,562
Add test for line anchor attributes with code fences
Fixes https://github.com/gohugoio/hugo/issues/9385.
null
2022-02-24 19:16:42+00:00
2022-02-24 21:54:50+00:00
markup/goldmark/convert_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 goldmark import ( "fmt" "strings" "testing" "github.com/spf13/cast" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) func convert(c *qt.C, mconf markup_config.Config, content string) converter.Result { p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) c.Assert(err, qt.IsNil) h := highlight.New(mconf.Highlight) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } conv, err := p.New(converter.DocumentContext{DocumentID: "thedoc"}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{RenderTOC: true, Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return b } func TestConvert(t *testing.T) { c := qt.New(t) // Smoke test of the default configuration. content := ` ## Links https://github.com/gohugoio/hugo/issues/6528 [Live Demo here!](https://docuapi.netlify.com/) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") <https://foo.bar/> https://bar.baz/ <[email protected]> <mailto:[email protected]> ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Custom ID {#custom} ## Auto ID * Autolink: https://gohugo.io/ * Strikethrough:~~Hi~~ Hello, world! ## Table | foo | bar | | --- | --- | | baz | bim | ## Task Lists (default on) - [x] Finish my changes[^1] - [ ] Push my commits to GitHub - [ ] Open a pull request ## Smartypants (default on) * Straight double "quotes" and single 'quotes' into β€œcurly” quote HTML entities * Dashes (β€œ--” and β€œ---”) into en- and em-dash entities * Three consecutive dots (β€œ...”) into an ellipsis entity * Apostrophes are also converted: "That was back in the '90s, that's a long time ago" ## Footnotes That's some text with a footnote.[^1] ## Definition Lists date : the datetime assigned to this page. description : the description for the content. ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ [^1]: And that's the footnote. ` // Code fences content = strings.Replace(content, "Β§Β§Β§", "```", -1) mconf := markup_config.Default mconf.Highlight.NoClasses = false mconf.Goldmark.Renderer.Unsafe = true b := convert(c, mconf, content) got := string(b.Bytes()) fmt.Println(got) // Links c.Assert(got, qt.Contains, `<a href="https://docuapi.netlify.com/">Live Demo here!</a>`) c.Assert(got, qt.Contains, `<a href="https://foo.bar/">https://foo.bar/</a>`) c.Assert(got, qt.Contains, `<a href="https://bar.baz/">https://bar.baz/</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">[email protected]</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">mailto:[email protected]</a></p>`) // Header IDs c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-1">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-2">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) // Code fences c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>") c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>") // Extensions c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`) c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`) c.Assert(got, qt.Contains, `<th>foo</th>`) c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox"> Push my commits to GitHub</li>`) c.Assert(got, qt.Contains, `Straight double &ldquo;quotes&rdquo; and single &lsquo;quotes&rsquo;`) c.Assert(got, qt.Contains, `Dashes (β€œ&ndash;” and β€œ&mdash;”) `) c.Assert(got, qt.Contains, `Three consecutive dots (β€œ&hellip;”)`) c.Assert(got, qt.Contains, `&ldquo;That was back in the &rsquo;90s, that&rsquo;s a long time ago&rdquo;`) c.Assert(got, qt.Contains, `footnote.<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`) c.Assert(got, qt.Contains, `<section class="footnotes" role="doc-endnotes">`) c.Assert(got, qt.Contains, `<dt>date</dt>`) toc, ok := b.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) tocHTML := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(tocHTML, qt.Contains, "TableOfContents") } func TestConvertAutoIDAsciiOnly(t *testing.T) { c := qt.New(t) content := ` ## God is Good: η₯žηœŸηΎŽε₯½ ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeGitHubAscii b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"god-is-good-\">") } func TestConvertAutoIDBlackfriday(t *testing.T) { c := qt.New(t) content := ` ## Let's try this, shall we? ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeBlackfriday b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"let-s-try-this-shall-we\">") } func TestConvertAttributes(t *testing.T) { c := qt.New(t) withBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = false } withTitleAndBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = true } for _, test := range []struct { name string withConfig func(conf *markup_config.Config) input string expect interface{} }{ { "Title", nil, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n", }, { "Blockquote", withBlockAttributes, "> foo\n> bar\n{#id .className attrName=attrValue class=\"class1 class2\"}\n", "<blockquote id=\"id\" class=\"className class1 class2\"><p>foo\nbar</p>\n</blockquote>\n", }, /*{ // TODO(bep) this needs an upstream fix, see https://github.com/yuin/goldmark/issues/195 "Code block, CodeFences=false", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = false }, "```bash\necho 'foo';\n```\n{.myclass}", "TODO", },*/ { "Code block, CodeFences=true", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {.myclass id=\"myid\"}\necho 'foo';\n````\n", "<div class=\"highlight myclass\" id=\"myid\"><pre style", }, { "Code block, CodeFences=true,linenos=table", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {linenos=table .myclass id=\"myid\"}\necho 'foo';\n````\n{ .adfadf }", []string{ "div class=\"highlight myclass\" id=\"myid\"><div s", "table style", }, }, { "Paragraph", withBlockAttributes, "\nHi there.\n{.myclass }", "<p class=\"myclass\">Hi there.</p>\n", }, { "Ordered list", withBlockAttributes, "\n1. First\n2. Second\n{.myclass }", "<ol class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ol>\n", }, { "Unordered list", withBlockAttributes, "\n* First\n* Second\n{.myclass }", "<ul class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ul>\n", }, { "Unordered list, indented", withBlockAttributes, `* Fruit * Apple * Orange * Banana {.fruits} * Dairy * Milk * Cheese {.dairies} {.list}`, []string{"<ul class=\"list\">\n<li>Fruit\n<ul class=\"fruits\">", "<li>Dairy\n<ul class=\"dairies\">"}, }, { "Table", withBlockAttributes, `| A | B | | ------------- |:-------------:| -----:| | AV | BV | {.myclass }`, "<table class=\"myclass\">\n<thead>", }, { "Title and Blockquote", withTitleAndBlockAttributes, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}\n> foo\n> bar\n{.myclass}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n<blockquote class=\"myclass\"><p>foo\nbar</p>\n</blockquote>\n", }, } { c.Run(test.name, func(c *qt.C) { mconf := markup_config.Default if test.withConfig != nil { test.withConfig(&mconf) } b := convert(c, mconf, test.input) got := string(b.Bytes()) for _, s := range cast.ToStringSlice(test.expect) { c.Assert(got, qt.Contains, s) } }) } } func TestConvertIssues(t *testing.T) { c := qt.New(t) // https://github.com/gohugoio/hugo/issues/7619 c.Run("Hyphen in HTML attributes", func(c *qt.C) { mconf := markup_config.Default mconf.Goldmark.Renderer.Unsafe = true input := `<custom-element> <div>This will be "slotted" into the custom element.</div> </custom-element> ` b := convert(c, mconf, input) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<custom-element>\n <div>This will be \"slotted\" into the custom element.</div>\n</custom-element>\n") }) } func TestCodeFence(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` convertForConfig := func(c *qt.C, conf highlight.Config, code, language string) string { mconf := markup_config.Default mconf.Highlight = conf p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) h := highlight.New(conf) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } content := "```" + language + "\n" + code + "\n```" c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return string(b.Bytes()) } c.Run("Basic", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "bash") // TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func. c.Assert(result, qt.Equals, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;Hugo Rocks!&#34;</span>\n</span></span></code></pre></div>") result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code class=\"language-unknown\" data-lang=\"unknown\">echo &#34;Hugo Rocks!&#34;\n</code></pre>") }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`) c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result = convertForConfig(c, cfg, lines, "bash {linenos=inline,hl_lines=[2]}") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result = convertForConfig(c, cfg, lines, "bash {linenos=true,hl_lines=[2]}") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=false,hl_lines=[2]}") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=table}") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<pre tabindex=\"0\"><code>LINE1\n") }) c.Run("No language, guess syntax", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.GuessSyntax = true cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") }) }
// 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 goldmark import ( "fmt" "strings" "testing" "github.com/spf13/cast" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) func convert(c *qt.C, mconf markup_config.Config, content string) converter.Result { p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) c.Assert(err, qt.IsNil) h := highlight.New(mconf.Highlight) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } conv, err := p.New(converter.DocumentContext{DocumentID: "thedoc"}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{RenderTOC: true, Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return b } func TestConvert(t *testing.T) { c := qt.New(t) // Smoke test of the default configuration. content := ` ## Links https://github.com/gohugoio/hugo/issues/6528 [Live Demo here!](https://docuapi.netlify.com/) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") <https://foo.bar/> https://bar.baz/ <[email protected]> <mailto:[email protected]> ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Custom ID {#custom} ## Auto ID * Autolink: https://gohugo.io/ * Strikethrough:~~Hi~~ Hello, world! ## Table | foo | bar | | --- | --- | | baz | bim | ## Task Lists (default on) - [x] Finish my changes[^1] - [ ] Push my commits to GitHub - [ ] Open a pull request ## Smartypants (default on) * Straight double "quotes" and single 'quotes' into β€œcurly” quote HTML entities * Dashes (β€œ--” and β€œ---”) into en- and em-dash entities * Three consecutive dots (β€œ...”) into an ellipsis entity * Apostrophes are also converted: "That was back in the '90s, that's a long time ago" ## Footnotes That's some text with a footnote.[^1] ## Definition Lists date : the datetime assigned to this page. description : the description for the content. ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ [^1]: And that's the footnote. ` // Code fences content = strings.Replace(content, "Β§Β§Β§", "```", -1) mconf := markup_config.Default mconf.Highlight.NoClasses = false mconf.Goldmark.Renderer.Unsafe = true b := convert(c, mconf, content) got := string(b.Bytes()) fmt.Println(got) // Links c.Assert(got, qt.Contains, `<a href="https://docuapi.netlify.com/">Live Demo here!</a>`) c.Assert(got, qt.Contains, `<a href="https://foo.bar/">https://foo.bar/</a>`) c.Assert(got, qt.Contains, `<a href="https://bar.baz/">https://bar.baz/</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">[email protected]</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">mailto:[email protected]</a></p>`) // Header IDs c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-1">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-2">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) // Code fences c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>") c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>") // Extensions c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`) c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`) c.Assert(got, qt.Contains, `<th>foo</th>`) c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox"> Push my commits to GitHub</li>`) c.Assert(got, qt.Contains, `Straight double &ldquo;quotes&rdquo; and single &lsquo;quotes&rsquo;`) c.Assert(got, qt.Contains, `Dashes (β€œ&ndash;” and β€œ&mdash;”) `) c.Assert(got, qt.Contains, `Three consecutive dots (β€œ&hellip;”)`) c.Assert(got, qt.Contains, `&ldquo;That was back in the &rsquo;90s, that&rsquo;s a long time ago&rdquo;`) c.Assert(got, qt.Contains, `footnote.<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`) c.Assert(got, qt.Contains, `<section class="footnotes" role="doc-endnotes">`) c.Assert(got, qt.Contains, `<dt>date</dt>`) toc, ok := b.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) tocHTML := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(tocHTML, qt.Contains, "TableOfContents") } func TestConvertAutoIDAsciiOnly(t *testing.T) { c := qt.New(t) content := ` ## God is Good: η₯žηœŸηΎŽε₯½ ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeGitHubAscii b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"god-is-good-\">") } func TestConvertAutoIDBlackfriday(t *testing.T) { c := qt.New(t) content := ` ## Let's try this, shall we? ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeBlackfriday b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"let-s-try-this-shall-we\">") } func TestConvertAttributes(t *testing.T) { c := qt.New(t) withBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = false } withTitleAndBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = true } for _, test := range []struct { name string withConfig func(conf *markup_config.Config) input string expect interface{} }{ { "Title", nil, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n", }, { "Blockquote", withBlockAttributes, "> foo\n> bar\n{#id .className attrName=attrValue class=\"class1 class2\"}\n", "<blockquote id=\"id\" class=\"className class1 class2\"><p>foo\nbar</p>\n</blockquote>\n", }, /*{ // TODO(bep) this needs an upstream fix, see https://github.com/yuin/goldmark/issues/195 "Code block, CodeFences=false", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = false }, "```bash\necho 'foo';\n```\n{.myclass}", "TODO", },*/ { "Code block, CodeFences=true", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {.myclass id=\"myid\"}\necho 'foo';\n````\n", "<div class=\"highlight myclass\" id=\"myid\"><pre style", }, { "Code block, CodeFences=true,linenos=table", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {linenos=table .myclass id=\"myid\"}\necho 'foo';\n````\n{ .adfadf }", []string{ "div class=\"highlight myclass\" id=\"myid\"><div s", "table style", }, }, { "Code block, CodeFences=true,lineanchors", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true conf.Highlight.NoClasses = false }, "```bash {linenos=table, anchorlinenos=true, lineanchors=org-coderef--xyz}\necho 'foo';\n```", "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class=\"lnt\" id=\"org-coderef--xyz-1\"><a style=\"outline: none; text-decoration:none; color:inherit\" href=\"#org-coderef--xyz-1\">1</a>\n</span></code></pre></td>\n<td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s1\">&#39;foo&#39;</span><span class=\"p\">;</span>\n</span></span></code></pre></td></tr></table>\n</div>\n</div>", }, { "Paragraph", withBlockAttributes, "\nHi there.\n{.myclass }", "<p class=\"myclass\">Hi there.</p>\n", }, { "Ordered list", withBlockAttributes, "\n1. First\n2. Second\n{.myclass }", "<ol class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ol>\n", }, { "Unordered list", withBlockAttributes, "\n* First\n* Second\n{.myclass }", "<ul class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ul>\n", }, { "Unordered list, indented", withBlockAttributes, `* Fruit * Apple * Orange * Banana {.fruits} * Dairy * Milk * Cheese {.dairies} {.list}`, []string{"<ul class=\"list\">\n<li>Fruit\n<ul class=\"fruits\">", "<li>Dairy\n<ul class=\"dairies\">"}, }, { "Table", withBlockAttributes, `| A | B | | ------------- |:-------------:| -----:| | AV | BV | {.myclass }`, "<table class=\"myclass\">\n<thead>", }, { "Title and Blockquote", withTitleAndBlockAttributes, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}\n> foo\n> bar\n{.myclass}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n<blockquote class=\"myclass\"><p>foo\nbar</p>\n</blockquote>\n", }, } { c.Run(test.name, func(c *qt.C) { mconf := markup_config.Default if test.withConfig != nil { test.withConfig(&mconf) } b := convert(c, mconf, test.input) got := string(b.Bytes()) for _, s := range cast.ToStringSlice(test.expect) { c.Assert(got, qt.Contains, s) } }) } } func TestConvertIssues(t *testing.T) { c := qt.New(t) // https://github.com/gohugoio/hugo/issues/7619 c.Run("Hyphen in HTML attributes", func(c *qt.C) { mconf := markup_config.Default mconf.Goldmark.Renderer.Unsafe = true input := `<custom-element> <div>This will be "slotted" into the custom element.</div> </custom-element> ` b := convert(c, mconf, input) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<custom-element>\n <div>This will be \"slotted\" into the custom element.</div>\n</custom-element>\n") }) } func TestCodeFence(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` convertForConfig := func(c *qt.C, conf highlight.Config, code, language string) string { mconf := markup_config.Default mconf.Highlight = conf p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) h := highlight.New(conf) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } content := "```" + language + "\n" + code + "\n```" c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return string(b.Bytes()) } c.Run("Basic", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "bash") // TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func. c.Assert(result, qt.Equals, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;Hugo Rocks!&#34;</span>\n</span></span></code></pre></div>") result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code class=\"language-unknown\" data-lang=\"unknown\">echo &#34;Hugo Rocks!&#34;\n</code></pre>") }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`) c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result = convertForConfig(c, cfg, lines, "bash {linenos=inline,hl_lines=[2]}") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result = convertForConfig(c, cfg, lines, "bash {linenos=true,hl_lines=[2]}") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=false,hl_lines=[2]}") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=table}") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<pre tabindex=\"0\"><code>LINE1\n") }) c.Run("No language, guess syntax", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.GuessSyntax = true cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") }) }
kaushalmodi
7248f43188c159519e1427a290267f7f69f91ded
6bffcdbd26d90dc4670cdf31f7ee622a297607af
I suspect what you want is `conf.Highlight.NoClass = true` (or something).
bep
119
gohugoio/hugo
9,562
Add test for line anchor attributes with code fences
Fixes https://github.com/gohugoio/hugo/issues/9385.
null
2022-02-24 19:16:42+00:00
2022-02-24 21:54:50+00:00
markup/goldmark/convert_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 goldmark import ( "fmt" "strings" "testing" "github.com/spf13/cast" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) func convert(c *qt.C, mconf markup_config.Config, content string) converter.Result { p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) c.Assert(err, qt.IsNil) h := highlight.New(mconf.Highlight) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } conv, err := p.New(converter.DocumentContext{DocumentID: "thedoc"}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{RenderTOC: true, Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return b } func TestConvert(t *testing.T) { c := qt.New(t) // Smoke test of the default configuration. content := ` ## Links https://github.com/gohugoio/hugo/issues/6528 [Live Demo here!](https://docuapi.netlify.com/) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") <https://foo.bar/> https://bar.baz/ <[email protected]> <mailto:[email protected]> ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Custom ID {#custom} ## Auto ID * Autolink: https://gohugo.io/ * Strikethrough:~~Hi~~ Hello, world! ## Table | foo | bar | | --- | --- | | baz | bim | ## Task Lists (default on) - [x] Finish my changes[^1] - [ ] Push my commits to GitHub - [ ] Open a pull request ## Smartypants (default on) * Straight double "quotes" and single 'quotes' into β€œcurly” quote HTML entities * Dashes (β€œ--” and β€œ---”) into en- and em-dash entities * Three consecutive dots (β€œ...”) into an ellipsis entity * Apostrophes are also converted: "That was back in the '90s, that's a long time ago" ## Footnotes That's some text with a footnote.[^1] ## Definition Lists date : the datetime assigned to this page. description : the description for the content. ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ [^1]: And that's the footnote. ` // Code fences content = strings.Replace(content, "Β§Β§Β§", "```", -1) mconf := markup_config.Default mconf.Highlight.NoClasses = false mconf.Goldmark.Renderer.Unsafe = true b := convert(c, mconf, content) got := string(b.Bytes()) fmt.Println(got) // Links c.Assert(got, qt.Contains, `<a href="https://docuapi.netlify.com/">Live Demo here!</a>`) c.Assert(got, qt.Contains, `<a href="https://foo.bar/">https://foo.bar/</a>`) c.Assert(got, qt.Contains, `<a href="https://bar.baz/">https://bar.baz/</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">[email protected]</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">mailto:[email protected]</a></p>`) // Header IDs c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-1">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-2">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) // Code fences c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>") c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>") // Extensions c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`) c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`) c.Assert(got, qt.Contains, `<th>foo</th>`) c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox"> Push my commits to GitHub</li>`) c.Assert(got, qt.Contains, `Straight double &ldquo;quotes&rdquo; and single &lsquo;quotes&rsquo;`) c.Assert(got, qt.Contains, `Dashes (β€œ&ndash;” and β€œ&mdash;”) `) c.Assert(got, qt.Contains, `Three consecutive dots (β€œ&hellip;”)`) c.Assert(got, qt.Contains, `&ldquo;That was back in the &rsquo;90s, that&rsquo;s a long time ago&rdquo;`) c.Assert(got, qt.Contains, `footnote.<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`) c.Assert(got, qt.Contains, `<section class="footnotes" role="doc-endnotes">`) c.Assert(got, qt.Contains, `<dt>date</dt>`) toc, ok := b.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) tocHTML := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(tocHTML, qt.Contains, "TableOfContents") } func TestConvertAutoIDAsciiOnly(t *testing.T) { c := qt.New(t) content := ` ## God is Good: η₯žηœŸηΎŽε₯½ ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeGitHubAscii b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"god-is-good-\">") } func TestConvertAutoIDBlackfriday(t *testing.T) { c := qt.New(t) content := ` ## Let's try this, shall we? ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeBlackfriday b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"let-s-try-this-shall-we\">") } func TestConvertAttributes(t *testing.T) { c := qt.New(t) withBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = false } withTitleAndBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = true } for _, test := range []struct { name string withConfig func(conf *markup_config.Config) input string expect interface{} }{ { "Title", nil, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n", }, { "Blockquote", withBlockAttributes, "> foo\n> bar\n{#id .className attrName=attrValue class=\"class1 class2\"}\n", "<blockquote id=\"id\" class=\"className class1 class2\"><p>foo\nbar</p>\n</blockquote>\n", }, /*{ // TODO(bep) this needs an upstream fix, see https://github.com/yuin/goldmark/issues/195 "Code block, CodeFences=false", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = false }, "```bash\necho 'foo';\n```\n{.myclass}", "TODO", },*/ { "Code block, CodeFences=true", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {.myclass id=\"myid\"}\necho 'foo';\n````\n", "<div class=\"highlight myclass\" id=\"myid\"><pre style", }, { "Code block, CodeFences=true,linenos=table", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {linenos=table .myclass id=\"myid\"}\necho 'foo';\n````\n{ .adfadf }", []string{ "div class=\"highlight myclass\" id=\"myid\"><div s", "table style", }, }, { "Paragraph", withBlockAttributes, "\nHi there.\n{.myclass }", "<p class=\"myclass\">Hi there.</p>\n", }, { "Ordered list", withBlockAttributes, "\n1. First\n2. Second\n{.myclass }", "<ol class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ol>\n", }, { "Unordered list", withBlockAttributes, "\n* First\n* Second\n{.myclass }", "<ul class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ul>\n", }, { "Unordered list, indented", withBlockAttributes, `* Fruit * Apple * Orange * Banana {.fruits} * Dairy * Milk * Cheese {.dairies} {.list}`, []string{"<ul class=\"list\">\n<li>Fruit\n<ul class=\"fruits\">", "<li>Dairy\n<ul class=\"dairies\">"}, }, { "Table", withBlockAttributes, `| A | B | | ------------- |:-------------:| -----:| | AV | BV | {.myclass }`, "<table class=\"myclass\">\n<thead>", }, { "Title and Blockquote", withTitleAndBlockAttributes, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}\n> foo\n> bar\n{.myclass}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n<blockquote class=\"myclass\"><p>foo\nbar</p>\n</blockquote>\n", }, } { c.Run(test.name, func(c *qt.C) { mconf := markup_config.Default if test.withConfig != nil { test.withConfig(&mconf) } b := convert(c, mconf, test.input) got := string(b.Bytes()) for _, s := range cast.ToStringSlice(test.expect) { c.Assert(got, qt.Contains, s) } }) } } func TestConvertIssues(t *testing.T) { c := qt.New(t) // https://github.com/gohugoio/hugo/issues/7619 c.Run("Hyphen in HTML attributes", func(c *qt.C) { mconf := markup_config.Default mconf.Goldmark.Renderer.Unsafe = true input := `<custom-element> <div>This will be "slotted" into the custom element.</div> </custom-element> ` b := convert(c, mconf, input) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<custom-element>\n <div>This will be \"slotted\" into the custom element.</div>\n</custom-element>\n") }) } func TestCodeFence(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` convertForConfig := func(c *qt.C, conf highlight.Config, code, language string) string { mconf := markup_config.Default mconf.Highlight = conf p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) h := highlight.New(conf) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } content := "```" + language + "\n" + code + "\n```" c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return string(b.Bytes()) } c.Run("Basic", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "bash") // TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func. c.Assert(result, qt.Equals, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;Hugo Rocks!&#34;</span>\n</span></span></code></pre></div>") result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code class=\"language-unknown\" data-lang=\"unknown\">echo &#34;Hugo Rocks!&#34;\n</code></pre>") }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`) c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result = convertForConfig(c, cfg, lines, "bash {linenos=inline,hl_lines=[2]}") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result = convertForConfig(c, cfg, lines, "bash {linenos=true,hl_lines=[2]}") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=false,hl_lines=[2]}") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=table}") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<pre tabindex=\"0\"><code>LINE1\n") }) c.Run("No language, guess syntax", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.GuessSyntax = true cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") }) }
// 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 goldmark import ( "fmt" "strings" "testing" "github.com/spf13/cast" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) func convert(c *qt.C, mconf markup_config.Config, content string) converter.Result { p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) c.Assert(err, qt.IsNil) h := highlight.New(mconf.Highlight) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } conv, err := p.New(converter.DocumentContext{DocumentID: "thedoc"}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{RenderTOC: true, Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return b } func TestConvert(t *testing.T) { c := qt.New(t) // Smoke test of the default configuration. content := ` ## Links https://github.com/gohugoio/hugo/issues/6528 [Live Demo here!](https://docuapi.netlify.com/) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") <https://foo.bar/> https://bar.baz/ <[email protected]> <mailto:[email protected]> ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Custom ID {#custom} ## Auto ID * Autolink: https://gohugo.io/ * Strikethrough:~~Hi~~ Hello, world! ## Table | foo | bar | | --- | --- | | baz | bim | ## Task Lists (default on) - [x] Finish my changes[^1] - [ ] Push my commits to GitHub - [ ] Open a pull request ## Smartypants (default on) * Straight double "quotes" and single 'quotes' into β€œcurly” quote HTML entities * Dashes (β€œ--” and β€œ---”) into en- and em-dash entities * Three consecutive dots (β€œ...”) into an ellipsis entity * Apostrophes are also converted: "That was back in the '90s, that's a long time ago" ## Footnotes That's some text with a footnote.[^1] ## Definition Lists date : the datetime assigned to this page. description : the description for the content. ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ [^1]: And that's the footnote. ` // Code fences content = strings.Replace(content, "Β§Β§Β§", "```", -1) mconf := markup_config.Default mconf.Highlight.NoClasses = false mconf.Goldmark.Renderer.Unsafe = true b := convert(c, mconf, content) got := string(b.Bytes()) fmt.Println(got) // Links c.Assert(got, qt.Contains, `<a href="https://docuapi.netlify.com/">Live Demo here!</a>`) c.Assert(got, qt.Contains, `<a href="https://foo.bar/">https://foo.bar/</a>`) c.Assert(got, qt.Contains, `<a href="https://bar.baz/">https://bar.baz/</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">[email protected]</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">mailto:[email protected]</a></p>`) // Header IDs c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-1">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-2">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) // Code fences c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>") c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>") // Extensions c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`) c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`) c.Assert(got, qt.Contains, `<th>foo</th>`) c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox"> Push my commits to GitHub</li>`) c.Assert(got, qt.Contains, `Straight double &ldquo;quotes&rdquo; and single &lsquo;quotes&rsquo;`) c.Assert(got, qt.Contains, `Dashes (β€œ&ndash;” and β€œ&mdash;”) `) c.Assert(got, qt.Contains, `Three consecutive dots (β€œ&hellip;”)`) c.Assert(got, qt.Contains, `&ldquo;That was back in the &rsquo;90s, that&rsquo;s a long time ago&rdquo;`) c.Assert(got, qt.Contains, `footnote.<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`) c.Assert(got, qt.Contains, `<section class="footnotes" role="doc-endnotes">`) c.Assert(got, qt.Contains, `<dt>date</dt>`) toc, ok := b.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) tocHTML := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(tocHTML, qt.Contains, "TableOfContents") } func TestConvertAutoIDAsciiOnly(t *testing.T) { c := qt.New(t) content := ` ## God is Good: η₯žηœŸηΎŽε₯½ ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeGitHubAscii b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"god-is-good-\">") } func TestConvertAutoIDBlackfriday(t *testing.T) { c := qt.New(t) content := ` ## Let's try this, shall we? ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeBlackfriday b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"let-s-try-this-shall-we\">") } func TestConvertAttributes(t *testing.T) { c := qt.New(t) withBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = false } withTitleAndBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = true } for _, test := range []struct { name string withConfig func(conf *markup_config.Config) input string expect interface{} }{ { "Title", nil, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n", }, { "Blockquote", withBlockAttributes, "> foo\n> bar\n{#id .className attrName=attrValue class=\"class1 class2\"}\n", "<blockquote id=\"id\" class=\"className class1 class2\"><p>foo\nbar</p>\n</blockquote>\n", }, /*{ // TODO(bep) this needs an upstream fix, see https://github.com/yuin/goldmark/issues/195 "Code block, CodeFences=false", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = false }, "```bash\necho 'foo';\n```\n{.myclass}", "TODO", },*/ { "Code block, CodeFences=true", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {.myclass id=\"myid\"}\necho 'foo';\n````\n", "<div class=\"highlight myclass\" id=\"myid\"><pre style", }, { "Code block, CodeFences=true,linenos=table", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {linenos=table .myclass id=\"myid\"}\necho 'foo';\n````\n{ .adfadf }", []string{ "div class=\"highlight myclass\" id=\"myid\"><div s", "table style", }, }, { "Code block, CodeFences=true,lineanchors", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true conf.Highlight.NoClasses = false }, "```bash {linenos=table, anchorlinenos=true, lineanchors=org-coderef--xyz}\necho 'foo';\n```", "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class=\"lnt\" id=\"org-coderef--xyz-1\"><a style=\"outline: none; text-decoration:none; color:inherit\" href=\"#org-coderef--xyz-1\">1</a>\n</span></code></pre></td>\n<td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s1\">&#39;foo&#39;</span><span class=\"p\">;</span>\n</span></span></code></pre></td></tr></table>\n</div>\n</div>", }, { "Paragraph", withBlockAttributes, "\nHi there.\n{.myclass }", "<p class=\"myclass\">Hi there.</p>\n", }, { "Ordered list", withBlockAttributes, "\n1. First\n2. Second\n{.myclass }", "<ol class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ol>\n", }, { "Unordered list", withBlockAttributes, "\n* First\n* Second\n{.myclass }", "<ul class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ul>\n", }, { "Unordered list, indented", withBlockAttributes, `* Fruit * Apple * Orange * Banana {.fruits} * Dairy * Milk * Cheese {.dairies} {.list}`, []string{"<ul class=\"list\">\n<li>Fruit\n<ul class=\"fruits\">", "<li>Dairy\n<ul class=\"dairies\">"}, }, { "Table", withBlockAttributes, `| A | B | | ------------- |:-------------:| -----:| | AV | BV | {.myclass }`, "<table class=\"myclass\">\n<thead>", }, { "Title and Blockquote", withTitleAndBlockAttributes, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}\n> foo\n> bar\n{.myclass}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n<blockquote class=\"myclass\"><p>foo\nbar</p>\n</blockquote>\n", }, } { c.Run(test.name, func(c *qt.C) { mconf := markup_config.Default if test.withConfig != nil { test.withConfig(&mconf) } b := convert(c, mconf, test.input) got := string(b.Bytes()) for _, s := range cast.ToStringSlice(test.expect) { c.Assert(got, qt.Contains, s) } }) } } func TestConvertIssues(t *testing.T) { c := qt.New(t) // https://github.com/gohugoio/hugo/issues/7619 c.Run("Hyphen in HTML attributes", func(c *qt.C) { mconf := markup_config.Default mconf.Goldmark.Renderer.Unsafe = true input := `<custom-element> <div>This will be "slotted" into the custom element.</div> </custom-element> ` b := convert(c, mconf, input) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<custom-element>\n <div>This will be \"slotted\" into the custom element.</div>\n</custom-element>\n") }) } func TestCodeFence(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` convertForConfig := func(c *qt.C, conf highlight.Config, code, language string) string { mconf := markup_config.Default mconf.Highlight = conf p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) h := highlight.New(conf) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } content := "```" + language + "\n" + code + "\n```" c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return string(b.Bytes()) } c.Run("Basic", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "bash") // TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func. c.Assert(result, qt.Equals, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;Hugo Rocks!&#34;</span>\n</span></span></code></pre></div>") result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code class=\"language-unknown\" data-lang=\"unknown\">echo &#34;Hugo Rocks!&#34;\n</code></pre>") }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`) c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result = convertForConfig(c, cfg, lines, "bash {linenos=inline,hl_lines=[2]}") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result = convertForConfig(c, cfg, lines, "bash {linenos=true,hl_lines=[2]}") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=false,hl_lines=[2]}") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=table}") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<pre tabindex=\"0\"><code>LINE1\n") }) c.Run("No language, guess syntax", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.GuessSyntax = true cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") }) }
kaushalmodi
7248f43188c159519e1427a290267f7f69f91ded
6bffcdbd26d90dc4670cdf31f7ee622a297607af
I meant noClasses=false.
bep
120
gohugoio/hugo
9,562
Add test for line anchor attributes with code fences
Fixes https://github.com/gohugoio/hugo/issues/9385.
null
2022-02-24 19:16:42+00:00
2022-02-24 21:54:50+00:00
markup/goldmark/convert_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 goldmark import ( "fmt" "strings" "testing" "github.com/spf13/cast" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) func convert(c *qt.C, mconf markup_config.Config, content string) converter.Result { p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) c.Assert(err, qt.IsNil) h := highlight.New(mconf.Highlight) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } conv, err := p.New(converter.DocumentContext{DocumentID: "thedoc"}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{RenderTOC: true, Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return b } func TestConvert(t *testing.T) { c := qt.New(t) // Smoke test of the default configuration. content := ` ## Links https://github.com/gohugoio/hugo/issues/6528 [Live Demo here!](https://docuapi.netlify.com/) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") <https://foo.bar/> https://bar.baz/ <[email protected]> <mailto:[email protected]> ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Custom ID {#custom} ## Auto ID * Autolink: https://gohugo.io/ * Strikethrough:~~Hi~~ Hello, world! ## Table | foo | bar | | --- | --- | | baz | bim | ## Task Lists (default on) - [x] Finish my changes[^1] - [ ] Push my commits to GitHub - [ ] Open a pull request ## Smartypants (default on) * Straight double "quotes" and single 'quotes' into β€œcurly” quote HTML entities * Dashes (β€œ--” and β€œ---”) into en- and em-dash entities * Three consecutive dots (β€œ...”) into an ellipsis entity * Apostrophes are also converted: "That was back in the '90s, that's a long time ago" ## Footnotes That's some text with a footnote.[^1] ## Definition Lists date : the datetime assigned to this page. description : the description for the content. ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ [^1]: And that's the footnote. ` // Code fences content = strings.Replace(content, "Β§Β§Β§", "```", -1) mconf := markup_config.Default mconf.Highlight.NoClasses = false mconf.Goldmark.Renderer.Unsafe = true b := convert(c, mconf, content) got := string(b.Bytes()) fmt.Println(got) // Links c.Assert(got, qt.Contains, `<a href="https://docuapi.netlify.com/">Live Demo here!</a>`) c.Assert(got, qt.Contains, `<a href="https://foo.bar/">https://foo.bar/</a>`) c.Assert(got, qt.Contains, `<a href="https://bar.baz/">https://bar.baz/</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">[email protected]</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">mailto:[email protected]</a></p>`) // Header IDs c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-1">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-2">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) // Code fences c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>") c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>") // Extensions c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`) c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`) c.Assert(got, qt.Contains, `<th>foo</th>`) c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox"> Push my commits to GitHub</li>`) c.Assert(got, qt.Contains, `Straight double &ldquo;quotes&rdquo; and single &lsquo;quotes&rsquo;`) c.Assert(got, qt.Contains, `Dashes (β€œ&ndash;” and β€œ&mdash;”) `) c.Assert(got, qt.Contains, `Three consecutive dots (β€œ&hellip;”)`) c.Assert(got, qt.Contains, `&ldquo;That was back in the &rsquo;90s, that&rsquo;s a long time ago&rdquo;`) c.Assert(got, qt.Contains, `footnote.<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`) c.Assert(got, qt.Contains, `<section class="footnotes" role="doc-endnotes">`) c.Assert(got, qt.Contains, `<dt>date</dt>`) toc, ok := b.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) tocHTML := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(tocHTML, qt.Contains, "TableOfContents") } func TestConvertAutoIDAsciiOnly(t *testing.T) { c := qt.New(t) content := ` ## God is Good: η₯žηœŸηΎŽε₯½ ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeGitHubAscii b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"god-is-good-\">") } func TestConvertAutoIDBlackfriday(t *testing.T) { c := qt.New(t) content := ` ## Let's try this, shall we? ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeBlackfriday b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"let-s-try-this-shall-we\">") } func TestConvertAttributes(t *testing.T) { c := qt.New(t) withBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = false } withTitleAndBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = true } for _, test := range []struct { name string withConfig func(conf *markup_config.Config) input string expect interface{} }{ { "Title", nil, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n", }, { "Blockquote", withBlockAttributes, "> foo\n> bar\n{#id .className attrName=attrValue class=\"class1 class2\"}\n", "<blockquote id=\"id\" class=\"className class1 class2\"><p>foo\nbar</p>\n</blockquote>\n", }, /*{ // TODO(bep) this needs an upstream fix, see https://github.com/yuin/goldmark/issues/195 "Code block, CodeFences=false", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = false }, "```bash\necho 'foo';\n```\n{.myclass}", "TODO", },*/ { "Code block, CodeFences=true", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {.myclass id=\"myid\"}\necho 'foo';\n````\n", "<div class=\"highlight myclass\" id=\"myid\"><pre style", }, { "Code block, CodeFences=true,linenos=table", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {linenos=table .myclass id=\"myid\"}\necho 'foo';\n````\n{ .adfadf }", []string{ "div class=\"highlight myclass\" id=\"myid\"><div s", "table style", }, }, { "Paragraph", withBlockAttributes, "\nHi there.\n{.myclass }", "<p class=\"myclass\">Hi there.</p>\n", }, { "Ordered list", withBlockAttributes, "\n1. First\n2. Second\n{.myclass }", "<ol class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ol>\n", }, { "Unordered list", withBlockAttributes, "\n* First\n* Second\n{.myclass }", "<ul class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ul>\n", }, { "Unordered list, indented", withBlockAttributes, `* Fruit * Apple * Orange * Banana {.fruits} * Dairy * Milk * Cheese {.dairies} {.list}`, []string{"<ul class=\"list\">\n<li>Fruit\n<ul class=\"fruits\">", "<li>Dairy\n<ul class=\"dairies\">"}, }, { "Table", withBlockAttributes, `| A | B | | ------------- |:-------------:| -----:| | AV | BV | {.myclass }`, "<table class=\"myclass\">\n<thead>", }, { "Title and Blockquote", withTitleAndBlockAttributes, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}\n> foo\n> bar\n{.myclass}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n<blockquote class=\"myclass\"><p>foo\nbar</p>\n</blockquote>\n", }, } { c.Run(test.name, func(c *qt.C) { mconf := markup_config.Default if test.withConfig != nil { test.withConfig(&mconf) } b := convert(c, mconf, test.input) got := string(b.Bytes()) for _, s := range cast.ToStringSlice(test.expect) { c.Assert(got, qt.Contains, s) } }) } } func TestConvertIssues(t *testing.T) { c := qt.New(t) // https://github.com/gohugoio/hugo/issues/7619 c.Run("Hyphen in HTML attributes", func(c *qt.C) { mconf := markup_config.Default mconf.Goldmark.Renderer.Unsafe = true input := `<custom-element> <div>This will be "slotted" into the custom element.</div> </custom-element> ` b := convert(c, mconf, input) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<custom-element>\n <div>This will be \"slotted\" into the custom element.</div>\n</custom-element>\n") }) } func TestCodeFence(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` convertForConfig := func(c *qt.C, conf highlight.Config, code, language string) string { mconf := markup_config.Default mconf.Highlight = conf p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) h := highlight.New(conf) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } content := "```" + language + "\n" + code + "\n```" c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return string(b.Bytes()) } c.Run("Basic", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "bash") // TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func. c.Assert(result, qt.Equals, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;Hugo Rocks!&#34;</span>\n</span></span></code></pre></div>") result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code class=\"language-unknown\" data-lang=\"unknown\">echo &#34;Hugo Rocks!&#34;\n</code></pre>") }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`) c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result = convertForConfig(c, cfg, lines, "bash {linenos=inline,hl_lines=[2]}") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result = convertForConfig(c, cfg, lines, "bash {linenos=true,hl_lines=[2]}") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=false,hl_lines=[2]}") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=table}") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<pre tabindex=\"0\"><code>LINE1\n") }) c.Run("No language, guess syntax", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.GuessSyntax = true cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") }) }
// 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 goldmark import ( "fmt" "strings" "testing" "github.com/spf13/cast" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) func convert(c *qt.C, mconf markup_config.Config, content string) converter.Result { p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) c.Assert(err, qt.IsNil) h := highlight.New(mconf.Highlight) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } conv, err := p.New(converter.DocumentContext{DocumentID: "thedoc"}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{RenderTOC: true, Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return b } func TestConvert(t *testing.T) { c := qt.New(t) // Smoke test of the default configuration. content := ` ## Links https://github.com/gohugoio/hugo/issues/6528 [Live Demo here!](https://docuapi.netlify.com/) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") <https://foo.bar/> https://bar.baz/ <[email protected]> <mailto:[email protected]> ## Code Fences Β§Β§Β§bash LINE1 Β§Β§Β§ ## Code Fences No Lexer Β§Β§Β§moo LINE1 Β§Β§Β§ ## Custom ID {#custom} ## Auto ID * Autolink: https://gohugo.io/ * Strikethrough:~~Hi~~ Hello, world! ## Table | foo | bar | | --- | --- | | baz | bim | ## Task Lists (default on) - [x] Finish my changes[^1] - [ ] Push my commits to GitHub - [ ] Open a pull request ## Smartypants (default on) * Straight double "quotes" and single 'quotes' into β€œcurly” quote HTML entities * Dashes (β€œ--” and β€œ---”) into en- and em-dash entities * Three consecutive dots (β€œ...”) into an ellipsis entity * Apostrophes are also converted: "That was back in the '90s, that's a long time ago" ## Footnotes That's some text with a footnote.[^1] ## Definition Lists date : the datetime assigned to this page. description : the description for the content. ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ ## η₯žηœŸηΎŽε₯½ [^1]: And that's the footnote. ` // Code fences content = strings.Replace(content, "Β§Β§Β§", "```", -1) mconf := markup_config.Default mconf.Highlight.NoClasses = false mconf.Goldmark.Renderer.Unsafe = true b := convert(c, mconf, content) got := string(b.Bytes()) fmt.Println(got) // Links c.Assert(got, qt.Contains, `<a href="https://docuapi.netlify.com/">Live Demo here!</a>`) c.Assert(got, qt.Contains, `<a href="https://foo.bar/">https://foo.bar/</a>`) c.Assert(got, qt.Contains, `<a href="https://bar.baz/">https://bar.baz/</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">[email protected]</a>`) c.Assert(got, qt.Contains, `<a href="mailto:[email protected]">mailto:[email protected]</a></p>`) // Header IDs c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-1">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="η₯žηœŸηΎŽε₯½-2">η₯žηœŸηΎŽε₯½</h2>`, qt.Commentf(got)) // Code fences c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>") c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>") // Extensions c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`) c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`) c.Assert(got, qt.Contains, `<th>foo</th>`) c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox"> Push my commits to GitHub</li>`) c.Assert(got, qt.Contains, `Straight double &ldquo;quotes&rdquo; and single &lsquo;quotes&rsquo;`) c.Assert(got, qt.Contains, `Dashes (β€œ&ndash;” and β€œ&mdash;”) `) c.Assert(got, qt.Contains, `Three consecutive dots (β€œ&hellip;”)`) c.Assert(got, qt.Contains, `&ldquo;That was back in the &rsquo;90s, that&rsquo;s a long time ago&rdquo;`) c.Assert(got, qt.Contains, `footnote.<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`) c.Assert(got, qt.Contains, `<section class="footnotes" role="doc-endnotes">`) c.Assert(got, qt.Contains, `<dt>date</dt>`) toc, ok := b.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) tocHTML := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(tocHTML, qt.Contains, "TableOfContents") } func TestConvertAutoIDAsciiOnly(t *testing.T) { c := qt.New(t) content := ` ## God is Good: η₯žηœŸηΎŽε₯½ ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeGitHubAscii b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"god-is-good-\">") } func TestConvertAutoIDBlackfriday(t *testing.T) { c := qt.New(t) content := ` ## Let's try this, shall we? ` mconf := markup_config.Default mconf.Goldmark.Parser.AutoHeadingIDType = goldmark_config.AutoHeadingIDTypeBlackfriday b := convert(c, mconf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"let-s-try-this-shall-we\">") } func TestConvertAttributes(t *testing.T) { c := qt.New(t) withBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = false } withTitleAndBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = true } for _, test := range []struct { name string withConfig func(conf *markup_config.Config) input string expect interface{} }{ { "Title", nil, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n", }, { "Blockquote", withBlockAttributes, "> foo\n> bar\n{#id .className attrName=attrValue class=\"class1 class2\"}\n", "<blockquote id=\"id\" class=\"className class1 class2\"><p>foo\nbar</p>\n</blockquote>\n", }, /*{ // TODO(bep) this needs an upstream fix, see https://github.com/yuin/goldmark/issues/195 "Code block, CodeFences=false", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = false }, "```bash\necho 'foo';\n```\n{.myclass}", "TODO", },*/ { "Code block, CodeFences=true", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {.myclass id=\"myid\"}\necho 'foo';\n````\n", "<div class=\"highlight myclass\" id=\"myid\"><pre style", }, { "Code block, CodeFences=true,linenos=table", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {linenos=table .myclass id=\"myid\"}\necho 'foo';\n````\n{ .adfadf }", []string{ "div class=\"highlight myclass\" id=\"myid\"><div s", "table style", }, }, { "Code block, CodeFences=true,lineanchors", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true conf.Highlight.NoClasses = false }, "```bash {linenos=table, anchorlinenos=true, lineanchors=org-coderef--xyz}\necho 'foo';\n```", "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class=\"lnt\" id=\"org-coderef--xyz-1\"><a style=\"outline: none; text-decoration:none; color:inherit\" href=\"#org-coderef--xyz-1\">1</a>\n</span></code></pre></td>\n<td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s1\">&#39;foo&#39;</span><span class=\"p\">;</span>\n</span></span></code></pre></td></tr></table>\n</div>\n</div>", }, { "Paragraph", withBlockAttributes, "\nHi there.\n{.myclass }", "<p class=\"myclass\">Hi there.</p>\n", }, { "Ordered list", withBlockAttributes, "\n1. First\n2. Second\n{.myclass }", "<ol class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ol>\n", }, { "Unordered list", withBlockAttributes, "\n* First\n* Second\n{.myclass }", "<ul class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ul>\n", }, { "Unordered list, indented", withBlockAttributes, `* Fruit * Apple * Orange * Banana {.fruits} * Dairy * Milk * Cheese {.dairies} {.list}`, []string{"<ul class=\"list\">\n<li>Fruit\n<ul class=\"fruits\">", "<li>Dairy\n<ul class=\"dairies\">"}, }, { "Table", withBlockAttributes, `| A | B | | ------------- |:-------------:| -----:| | AV | BV | {.myclass }`, "<table class=\"myclass\">\n<thead>", }, { "Title and Blockquote", withTitleAndBlockAttributes, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}\n> foo\n> bar\n{.myclass}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n<blockquote class=\"myclass\"><p>foo\nbar</p>\n</blockquote>\n", }, } { c.Run(test.name, func(c *qt.C) { mconf := markup_config.Default if test.withConfig != nil { test.withConfig(&mconf) } b := convert(c, mconf, test.input) got := string(b.Bytes()) for _, s := range cast.ToStringSlice(test.expect) { c.Assert(got, qt.Contains, s) } }) } } func TestConvertIssues(t *testing.T) { c := qt.New(t) // https://github.com/gohugoio/hugo/issues/7619 c.Run("Hyphen in HTML attributes", func(c *qt.C) { mconf := markup_config.Default mconf.Goldmark.Renderer.Unsafe = true input := `<custom-element> <div>This will be "slotted" into the custom element.</div> </custom-element> ` b := convert(c, mconf, input) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<custom-element>\n <div>This will be \"slotted\" into the custom element.</div>\n</custom-element>\n") }) } func TestCodeFence(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` convertForConfig := func(c *qt.C, conf highlight.Config, code, language string) string { mconf := markup_config.Default mconf.Highlight = conf p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, Logger: loggers.NewErrorLogger(), }, ) h := highlight.New(conf) getRenderer := func(t hooks.RendererType, id interface{}) interface{} { if t == hooks.CodeBlockRendererType { return h } return nil } content := "```" + language + "\n" + code + "\n```" c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return string(b.Bytes()) } c.Run("Basic", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "bash") // TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func. c.Assert(result, qt.Equals, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;Hugo Rocks!&#34;</span>\n</span></span></code></pre></div>") result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code class=\"language-unknown\" data-lang=\"unknown\">echo &#34;Hugo Rocks!&#34;\n</code></pre>") }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false result := convertForConfig(c, cfg, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`) c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result = convertForConfig(c, cfg, lines, "bash {linenos=inline,hl_lines=[2]}") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result = convertForConfig(c, cfg, lines, "bash {linenos=true,hl_lines=[2]}") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=false,hl_lines=[2]}") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span>") result = convertForConfig(c, cfg, lines, "bash {linenos=table}") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<pre tabindex=\"0\"><code>LINE1\n") }) c.Run("No language, guess syntax", func(c *qt.C) { cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.GuessSyntax = true cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, cfg, lines, "") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") }) }
kaushalmodi
7248f43188c159519e1427a290267f7f69f91ded
6bffcdbd26d90dc4670cdf31f7ee622a297607af
Thanks. I have force-pushed a change.
kaushalmodi
121
gohugoio/hugo
9,398
Ensure page translation CPs are initialized
PR #9342 introduced a regression in which calling .Translations in a template and calling RenderString on a translated Page caused a nil pointer dereference. The issue was that some Pages returned from .Translations had a nil cp field at the time the calling template was being executed. While PR #9342 had attempted to ensure that all ContentProviders were initialized for translations at build time, it only performed the initialization for receivers of ContentProvider methods such as .Summary. However, the ContentProvider's *pageState.pageOutput.cp would remain uninitialized, causing the nil pointer dereference. This change edits the .Translations and .AllTranslations methods to ensure that all of a page's translations have an initialized content provider in time for a template to be executed. Since LazyContentProvider is no longer needed with this approach, this change also reverts the following commits: - cdcd15b6c2abbb76fd95fbbf90365c56e82f46aa - 25d645f47ae0a32470d303c9478c9e0b2fff0f0e Fixes #9383
null
2022-01-16 21:11:13+00:00
2022-01-27 10:51:13+00:00
hugolib/page.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 hugolib import ( "bytes" "fmt" "html/template" "os" "path" "path/filepath" "sort" "strings" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/hugofs/files" "github.com/bep/gitmap" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/pkg/errors" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, ContentProvider: page.NopPage, TableOfContentsProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter addDependency(dep identity.Provider) } // wrapErr adds some context to the given error if possible. func wrapErr(err error, ctx interface{}) error { if pc, ok := ctx.(pageContext); ok { return pc.wrapError(err) } return err } type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPageWithTemplateInfo(info tpl.Info, ref string) (page.Page, error) { p, err := pa.GetPage(ref) if p != nil { // Track pages referenced by templates/shortcodes // when in server mode. if im, ok := info.(identity.Manager); ok { im.Add(p) } } return p, err } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPageNew(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // This will be shifted out when we start to render a new output format. *pageOutput // Common for all output formats. *pageCommon } func (p *pageState) Err() error { return nil } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (p *pageState) Eq(other interface{}) bool { pp, err := unwrapPage(other) if err != nil { return false } return p == pp } func (p *pageState) GetIdentity() identity.Identity { return identity.NewPathIdentity(files.ComponentFolderContent, filepath.FromSlash(p.Pathc())) } func (p *pageState) GitInfo() *gitmap.GitInfo { return p.gitInfo } // GetTerms gets the terms defined on this page in the given taxonomy. // The pages returned will be ordered according to the front matter. func (p *pageState) GetTerms(taxonomy string) page.Pages { if p.treeRef == nil { return nil } m := p.s.pageMap taxonomy = strings.ToLower(taxonomy) prefix := cleanSectionTreeKey(taxonomy) self := strings.TrimPrefix(p.treeRef.key, "/") var pas page.Pages m.taxonomies.WalkQuery(pageMapQuery{Prefix: prefix}, func(s string, n *contentNode) bool { key := s + self if tn, found := m.taxonomyEntries.Get(key); found { vi := tn.(*contentNode).viewInfo pas = append(pas, pageWithOrdinal{pageState: n.p, ordinal: vi.ordinal}) } return false }) page.SortByDefault(pas) return pas } func (p *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(p) } func (p *pageState) getPages() page.Pages { b := p.bucket if b == nil { return nil } return b.getPages() } func (p *pageState) getPagesRecursive() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesRecursive() } func (p *pageState) getPagesAndSections() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesAndSections() } func (p *pageState) RegularPagesRecursive() page.Pages { p.regularPagesRecursiveInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindSection: pages = p.getPagesRecursive() default: pages = p.RegularPages() } p.regularPagesRecursive = pages }) return p.regularPagesRecursive } func (p *pageState) PagesRecursive() page.Pages { return nil } func (p *pageState) RegularPages() page.Pages { p.regularPagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome, page.KindTaxonomy: pages = p.getPages() case page.KindTerm: all := p.Pages() for _, p := range all { if p.IsPage() { pages = append(pages, p) } } default: pages = p.s.RegularPages() } p.regularPages = pages }) return p.regularPages } func (p *pageState) Pages() page.Pages { p.pagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome: pages = p.getPagesAndSections() case page.KindTerm: pages = p.bucket.getTaxonomyEntries() case page.KindTaxonomy: pages = p.bucket.getTaxonomies() default: pages = p.s.Pages() } p.pages = pages }) return p.pages } // RawContent returns the un-rendered source content without // any leading front matter. func (p *pageState) RawContent() string { if p.source.parsed == nil { return "" } start := p.source.posMainContent if start == -1 { start = 0 } return string(p.source.parsed.Input()[start:]) } func (p *pageState) sortResources() { sort.SliceStable(p.resources, func(i, j int) bool { ri, rj := p.resources[i], p.resources[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() }) } func (p *pageState) Resources() resource.Resources { p.resourcesInit.Do(func() { p.sortResources() if len(p.m.resourcesMetadata) > 0 { resources.AssignMetadata(p.m.resourcesMetadata, p.resources...) p.sortResources() } }) return p.resources } func (p *pageState) HasShortcode(name string) bool { if p.shortcodeState == nil { return false } return p.shortcodeState.nameSet[name] } func (p *pageState) Site() page.Site { return p.s.Info } func (p *pageState) String() string { if sourceRef := p.sourceRef(); sourceRef != "" { return fmt.Sprintf("Page(%s)", sourceRef) } return fmt.Sprintf("Page(%q)", p.Title()) } // IsTranslated returns whether this content file is translated to // other language(s). func (p *pageState) IsTranslated() bool { p.s.h.init.translations.Do() return len(p.translations) > 0 } // TranslationKey returns the key used to map language translations of this page. // It will use the translationKey set in front matter if set, or the content path and // filename (excluding any language code and extension), e.g. "about/index". // The Page Kind is always prepended. func (p *pageState) TranslationKey() string { p.translationKeyInit.Do(func() { if p.m.translationKey != "" { p.translationKey = p.Kind() + "/" + p.m.translationKey } else if p.IsPage() && !p.File().IsZero() { p.translationKey = path.Join(p.Kind(), filepath.ToSlash(p.File().Dir()), p.File().TranslationBaseName()) } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } }) return p.translationKey } // AllTranslations returns all translations, including the current Page. func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() return p.allTranslations } // Translations returns the translations excluding the current Page. func (p *pageState) Translations() page.Pages { p.s.h.init.translations.Do() return p.translations } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s.Info return nil } func (p *pageState) createRenderHooks(f output.Format) (hooks.Renderers, error) { layoutDescriptor := p.getLayoutDescriptor() layoutDescriptor.RenderingHook = true layoutDescriptor.LayoutOverride = false layoutDescriptor.Layout = "" var renderers hooks.Renderers layoutDescriptor.Kind = "render-link" templ, templFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.LinkRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-image" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.ImageRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-heading" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.HeadingRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } return renderers, nil } func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { p.layoutDescriptorInit.Do(func() { var section string sections := p.SectionsEntries() switch p.Kind() { case page.KindSection: if len(sections) > 0 { section = sections[0] } case page.KindTaxonomy, page.KindTerm: b := p.getTreeRef().n section = b.viewInfo.name.singular default: } p.layoutDescriptor = output.LayoutDescriptor{ Kind: p.Kind(), Type: p.Type(), Lang: p.Language().Lang, Layout: p.Layout(), Section: section, } }) return p.layoutDescriptor } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { f := p.outputFormat() if len(layouts) == 0 { selfLayout := p.selfLayoutForOutput(f) if selfLayout != "" { templ, found := p.s.Tmpl().Lookup(selfLayout) return templ, found, nil } } d := p.getLayoutDescriptor() if len(layouts) > 0 { d.Layout = layouts[0] d.LayoutOverride = true } return p.s.Tmpl().LookupLayout(d, f) } // This is serialized func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { if err := p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } // Must be run after the site section tree etc. is built and ready. func (p *pageState) initPage() error { if _, err := p.init.Do(); err != nil { return err } return nil } func (p *pageState) renderResources() (err error) { p.resourcesPublishInit.Do(func() { var toBeDeleted []int for i, r := range p.Resources() { if _, ok := r.(page.Page); ok { // Pages gets rendered with the owning page but we count them here. p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Pages) continue } src, ok := r.(resource.Source) if !ok { err = errors.Errorf("Resource %T does not support resource.Source", src) return } if err := src.Publish(); err != nil { if os.IsNotExist(err) { // The resource has been deleted from the file system. // This should be extremely rare, but can happen on live reload in server // mode when the same resource is member of different page bundles. toBeDeleted = append(toBeDeleted, i) } else { p.s.Log.Errorf("Failed to publish Resource for page %q: %s", p.pathOrTitle(), err) } } else { p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Files) } } for _, i := range toBeDeleted { p.deleteResource(i) } }) return } func (p *pageState) deleteResource(i int) { p.resources = append(p.resources[:i], p.resources[i+1:]...) } func (p *pageState) getTargetPaths() page.TargetPaths { return p.targetPaths() } func (p *pageState) setTranslations(pages page.Pages) { p.allTranslations = pages page.SortByLanguage(p.allTranslations) translations := make(page.Pages, 0) for _, t := range p.allTranslations { if !t.Eq(p) { translations = append(translations, t) } } p.translations = translations } func (p *pageState) AlternativeOutputFormats() page.OutputFormats { f := p.outputFormat() var o page.OutputFormats for _, of := range p.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defaultRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (p *pageState) RenderString(args ...interface{}) (template.HTML, error) { if len(args) < 1 || len(args) > 2 { return "", errors.New("want 1 or 2 arguments") } var s string opts := defaultRenderStringOpts sidx := 1 if len(args) == 1 { sidx = 0 } else { m, ok := args[0].(map[string]interface{}) if !ok { return "", errors.New("first argument must be a map") } if err := mapstructure.WeakDecode(m, &opts); err != nil { return "", errors.WithMessage(err, "failed to decode options") } } var err error s, err = cast.ToStringE(args[sidx]) if err != nil { return "", err } if err = p.pageOutput.initRenderHooks(); err != nil { return "", err } conv := p.getContentConverter() if opts.Markup != "" && opts.Markup != p.m.markup { var err error // TODO(bep) consider cache conv, err = p.m.newContentConverter(p, opts.Markup, nil) if err != nil { return "", p.wrapError(err) } } var cp *pageContentOutput // If the current content provider is not yet initialized, do so now. if lcp, ok := p.pageOutput.ContentProvider.(*page.LazyContentProvider); ok { c := lcp.Init() if pco, ok := c.(*pageContentOutput); ok { cp = pco } } else { cp = p.pageOutput.cp } c, err := cp.renderContentWithConverter(conv, []byte(s), false) if err != nil { return "", p.wrapError(err) } b := c.Bytes() if opts.Display == "inline" { // We may have to rethink this in the future when we get other // renderers. b = p.s.ContentSpec.TrimShortHTML(b) } return template.HTML(string(b)), nil } func (p *pageState) addDependency(dep identity.Provider) { if !p.s.running() || p.pageOutput.cp == nil { return } p.pageOutput.cp.dependencyTracker.Add(dep) } func (p *pageState) RenderWithTemplateInfo(info tpl.Info, layout ...string) (template.HTML, error) { p.addDependency(info) return p.Render(layout...) } func (p *pageState) Render(layout ...string) (template.HTML, error) { templ, found, err := p.resolveTemplate(layout...) if err != nil { return "", p.wrapError(err) } if !found { return "", nil } p.addDependency(templ.(tpl.Info)) res, err := executeToString(p.s.Tmpl(), templ, p) if err != nil { return "", p.wrapError(errors.Wrapf(err, "failed to execute template %q v", layout)) } return template.HTML(res), nil } // wrapError adds some more context to the given error if possible/needed func (p *pageState) wrapError(err error) error { if _, ok := err.(*herrors.ErrorWithFileContext); ok { // Preserve the first file context. return err } var filename string if !p.File().IsZero() { filename = p.File().Filename() } err, _ = herrors.WithFileContextForFile( err, filename, filename, p.s.SourceSpec.Fs.Source, herrors.SimpleLineMatcher) return err } func (p *pageState) getContentConverter() converter.Converter { var err error p.m.contentConverterInit.Do(func() { markup := p.m.markup if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) }) if err != nil { p.s.Log.Errorln("Failed to create content converter:", err) } return p.m.contentConverter } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { s := p.shortcodeState rn := &pageContentMap{ items: make([]interface{}, 0, 20), } iter := p.source.parsed.Iterator() fail := func(err error, i pageparser.Item) error { return p.parseError(err, iter.Input(), i.Pos) } // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var currShortcode shortcode var ordinal int var frontMatterSet bool Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): f := pageparser.FormatFromFrontMatterType(it.Type) m, err := metadecoders.Default.UnmarshalToMap(it.Val, f) if err != nil { if fe, ok := err.(herrors.FileError); ok { return herrors.ToFileErrorWithOffset(fe, iter.LineNumber()-1) } else { return err } } if err := meta.setMetadata(bucket, p, m); err != nil { return err } frontMatterSet = true next := iter.Peek() if !next.IsDone() { p.source.posMainContent = next.Pos } if !p.s.shouldBuild(p) { // Nothing more to do. return nil } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos } if item.IsNonWhitespace() { p.truncated = true // Done return false } return true } iter.PeekWalk(f) p.source.posSummaryEnd = it.Pos p.source.posBodyStart = posBody p.source.hasSummaryDivider = true if meta.markup != "html" { // The content will be rendered by Blackfriday or similar, // and we need to track the summary. rn.AddReplacement(internalSummaryDividerPre, it) } // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, iter) if err != nil { return fail(errors.Wrap(err, "failed to extract shortcode"), it) } currShortcode.pos = it.Pos currShortcode.length = iter.Current().Pos - it.Pos if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", currShortcode.ordinal) } if currShortcode.name != "" { s.nameSet[currShortcode.name] = true } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", ordinal) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) rn.AddShortcode(currShortcode) case it.Type == pageparser.TypeEmoji: if emoji := helpers.Emoji(it.ValStr()); emoji != nil { rn.AddReplacement(emoji, it) } else { rn.AddBytes(it) } case it.IsEOF(): break Loop case it.IsError(): err := fail(errors.WithStack(errors.New(it.ValStr())), it) currShortcode.err = err return err default: rn.AddBytes(it) } } if !frontMatterSet { // Page content without front matter. Assign default front matter from // cascades etc. if err := meta.setMetadata(bucket, p, nil); err != nil { return err } } p.cmap = rn return nil } func (p *pageState) errorf(err error, format string, a ...interface{}) error { if herrors.UnwrapErrorWithFileContext(err) != nil { // More isn't always better. return err } args := append([]interface{}{p.Language().Lang, p.pathOrTitle()}, a...) format = "[%s] page %q: " + format if err == nil { errors.Errorf(format, args...) return fmt.Errorf(format, args...) } return errors.Wrapf(err, format, args...) } func (p *pageState) outputFormat() (f output.Format) { if p.pageOutput == nil { panic("no pageOutput") } return p.pageOutput.f } func (p *pageState) parseError(err error, input []byte, offset int) error { if herrors.UnwrapFileError(err) != nil { // Use the most specific location. return err } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) } func (p *pageState) pathOrTitle() string { if !p.File().IsZero() { return p.File().Filename() } if p.Pathc() != "" { return p.Pathc() } return p.Title() } func (p *pageState) posFromPage(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } func (p *pageState) posFromInput(input []byte, offset int) text.Position { lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: p.pathOrTitle(), LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } func (p *pageState) posOffset(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := p.initPage(); err != nil { return err } if len(p.pageOutputs) == 1 { idx = 0 } p.pageOutput = p.pageOutputs[idx] if p.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && p.pageOutput.paginator != nil && p.pageOutput.paginator.current != nil { p.pageOutput.paginator.reset() } if isRenderingSite { cp := p.pageOutput.cp if cp == nil { // Look for content to reuse. for i := 0; i < len(p.pageOutputs); i++ { if i == idx { continue } po := p.pageOutputs[i] if po.cp != nil && po.cp.reuse { cp = po.cp break } } } if cp == nil { var err error cp, err = newPageContentOutput(p, p.pageOutput) if err != nil { return err } } p.pageOutput.initContentProvider(cp) } else { // We attempt to assign pageContentOutputs while preparing each site // for rendering and before rendering each site. This lets us share // content between page outputs to conserve resources. But if a template // unexpectedly calls a method of a ContentProvider that is not yet // initialized, we assign a LazyContentProvider that performs the // initialization just in time. if lcp, ok := (p.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok { lcp.Reset() } else { p.pageOutput.ContentProvider = page.NewLazyContentProvider(func() (page.ContentProvider, error) { cp, err := newPageContentOutput(p, p.pageOutput) if err != nil { return nil, err } return cp, nil }) } } return nil } // sourceRef returns the reference used by GetPage and ref/relref shortcodes to refer to // this page. It is prefixed with a "/". // // For pages that have a source file, it is returns the path to this file as an // absolute path rooted in this site's content dir. // For pages that do not (sections without content page etc.), it returns the // virtual path, consistent with where you would add a source file. func (p *pageState) sourceRef() string { if !p.File().IsZero() { sourcePath := p.File().Path() if sourcePath != "" { return "/" + filepath.ToSlash(sourcePath) } } if len(p.SectionsEntries()) > 0 { // no backing file, return the virtual source path return "/" + p.SectionsPath() } return "" } func (s *Site) sectionsFromFile(fi source.File) []string { dirname := fi.Dir() dirname = strings.Trim(dirname, helpers.FilePathSeparator) if dirname == "" { return nil } parts := strings.Split(dirname, helpers.FilePathSeparator) if fii, ok := fi.(*fileInfo); ok { if len(parts) > 0 && fii.FileInfo().Meta().Classifier == files.ContentClassLeaf { // my-section/mybundle/index.md => my-section return parts[:len(parts)-1] } } return parts } var ( _ page.Page = (*pageWithOrdinal)(nil) _ collections.Order = (*pageWithOrdinal)(nil) _ pageWrapper = (*pageWithOrdinal)(nil) ) type pageWithOrdinal struct { ordinal int *pageState } func (p pageWithOrdinal) Ordinal() int { return p.ordinal } func (p pageWithOrdinal) page() page.Page { return p.pageState }
// 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 hugolib import ( "bytes" "fmt" "os" "path" "path/filepath" "sort" "strings" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/hugofs/files" "github.com/bep/gitmap" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/pkg/errors" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, ContentProvider: page.NopPage, TableOfContentsProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter addDependency(dep identity.Provider) } // wrapErr adds some context to the given error if possible. func wrapErr(err error, ctx interface{}) error { if pc, ok := ctx.(pageContext); ok { return pc.wrapError(err) } return err } type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPageWithTemplateInfo(info tpl.Info, ref string) (page.Page, error) { p, err := pa.GetPage(ref) if p != nil { // Track pages referenced by templates/shortcodes // when in server mode. if im, ok := info.(identity.Manager); ok { im.Add(p) } } return p, err } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPageNew(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // This will be shifted out when we start to render a new output format. *pageOutput // Common for all output formats. *pageCommon } func (p *pageState) Err() error { return nil } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (p *pageState) Eq(other interface{}) bool { pp, err := unwrapPage(other) if err != nil { return false } return p == pp } func (p *pageState) GetIdentity() identity.Identity { return identity.NewPathIdentity(files.ComponentFolderContent, filepath.FromSlash(p.Pathc())) } func (p *pageState) GitInfo() *gitmap.GitInfo { return p.gitInfo } // GetTerms gets the terms defined on this page in the given taxonomy. // The pages returned will be ordered according to the front matter. func (p *pageState) GetTerms(taxonomy string) page.Pages { if p.treeRef == nil { return nil } m := p.s.pageMap taxonomy = strings.ToLower(taxonomy) prefix := cleanSectionTreeKey(taxonomy) self := strings.TrimPrefix(p.treeRef.key, "/") var pas page.Pages m.taxonomies.WalkQuery(pageMapQuery{Prefix: prefix}, func(s string, n *contentNode) bool { key := s + self if tn, found := m.taxonomyEntries.Get(key); found { vi := tn.(*contentNode).viewInfo pas = append(pas, pageWithOrdinal{pageState: n.p, ordinal: vi.ordinal}) } return false }) page.SortByDefault(pas) return pas } func (p *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(p) } func (p *pageState) getPages() page.Pages { b := p.bucket if b == nil { return nil } return b.getPages() } func (p *pageState) getPagesRecursive() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesRecursive() } func (p *pageState) getPagesAndSections() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesAndSections() } func (p *pageState) RegularPagesRecursive() page.Pages { p.regularPagesRecursiveInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindSection: pages = p.getPagesRecursive() default: pages = p.RegularPages() } p.regularPagesRecursive = pages }) return p.regularPagesRecursive } func (p *pageState) PagesRecursive() page.Pages { return nil } func (p *pageState) RegularPages() page.Pages { p.regularPagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome, page.KindTaxonomy: pages = p.getPages() case page.KindTerm: all := p.Pages() for _, p := range all { if p.IsPage() { pages = append(pages, p) } } default: pages = p.s.RegularPages() } p.regularPages = pages }) return p.regularPages } func (p *pageState) Pages() page.Pages { p.pagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome: pages = p.getPagesAndSections() case page.KindTerm: pages = p.bucket.getTaxonomyEntries() case page.KindTaxonomy: pages = p.bucket.getTaxonomies() default: pages = p.s.Pages() } p.pages = pages }) return p.pages } // RawContent returns the un-rendered source content without // any leading front matter. func (p *pageState) RawContent() string { if p.source.parsed == nil { return "" } start := p.source.posMainContent if start == -1 { start = 0 } return string(p.source.parsed.Input()[start:]) } func (p *pageState) sortResources() { sort.SliceStable(p.resources, func(i, j int) bool { ri, rj := p.resources[i], p.resources[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() }) } func (p *pageState) Resources() resource.Resources { p.resourcesInit.Do(func() { p.sortResources() if len(p.m.resourcesMetadata) > 0 { resources.AssignMetadata(p.m.resourcesMetadata, p.resources...) p.sortResources() } }) return p.resources } func (p *pageState) HasShortcode(name string) bool { if p.shortcodeState == nil { return false } return p.shortcodeState.nameSet[name] } func (p *pageState) Site() page.Site { return p.s.Info } func (p *pageState) String() string { if sourceRef := p.sourceRef(); sourceRef != "" { return fmt.Sprintf("Page(%s)", sourceRef) } return fmt.Sprintf("Page(%q)", p.Title()) } // IsTranslated returns whether this content file is translated to // other language(s). func (p *pageState) IsTranslated() bool { p.s.h.init.translations.Do() return len(p.translations) > 0 } // TranslationKey returns the key used to map language translations of this page. // It will use the translationKey set in front matter if set, or the content path and // filename (excluding any language code and extension), e.g. "about/index". // The Page Kind is always prepended. func (p *pageState) TranslationKey() string { p.translationKeyInit.Do(func() { if p.m.translationKey != "" { p.translationKey = p.Kind() + "/" + p.m.translationKey } else if p.IsPage() && !p.File().IsZero() { p.translationKey = path.Join(p.Kind(), filepath.ToSlash(p.File().Dir()), p.File().TranslationBaseName()) } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } }) return p.translationKey } // AllTranslations returns all translations, including the current Page. func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() return p.allTranslations } // Translations returns the translations excluding the current Page. func (p *pageState) Translations() page.Pages { p.s.h.init.translations.Do() return p.translations } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s.Info return nil } func (p *pageState) createRenderHooks(f output.Format) (hooks.Renderers, error) { layoutDescriptor := p.getLayoutDescriptor() layoutDescriptor.RenderingHook = true layoutDescriptor.LayoutOverride = false layoutDescriptor.Layout = "" var renderers hooks.Renderers layoutDescriptor.Kind = "render-link" templ, templFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.LinkRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-image" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.ImageRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-heading" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.HeadingRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } return renderers, nil } func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { p.layoutDescriptorInit.Do(func() { var section string sections := p.SectionsEntries() switch p.Kind() { case page.KindSection: if len(sections) > 0 { section = sections[0] } case page.KindTaxonomy, page.KindTerm: b := p.getTreeRef().n section = b.viewInfo.name.singular default: } p.layoutDescriptor = output.LayoutDescriptor{ Kind: p.Kind(), Type: p.Type(), Lang: p.Language().Lang, Layout: p.Layout(), Section: section, } }) return p.layoutDescriptor } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { f := p.outputFormat() if len(layouts) == 0 { selfLayout := p.selfLayoutForOutput(f) if selfLayout != "" { templ, found := p.s.Tmpl().Lookup(selfLayout) return templ, found, nil } } d := p.getLayoutDescriptor() if len(layouts) > 0 { d.Layout = layouts[0] d.LayoutOverride = true } return p.s.Tmpl().LookupLayout(d, f) } // This is serialized func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { if err := p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } // Must be run after the site section tree etc. is built and ready. func (p *pageState) initPage() error { if _, err := p.init.Do(); err != nil { return err } return nil } func (p *pageState) renderResources() (err error) { p.resourcesPublishInit.Do(func() { var toBeDeleted []int for i, r := range p.Resources() { if _, ok := r.(page.Page); ok { // Pages gets rendered with the owning page but we count them here. p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Pages) continue } src, ok := r.(resource.Source) if !ok { err = errors.Errorf("Resource %T does not support resource.Source", src) return } if err := src.Publish(); err != nil { if os.IsNotExist(err) { // The resource has been deleted from the file system. // This should be extremely rare, but can happen on live reload in server // mode when the same resource is member of different page bundles. toBeDeleted = append(toBeDeleted, i) } else { p.s.Log.Errorf("Failed to publish Resource for page %q: %s", p.pathOrTitle(), err) } } else { p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Files) } } for _, i := range toBeDeleted { p.deleteResource(i) } }) return } func (p *pageState) deleteResource(i int) { p.resources = append(p.resources[:i], p.resources[i+1:]...) } func (p *pageState) getTargetPaths() page.TargetPaths { return p.targetPaths() } func (p *pageState) setTranslations(pages page.Pages) { p.allTranslations = pages page.SortByLanguage(p.allTranslations) translations := make(page.Pages, 0) for _, t := range p.allTranslations { if !t.Eq(p) { translations = append(translations, t) } } p.translations = translations } func (p *pageState) AlternativeOutputFormats() page.OutputFormats { f := p.outputFormat() var o page.OutputFormats for _, of := range p.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defaultRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (p *pageState) addDependency(dep identity.Provider) { if !p.s.running() || p.pageOutput.cp == nil { return } p.pageOutput.cp.dependencyTracker.Add(dep) } // wrapError adds some more context to the given error if possible/needed func (p *pageState) wrapError(err error) error { if _, ok := err.(*herrors.ErrorWithFileContext); ok { // Preserve the first file context. return err } var filename string if !p.File().IsZero() { filename = p.File().Filename() } err, _ = herrors.WithFileContextForFile( err, filename, filename, p.s.SourceSpec.Fs.Source, herrors.SimpleLineMatcher) return err } func (p *pageState) getContentConverter() converter.Converter { var err error p.m.contentConverterInit.Do(func() { markup := p.m.markup if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) }) if err != nil { p.s.Log.Errorln("Failed to create content converter:", err) } return p.m.contentConverter } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { s := p.shortcodeState rn := &pageContentMap{ items: make([]interface{}, 0, 20), } iter := p.source.parsed.Iterator() fail := func(err error, i pageparser.Item) error { return p.parseError(err, iter.Input(), i.Pos) } // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var currShortcode shortcode var ordinal int var frontMatterSet bool Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): f := pageparser.FormatFromFrontMatterType(it.Type) m, err := metadecoders.Default.UnmarshalToMap(it.Val, f) if err != nil { if fe, ok := err.(herrors.FileError); ok { return herrors.ToFileErrorWithOffset(fe, iter.LineNumber()-1) } else { return err } } if err := meta.setMetadata(bucket, p, m); err != nil { return err } frontMatterSet = true next := iter.Peek() if !next.IsDone() { p.source.posMainContent = next.Pos } if !p.s.shouldBuild(p) { // Nothing more to do. return nil } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos } if item.IsNonWhitespace() { p.truncated = true // Done return false } return true } iter.PeekWalk(f) p.source.posSummaryEnd = it.Pos p.source.posBodyStart = posBody p.source.hasSummaryDivider = true if meta.markup != "html" { // The content will be rendered by Blackfriday or similar, // and we need to track the summary. rn.AddReplacement(internalSummaryDividerPre, it) } // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, iter) if err != nil { return fail(errors.Wrap(err, "failed to extract shortcode"), it) } currShortcode.pos = it.Pos currShortcode.length = iter.Current().Pos - it.Pos if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", currShortcode.ordinal) } if currShortcode.name != "" { s.nameSet[currShortcode.name] = true } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", ordinal) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) rn.AddShortcode(currShortcode) case it.Type == pageparser.TypeEmoji: if emoji := helpers.Emoji(it.ValStr()); emoji != nil { rn.AddReplacement(emoji, it) } else { rn.AddBytes(it) } case it.IsEOF(): break Loop case it.IsError(): err := fail(errors.WithStack(errors.New(it.ValStr())), it) currShortcode.err = err return err default: rn.AddBytes(it) } } if !frontMatterSet { // Page content without front matter. Assign default front matter from // cascades etc. if err := meta.setMetadata(bucket, p, nil); err != nil { return err } } p.cmap = rn return nil } func (p *pageState) errorf(err error, format string, a ...interface{}) error { if herrors.UnwrapErrorWithFileContext(err) != nil { // More isn't always better. return err } args := append([]interface{}{p.Language().Lang, p.pathOrTitle()}, a...) format = "[%s] page %q: " + format if err == nil { errors.Errorf(format, args...) return fmt.Errorf(format, args...) } return errors.Wrapf(err, format, args...) } func (p *pageState) outputFormat() (f output.Format) { if p.pageOutput == nil { panic("no pageOutput") } return p.pageOutput.f } func (p *pageState) parseError(err error, input []byte, offset int) error { if herrors.UnwrapFileError(err) != nil { // Use the most specific location. return err } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) } func (p *pageState) pathOrTitle() string { if !p.File().IsZero() { return p.File().Filename() } if p.Pathc() != "" { return p.Pathc() } return p.Title() } func (p *pageState) posFromPage(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } func (p *pageState) posFromInput(input []byte, offset int) text.Position { lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: p.pathOrTitle(), LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } func (p *pageState) posOffset(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := p.initPage(); err != nil { return err } if len(p.pageOutputs) == 1 { idx = 0 } p.pageOutput = p.pageOutputs[idx] if p.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && p.pageOutput.paginator != nil && p.pageOutput.paginator.current != nil { p.pageOutput.paginator.reset() } if isRenderingSite { cp := p.pageOutput.cp if cp == nil { // Look for content to reuse. for i := 0; i < len(p.pageOutputs); i++ { if i == idx { continue } po := p.pageOutputs[i] if po.cp != nil && po.cp.reuse { cp = po.cp break } } } if cp == nil { var err error cp, err = newPageContentOutput(p, p.pageOutput) if err != nil { return err } } p.pageOutput.initContentProvider(cp) } else { // We attempt to assign pageContentOutputs while preparing each site // for rendering and before rendering each site. This lets us share // content between page outputs to conserve resources. But if a template // unexpectedly calls a method of a ContentProvider that is not yet // initialized, we assign a LazyContentProvider that performs the // initialization just in time. if lcp, ok := (p.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok { lcp.Reset() } else { lcp = page.NewLazyContentProvider(func() (page.OutputFormatContentProvider, error) { cp, err := newPageContentOutput(p, p.pageOutput) if err != nil { return nil, err } return cp, nil }) p.pageOutput.ContentProvider = lcp p.pageOutput.TableOfContentsProvider = lcp p.pageOutput.PageRenderProvider = lcp } } return nil } // sourceRef returns the reference used by GetPage and ref/relref shortcodes to refer to // this page. It is prefixed with a "/". // // For pages that have a source file, it is returns the path to this file as an // absolute path rooted in this site's content dir. // For pages that do not (sections without content page etc.), it returns the // virtual path, consistent with where you would add a source file. func (p *pageState) sourceRef() string { if !p.File().IsZero() { sourcePath := p.File().Path() if sourcePath != "" { return "/" + filepath.ToSlash(sourcePath) } } if len(p.SectionsEntries()) > 0 { // no backing file, return the virtual source path return "/" + p.SectionsPath() } return "" } func (s *Site) sectionsFromFile(fi source.File) []string { dirname := fi.Dir() dirname = strings.Trim(dirname, helpers.FilePathSeparator) if dirname == "" { return nil } parts := strings.Split(dirname, helpers.FilePathSeparator) if fii, ok := fi.(*fileInfo); ok { if len(parts) > 0 && fii.FileInfo().Meta().Classifier == files.ContentClassLeaf { // my-section/mybundle/index.md => my-section return parts[:len(parts)-1] } } return parts } var ( _ page.Page = (*pageWithOrdinal)(nil) _ collections.Order = (*pageWithOrdinal)(nil) _ pageWrapper = (*pageWithOrdinal)(nil) ) type pageWithOrdinal struct { ordinal int *pageState } func (p pageWithOrdinal) Ordinal() int { return p.ordinal } func (p pageWithOrdinal) page() page.Page { return p.pageState }
ptgott
85d31f7bfb7a13c9ab7655829a315a820dc1b403
f22c4aba047e89130bf9921c5ded3823743a9ffa
Thanks for this. But I don't think we can solve this like this. Most notably is the data race which, if it's not already failing the build, it will if you move the `.Translations` into the single template. I suspect that the cleanest, working solution we will find without doing too much work is to expand on the patch we added a few days ago: Make sure that the lazy content provider is triggered on all access to `cp` (including `RenderString`).
bep
122
gohugoio/hugo
9,398
Ensure page translation CPs are initialized
PR #9342 introduced a regression in which calling .Translations in a template and calling RenderString on a translated Page caused a nil pointer dereference. The issue was that some Pages returned from .Translations had a nil cp field at the time the calling template was being executed. While PR #9342 had attempted to ensure that all ContentProviders were initialized for translations at build time, it only performed the initialization for receivers of ContentProvider methods such as .Summary. However, the ContentProvider's *pageState.pageOutput.cp would remain uninitialized, causing the nil pointer dereference. This change edits the .Translations and .AllTranslations methods to ensure that all of a page's translations have an initialized content provider in time for a template to be executed. Since LazyContentProvider is no longer needed with this approach, this change also reverts the following commits: - cdcd15b6c2abbb76fd95fbbf90365c56e82f46aa - 25d645f47ae0a32470d303c9478c9e0b2fff0f0e Fixes #9383
null
2022-01-16 21:11:13+00:00
2022-01-27 10:51:13+00:00
hugolib/page.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 hugolib import ( "bytes" "fmt" "html/template" "os" "path" "path/filepath" "sort" "strings" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/hugofs/files" "github.com/bep/gitmap" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/pkg/errors" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, ContentProvider: page.NopPage, TableOfContentsProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter addDependency(dep identity.Provider) } // wrapErr adds some context to the given error if possible. func wrapErr(err error, ctx interface{}) error { if pc, ok := ctx.(pageContext); ok { return pc.wrapError(err) } return err } type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPageWithTemplateInfo(info tpl.Info, ref string) (page.Page, error) { p, err := pa.GetPage(ref) if p != nil { // Track pages referenced by templates/shortcodes // when in server mode. if im, ok := info.(identity.Manager); ok { im.Add(p) } } return p, err } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPageNew(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // This will be shifted out when we start to render a new output format. *pageOutput // Common for all output formats. *pageCommon } func (p *pageState) Err() error { return nil } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (p *pageState) Eq(other interface{}) bool { pp, err := unwrapPage(other) if err != nil { return false } return p == pp } func (p *pageState) GetIdentity() identity.Identity { return identity.NewPathIdentity(files.ComponentFolderContent, filepath.FromSlash(p.Pathc())) } func (p *pageState) GitInfo() *gitmap.GitInfo { return p.gitInfo } // GetTerms gets the terms defined on this page in the given taxonomy. // The pages returned will be ordered according to the front matter. func (p *pageState) GetTerms(taxonomy string) page.Pages { if p.treeRef == nil { return nil } m := p.s.pageMap taxonomy = strings.ToLower(taxonomy) prefix := cleanSectionTreeKey(taxonomy) self := strings.TrimPrefix(p.treeRef.key, "/") var pas page.Pages m.taxonomies.WalkQuery(pageMapQuery{Prefix: prefix}, func(s string, n *contentNode) bool { key := s + self if tn, found := m.taxonomyEntries.Get(key); found { vi := tn.(*contentNode).viewInfo pas = append(pas, pageWithOrdinal{pageState: n.p, ordinal: vi.ordinal}) } return false }) page.SortByDefault(pas) return pas } func (p *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(p) } func (p *pageState) getPages() page.Pages { b := p.bucket if b == nil { return nil } return b.getPages() } func (p *pageState) getPagesRecursive() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesRecursive() } func (p *pageState) getPagesAndSections() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesAndSections() } func (p *pageState) RegularPagesRecursive() page.Pages { p.regularPagesRecursiveInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindSection: pages = p.getPagesRecursive() default: pages = p.RegularPages() } p.regularPagesRecursive = pages }) return p.regularPagesRecursive } func (p *pageState) PagesRecursive() page.Pages { return nil } func (p *pageState) RegularPages() page.Pages { p.regularPagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome, page.KindTaxonomy: pages = p.getPages() case page.KindTerm: all := p.Pages() for _, p := range all { if p.IsPage() { pages = append(pages, p) } } default: pages = p.s.RegularPages() } p.regularPages = pages }) return p.regularPages } func (p *pageState) Pages() page.Pages { p.pagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome: pages = p.getPagesAndSections() case page.KindTerm: pages = p.bucket.getTaxonomyEntries() case page.KindTaxonomy: pages = p.bucket.getTaxonomies() default: pages = p.s.Pages() } p.pages = pages }) return p.pages } // RawContent returns the un-rendered source content without // any leading front matter. func (p *pageState) RawContent() string { if p.source.parsed == nil { return "" } start := p.source.posMainContent if start == -1 { start = 0 } return string(p.source.parsed.Input()[start:]) } func (p *pageState) sortResources() { sort.SliceStable(p.resources, func(i, j int) bool { ri, rj := p.resources[i], p.resources[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() }) } func (p *pageState) Resources() resource.Resources { p.resourcesInit.Do(func() { p.sortResources() if len(p.m.resourcesMetadata) > 0 { resources.AssignMetadata(p.m.resourcesMetadata, p.resources...) p.sortResources() } }) return p.resources } func (p *pageState) HasShortcode(name string) bool { if p.shortcodeState == nil { return false } return p.shortcodeState.nameSet[name] } func (p *pageState) Site() page.Site { return p.s.Info } func (p *pageState) String() string { if sourceRef := p.sourceRef(); sourceRef != "" { return fmt.Sprintf("Page(%s)", sourceRef) } return fmt.Sprintf("Page(%q)", p.Title()) } // IsTranslated returns whether this content file is translated to // other language(s). func (p *pageState) IsTranslated() bool { p.s.h.init.translations.Do() return len(p.translations) > 0 } // TranslationKey returns the key used to map language translations of this page. // It will use the translationKey set in front matter if set, or the content path and // filename (excluding any language code and extension), e.g. "about/index". // The Page Kind is always prepended. func (p *pageState) TranslationKey() string { p.translationKeyInit.Do(func() { if p.m.translationKey != "" { p.translationKey = p.Kind() + "/" + p.m.translationKey } else if p.IsPage() && !p.File().IsZero() { p.translationKey = path.Join(p.Kind(), filepath.ToSlash(p.File().Dir()), p.File().TranslationBaseName()) } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } }) return p.translationKey } // AllTranslations returns all translations, including the current Page. func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() return p.allTranslations } // Translations returns the translations excluding the current Page. func (p *pageState) Translations() page.Pages { p.s.h.init.translations.Do() return p.translations } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s.Info return nil } func (p *pageState) createRenderHooks(f output.Format) (hooks.Renderers, error) { layoutDescriptor := p.getLayoutDescriptor() layoutDescriptor.RenderingHook = true layoutDescriptor.LayoutOverride = false layoutDescriptor.Layout = "" var renderers hooks.Renderers layoutDescriptor.Kind = "render-link" templ, templFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.LinkRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-image" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.ImageRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-heading" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.HeadingRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } return renderers, nil } func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { p.layoutDescriptorInit.Do(func() { var section string sections := p.SectionsEntries() switch p.Kind() { case page.KindSection: if len(sections) > 0 { section = sections[0] } case page.KindTaxonomy, page.KindTerm: b := p.getTreeRef().n section = b.viewInfo.name.singular default: } p.layoutDescriptor = output.LayoutDescriptor{ Kind: p.Kind(), Type: p.Type(), Lang: p.Language().Lang, Layout: p.Layout(), Section: section, } }) return p.layoutDescriptor } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { f := p.outputFormat() if len(layouts) == 0 { selfLayout := p.selfLayoutForOutput(f) if selfLayout != "" { templ, found := p.s.Tmpl().Lookup(selfLayout) return templ, found, nil } } d := p.getLayoutDescriptor() if len(layouts) > 0 { d.Layout = layouts[0] d.LayoutOverride = true } return p.s.Tmpl().LookupLayout(d, f) } // This is serialized func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { if err := p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } // Must be run after the site section tree etc. is built and ready. func (p *pageState) initPage() error { if _, err := p.init.Do(); err != nil { return err } return nil } func (p *pageState) renderResources() (err error) { p.resourcesPublishInit.Do(func() { var toBeDeleted []int for i, r := range p.Resources() { if _, ok := r.(page.Page); ok { // Pages gets rendered with the owning page but we count them here. p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Pages) continue } src, ok := r.(resource.Source) if !ok { err = errors.Errorf("Resource %T does not support resource.Source", src) return } if err := src.Publish(); err != nil { if os.IsNotExist(err) { // The resource has been deleted from the file system. // This should be extremely rare, but can happen on live reload in server // mode when the same resource is member of different page bundles. toBeDeleted = append(toBeDeleted, i) } else { p.s.Log.Errorf("Failed to publish Resource for page %q: %s", p.pathOrTitle(), err) } } else { p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Files) } } for _, i := range toBeDeleted { p.deleteResource(i) } }) return } func (p *pageState) deleteResource(i int) { p.resources = append(p.resources[:i], p.resources[i+1:]...) } func (p *pageState) getTargetPaths() page.TargetPaths { return p.targetPaths() } func (p *pageState) setTranslations(pages page.Pages) { p.allTranslations = pages page.SortByLanguage(p.allTranslations) translations := make(page.Pages, 0) for _, t := range p.allTranslations { if !t.Eq(p) { translations = append(translations, t) } } p.translations = translations } func (p *pageState) AlternativeOutputFormats() page.OutputFormats { f := p.outputFormat() var o page.OutputFormats for _, of := range p.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defaultRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (p *pageState) RenderString(args ...interface{}) (template.HTML, error) { if len(args) < 1 || len(args) > 2 { return "", errors.New("want 1 or 2 arguments") } var s string opts := defaultRenderStringOpts sidx := 1 if len(args) == 1 { sidx = 0 } else { m, ok := args[0].(map[string]interface{}) if !ok { return "", errors.New("first argument must be a map") } if err := mapstructure.WeakDecode(m, &opts); err != nil { return "", errors.WithMessage(err, "failed to decode options") } } var err error s, err = cast.ToStringE(args[sidx]) if err != nil { return "", err } if err = p.pageOutput.initRenderHooks(); err != nil { return "", err } conv := p.getContentConverter() if opts.Markup != "" && opts.Markup != p.m.markup { var err error // TODO(bep) consider cache conv, err = p.m.newContentConverter(p, opts.Markup, nil) if err != nil { return "", p.wrapError(err) } } var cp *pageContentOutput // If the current content provider is not yet initialized, do so now. if lcp, ok := p.pageOutput.ContentProvider.(*page.LazyContentProvider); ok { c := lcp.Init() if pco, ok := c.(*pageContentOutput); ok { cp = pco } } else { cp = p.pageOutput.cp } c, err := cp.renderContentWithConverter(conv, []byte(s), false) if err != nil { return "", p.wrapError(err) } b := c.Bytes() if opts.Display == "inline" { // We may have to rethink this in the future when we get other // renderers. b = p.s.ContentSpec.TrimShortHTML(b) } return template.HTML(string(b)), nil } func (p *pageState) addDependency(dep identity.Provider) { if !p.s.running() || p.pageOutput.cp == nil { return } p.pageOutput.cp.dependencyTracker.Add(dep) } func (p *pageState) RenderWithTemplateInfo(info tpl.Info, layout ...string) (template.HTML, error) { p.addDependency(info) return p.Render(layout...) } func (p *pageState) Render(layout ...string) (template.HTML, error) { templ, found, err := p.resolveTemplate(layout...) if err != nil { return "", p.wrapError(err) } if !found { return "", nil } p.addDependency(templ.(tpl.Info)) res, err := executeToString(p.s.Tmpl(), templ, p) if err != nil { return "", p.wrapError(errors.Wrapf(err, "failed to execute template %q v", layout)) } return template.HTML(res), nil } // wrapError adds some more context to the given error if possible/needed func (p *pageState) wrapError(err error) error { if _, ok := err.(*herrors.ErrorWithFileContext); ok { // Preserve the first file context. return err } var filename string if !p.File().IsZero() { filename = p.File().Filename() } err, _ = herrors.WithFileContextForFile( err, filename, filename, p.s.SourceSpec.Fs.Source, herrors.SimpleLineMatcher) return err } func (p *pageState) getContentConverter() converter.Converter { var err error p.m.contentConverterInit.Do(func() { markup := p.m.markup if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) }) if err != nil { p.s.Log.Errorln("Failed to create content converter:", err) } return p.m.contentConverter } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { s := p.shortcodeState rn := &pageContentMap{ items: make([]interface{}, 0, 20), } iter := p.source.parsed.Iterator() fail := func(err error, i pageparser.Item) error { return p.parseError(err, iter.Input(), i.Pos) } // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var currShortcode shortcode var ordinal int var frontMatterSet bool Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): f := pageparser.FormatFromFrontMatterType(it.Type) m, err := metadecoders.Default.UnmarshalToMap(it.Val, f) if err != nil { if fe, ok := err.(herrors.FileError); ok { return herrors.ToFileErrorWithOffset(fe, iter.LineNumber()-1) } else { return err } } if err := meta.setMetadata(bucket, p, m); err != nil { return err } frontMatterSet = true next := iter.Peek() if !next.IsDone() { p.source.posMainContent = next.Pos } if !p.s.shouldBuild(p) { // Nothing more to do. return nil } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos } if item.IsNonWhitespace() { p.truncated = true // Done return false } return true } iter.PeekWalk(f) p.source.posSummaryEnd = it.Pos p.source.posBodyStart = posBody p.source.hasSummaryDivider = true if meta.markup != "html" { // The content will be rendered by Blackfriday or similar, // and we need to track the summary. rn.AddReplacement(internalSummaryDividerPre, it) } // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, iter) if err != nil { return fail(errors.Wrap(err, "failed to extract shortcode"), it) } currShortcode.pos = it.Pos currShortcode.length = iter.Current().Pos - it.Pos if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", currShortcode.ordinal) } if currShortcode.name != "" { s.nameSet[currShortcode.name] = true } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", ordinal) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) rn.AddShortcode(currShortcode) case it.Type == pageparser.TypeEmoji: if emoji := helpers.Emoji(it.ValStr()); emoji != nil { rn.AddReplacement(emoji, it) } else { rn.AddBytes(it) } case it.IsEOF(): break Loop case it.IsError(): err := fail(errors.WithStack(errors.New(it.ValStr())), it) currShortcode.err = err return err default: rn.AddBytes(it) } } if !frontMatterSet { // Page content without front matter. Assign default front matter from // cascades etc. if err := meta.setMetadata(bucket, p, nil); err != nil { return err } } p.cmap = rn return nil } func (p *pageState) errorf(err error, format string, a ...interface{}) error { if herrors.UnwrapErrorWithFileContext(err) != nil { // More isn't always better. return err } args := append([]interface{}{p.Language().Lang, p.pathOrTitle()}, a...) format = "[%s] page %q: " + format if err == nil { errors.Errorf(format, args...) return fmt.Errorf(format, args...) } return errors.Wrapf(err, format, args...) } func (p *pageState) outputFormat() (f output.Format) { if p.pageOutput == nil { panic("no pageOutput") } return p.pageOutput.f } func (p *pageState) parseError(err error, input []byte, offset int) error { if herrors.UnwrapFileError(err) != nil { // Use the most specific location. return err } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) } func (p *pageState) pathOrTitle() string { if !p.File().IsZero() { return p.File().Filename() } if p.Pathc() != "" { return p.Pathc() } return p.Title() } func (p *pageState) posFromPage(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } func (p *pageState) posFromInput(input []byte, offset int) text.Position { lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: p.pathOrTitle(), LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } func (p *pageState) posOffset(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := p.initPage(); err != nil { return err } if len(p.pageOutputs) == 1 { idx = 0 } p.pageOutput = p.pageOutputs[idx] if p.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && p.pageOutput.paginator != nil && p.pageOutput.paginator.current != nil { p.pageOutput.paginator.reset() } if isRenderingSite { cp := p.pageOutput.cp if cp == nil { // Look for content to reuse. for i := 0; i < len(p.pageOutputs); i++ { if i == idx { continue } po := p.pageOutputs[i] if po.cp != nil && po.cp.reuse { cp = po.cp break } } } if cp == nil { var err error cp, err = newPageContentOutput(p, p.pageOutput) if err != nil { return err } } p.pageOutput.initContentProvider(cp) } else { // We attempt to assign pageContentOutputs while preparing each site // for rendering and before rendering each site. This lets us share // content between page outputs to conserve resources. But if a template // unexpectedly calls a method of a ContentProvider that is not yet // initialized, we assign a LazyContentProvider that performs the // initialization just in time. if lcp, ok := (p.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok { lcp.Reset() } else { p.pageOutput.ContentProvider = page.NewLazyContentProvider(func() (page.ContentProvider, error) { cp, err := newPageContentOutput(p, p.pageOutput) if err != nil { return nil, err } return cp, nil }) } } return nil } // sourceRef returns the reference used by GetPage and ref/relref shortcodes to refer to // this page. It is prefixed with a "/". // // For pages that have a source file, it is returns the path to this file as an // absolute path rooted in this site's content dir. // For pages that do not (sections without content page etc.), it returns the // virtual path, consistent with where you would add a source file. func (p *pageState) sourceRef() string { if !p.File().IsZero() { sourcePath := p.File().Path() if sourcePath != "" { return "/" + filepath.ToSlash(sourcePath) } } if len(p.SectionsEntries()) > 0 { // no backing file, return the virtual source path return "/" + p.SectionsPath() } return "" } func (s *Site) sectionsFromFile(fi source.File) []string { dirname := fi.Dir() dirname = strings.Trim(dirname, helpers.FilePathSeparator) if dirname == "" { return nil } parts := strings.Split(dirname, helpers.FilePathSeparator) if fii, ok := fi.(*fileInfo); ok { if len(parts) > 0 && fii.FileInfo().Meta().Classifier == files.ContentClassLeaf { // my-section/mybundle/index.md => my-section return parts[:len(parts)-1] } } return parts } var ( _ page.Page = (*pageWithOrdinal)(nil) _ collections.Order = (*pageWithOrdinal)(nil) _ pageWrapper = (*pageWithOrdinal)(nil) ) type pageWithOrdinal struct { ordinal int *pageState } func (p pageWithOrdinal) Ordinal() int { return p.ordinal } func (p pageWithOrdinal) page() page.Page { return p.pageState }
// 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 hugolib import ( "bytes" "fmt" "os" "path" "path/filepath" "sort" "strings" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/hugofs/files" "github.com/bep/gitmap" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/pkg/errors" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, ContentProvider: page.NopPage, TableOfContentsProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter addDependency(dep identity.Provider) } // wrapErr adds some context to the given error if possible. func wrapErr(err error, ctx interface{}) error { if pc, ok := ctx.(pageContext); ok { return pc.wrapError(err) } return err } type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPageWithTemplateInfo(info tpl.Info, ref string) (page.Page, error) { p, err := pa.GetPage(ref) if p != nil { // Track pages referenced by templates/shortcodes // when in server mode. if im, ok := info.(identity.Manager); ok { im.Add(p) } } return p, err } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPageNew(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // This will be shifted out when we start to render a new output format. *pageOutput // Common for all output formats. *pageCommon } func (p *pageState) Err() error { return nil } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (p *pageState) Eq(other interface{}) bool { pp, err := unwrapPage(other) if err != nil { return false } return p == pp } func (p *pageState) GetIdentity() identity.Identity { return identity.NewPathIdentity(files.ComponentFolderContent, filepath.FromSlash(p.Pathc())) } func (p *pageState) GitInfo() *gitmap.GitInfo { return p.gitInfo } // GetTerms gets the terms defined on this page in the given taxonomy. // The pages returned will be ordered according to the front matter. func (p *pageState) GetTerms(taxonomy string) page.Pages { if p.treeRef == nil { return nil } m := p.s.pageMap taxonomy = strings.ToLower(taxonomy) prefix := cleanSectionTreeKey(taxonomy) self := strings.TrimPrefix(p.treeRef.key, "/") var pas page.Pages m.taxonomies.WalkQuery(pageMapQuery{Prefix: prefix}, func(s string, n *contentNode) bool { key := s + self if tn, found := m.taxonomyEntries.Get(key); found { vi := tn.(*contentNode).viewInfo pas = append(pas, pageWithOrdinal{pageState: n.p, ordinal: vi.ordinal}) } return false }) page.SortByDefault(pas) return pas } func (p *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(p) } func (p *pageState) getPages() page.Pages { b := p.bucket if b == nil { return nil } return b.getPages() } func (p *pageState) getPagesRecursive() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesRecursive() } func (p *pageState) getPagesAndSections() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesAndSections() } func (p *pageState) RegularPagesRecursive() page.Pages { p.regularPagesRecursiveInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindSection: pages = p.getPagesRecursive() default: pages = p.RegularPages() } p.regularPagesRecursive = pages }) return p.regularPagesRecursive } func (p *pageState) PagesRecursive() page.Pages { return nil } func (p *pageState) RegularPages() page.Pages { p.regularPagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome, page.KindTaxonomy: pages = p.getPages() case page.KindTerm: all := p.Pages() for _, p := range all { if p.IsPage() { pages = append(pages, p) } } default: pages = p.s.RegularPages() } p.regularPages = pages }) return p.regularPages } func (p *pageState) Pages() page.Pages { p.pagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome: pages = p.getPagesAndSections() case page.KindTerm: pages = p.bucket.getTaxonomyEntries() case page.KindTaxonomy: pages = p.bucket.getTaxonomies() default: pages = p.s.Pages() } p.pages = pages }) return p.pages } // RawContent returns the un-rendered source content without // any leading front matter. func (p *pageState) RawContent() string { if p.source.parsed == nil { return "" } start := p.source.posMainContent if start == -1 { start = 0 } return string(p.source.parsed.Input()[start:]) } func (p *pageState) sortResources() { sort.SliceStable(p.resources, func(i, j int) bool { ri, rj := p.resources[i], p.resources[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() }) } func (p *pageState) Resources() resource.Resources { p.resourcesInit.Do(func() { p.sortResources() if len(p.m.resourcesMetadata) > 0 { resources.AssignMetadata(p.m.resourcesMetadata, p.resources...) p.sortResources() } }) return p.resources } func (p *pageState) HasShortcode(name string) bool { if p.shortcodeState == nil { return false } return p.shortcodeState.nameSet[name] } func (p *pageState) Site() page.Site { return p.s.Info } func (p *pageState) String() string { if sourceRef := p.sourceRef(); sourceRef != "" { return fmt.Sprintf("Page(%s)", sourceRef) } return fmt.Sprintf("Page(%q)", p.Title()) } // IsTranslated returns whether this content file is translated to // other language(s). func (p *pageState) IsTranslated() bool { p.s.h.init.translations.Do() return len(p.translations) > 0 } // TranslationKey returns the key used to map language translations of this page. // It will use the translationKey set in front matter if set, or the content path and // filename (excluding any language code and extension), e.g. "about/index". // The Page Kind is always prepended. func (p *pageState) TranslationKey() string { p.translationKeyInit.Do(func() { if p.m.translationKey != "" { p.translationKey = p.Kind() + "/" + p.m.translationKey } else if p.IsPage() && !p.File().IsZero() { p.translationKey = path.Join(p.Kind(), filepath.ToSlash(p.File().Dir()), p.File().TranslationBaseName()) } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } }) return p.translationKey } // AllTranslations returns all translations, including the current Page. func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() return p.allTranslations } // Translations returns the translations excluding the current Page. func (p *pageState) Translations() page.Pages { p.s.h.init.translations.Do() return p.translations } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s.Info return nil } func (p *pageState) createRenderHooks(f output.Format) (hooks.Renderers, error) { layoutDescriptor := p.getLayoutDescriptor() layoutDescriptor.RenderingHook = true layoutDescriptor.LayoutOverride = false layoutDescriptor.Layout = "" var renderers hooks.Renderers layoutDescriptor.Kind = "render-link" templ, templFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.LinkRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-image" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.ImageRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-heading" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.HeadingRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } return renderers, nil } func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { p.layoutDescriptorInit.Do(func() { var section string sections := p.SectionsEntries() switch p.Kind() { case page.KindSection: if len(sections) > 0 { section = sections[0] } case page.KindTaxonomy, page.KindTerm: b := p.getTreeRef().n section = b.viewInfo.name.singular default: } p.layoutDescriptor = output.LayoutDescriptor{ Kind: p.Kind(), Type: p.Type(), Lang: p.Language().Lang, Layout: p.Layout(), Section: section, } }) return p.layoutDescriptor } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { f := p.outputFormat() if len(layouts) == 0 { selfLayout := p.selfLayoutForOutput(f) if selfLayout != "" { templ, found := p.s.Tmpl().Lookup(selfLayout) return templ, found, nil } } d := p.getLayoutDescriptor() if len(layouts) > 0 { d.Layout = layouts[0] d.LayoutOverride = true } return p.s.Tmpl().LookupLayout(d, f) } // This is serialized func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { if err := p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } // Must be run after the site section tree etc. is built and ready. func (p *pageState) initPage() error { if _, err := p.init.Do(); err != nil { return err } return nil } func (p *pageState) renderResources() (err error) { p.resourcesPublishInit.Do(func() { var toBeDeleted []int for i, r := range p.Resources() { if _, ok := r.(page.Page); ok { // Pages gets rendered with the owning page but we count them here. p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Pages) continue } src, ok := r.(resource.Source) if !ok { err = errors.Errorf("Resource %T does not support resource.Source", src) return } if err := src.Publish(); err != nil { if os.IsNotExist(err) { // The resource has been deleted from the file system. // This should be extremely rare, but can happen on live reload in server // mode when the same resource is member of different page bundles. toBeDeleted = append(toBeDeleted, i) } else { p.s.Log.Errorf("Failed to publish Resource for page %q: %s", p.pathOrTitle(), err) } } else { p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Files) } } for _, i := range toBeDeleted { p.deleteResource(i) } }) return } func (p *pageState) deleteResource(i int) { p.resources = append(p.resources[:i], p.resources[i+1:]...) } func (p *pageState) getTargetPaths() page.TargetPaths { return p.targetPaths() } func (p *pageState) setTranslations(pages page.Pages) { p.allTranslations = pages page.SortByLanguage(p.allTranslations) translations := make(page.Pages, 0) for _, t := range p.allTranslations { if !t.Eq(p) { translations = append(translations, t) } } p.translations = translations } func (p *pageState) AlternativeOutputFormats() page.OutputFormats { f := p.outputFormat() var o page.OutputFormats for _, of := range p.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defaultRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (p *pageState) addDependency(dep identity.Provider) { if !p.s.running() || p.pageOutput.cp == nil { return } p.pageOutput.cp.dependencyTracker.Add(dep) } // wrapError adds some more context to the given error if possible/needed func (p *pageState) wrapError(err error) error { if _, ok := err.(*herrors.ErrorWithFileContext); ok { // Preserve the first file context. return err } var filename string if !p.File().IsZero() { filename = p.File().Filename() } err, _ = herrors.WithFileContextForFile( err, filename, filename, p.s.SourceSpec.Fs.Source, herrors.SimpleLineMatcher) return err } func (p *pageState) getContentConverter() converter.Converter { var err error p.m.contentConverterInit.Do(func() { markup := p.m.markup if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) }) if err != nil { p.s.Log.Errorln("Failed to create content converter:", err) } return p.m.contentConverter } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { s := p.shortcodeState rn := &pageContentMap{ items: make([]interface{}, 0, 20), } iter := p.source.parsed.Iterator() fail := func(err error, i pageparser.Item) error { return p.parseError(err, iter.Input(), i.Pos) } // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var currShortcode shortcode var ordinal int var frontMatterSet bool Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): f := pageparser.FormatFromFrontMatterType(it.Type) m, err := metadecoders.Default.UnmarshalToMap(it.Val, f) if err != nil { if fe, ok := err.(herrors.FileError); ok { return herrors.ToFileErrorWithOffset(fe, iter.LineNumber()-1) } else { return err } } if err := meta.setMetadata(bucket, p, m); err != nil { return err } frontMatterSet = true next := iter.Peek() if !next.IsDone() { p.source.posMainContent = next.Pos } if !p.s.shouldBuild(p) { // Nothing more to do. return nil } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos } if item.IsNonWhitespace() { p.truncated = true // Done return false } return true } iter.PeekWalk(f) p.source.posSummaryEnd = it.Pos p.source.posBodyStart = posBody p.source.hasSummaryDivider = true if meta.markup != "html" { // The content will be rendered by Blackfriday or similar, // and we need to track the summary. rn.AddReplacement(internalSummaryDividerPre, it) } // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, iter) if err != nil { return fail(errors.Wrap(err, "failed to extract shortcode"), it) } currShortcode.pos = it.Pos currShortcode.length = iter.Current().Pos - it.Pos if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", currShortcode.ordinal) } if currShortcode.name != "" { s.nameSet[currShortcode.name] = true } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", ordinal) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) rn.AddShortcode(currShortcode) case it.Type == pageparser.TypeEmoji: if emoji := helpers.Emoji(it.ValStr()); emoji != nil { rn.AddReplacement(emoji, it) } else { rn.AddBytes(it) } case it.IsEOF(): break Loop case it.IsError(): err := fail(errors.WithStack(errors.New(it.ValStr())), it) currShortcode.err = err return err default: rn.AddBytes(it) } } if !frontMatterSet { // Page content without front matter. Assign default front matter from // cascades etc. if err := meta.setMetadata(bucket, p, nil); err != nil { return err } } p.cmap = rn return nil } func (p *pageState) errorf(err error, format string, a ...interface{}) error { if herrors.UnwrapErrorWithFileContext(err) != nil { // More isn't always better. return err } args := append([]interface{}{p.Language().Lang, p.pathOrTitle()}, a...) format = "[%s] page %q: " + format if err == nil { errors.Errorf(format, args...) return fmt.Errorf(format, args...) } return errors.Wrapf(err, format, args...) } func (p *pageState) outputFormat() (f output.Format) { if p.pageOutput == nil { panic("no pageOutput") } return p.pageOutput.f } func (p *pageState) parseError(err error, input []byte, offset int) error { if herrors.UnwrapFileError(err) != nil { // Use the most specific location. return err } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) } func (p *pageState) pathOrTitle() string { if !p.File().IsZero() { return p.File().Filename() } if p.Pathc() != "" { return p.Pathc() } return p.Title() } func (p *pageState) posFromPage(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } func (p *pageState) posFromInput(input []byte, offset int) text.Position { lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: p.pathOrTitle(), LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } func (p *pageState) posOffset(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := p.initPage(); err != nil { return err } if len(p.pageOutputs) == 1 { idx = 0 } p.pageOutput = p.pageOutputs[idx] if p.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && p.pageOutput.paginator != nil && p.pageOutput.paginator.current != nil { p.pageOutput.paginator.reset() } if isRenderingSite { cp := p.pageOutput.cp if cp == nil { // Look for content to reuse. for i := 0; i < len(p.pageOutputs); i++ { if i == idx { continue } po := p.pageOutputs[i] if po.cp != nil && po.cp.reuse { cp = po.cp break } } } if cp == nil { var err error cp, err = newPageContentOutput(p, p.pageOutput) if err != nil { return err } } p.pageOutput.initContentProvider(cp) } else { // We attempt to assign pageContentOutputs while preparing each site // for rendering and before rendering each site. This lets us share // content between page outputs to conserve resources. But if a template // unexpectedly calls a method of a ContentProvider that is not yet // initialized, we assign a LazyContentProvider that performs the // initialization just in time. if lcp, ok := (p.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok { lcp.Reset() } else { lcp = page.NewLazyContentProvider(func() (page.OutputFormatContentProvider, error) { cp, err := newPageContentOutput(p, p.pageOutput) if err != nil { return nil, err } return cp, nil }) p.pageOutput.ContentProvider = lcp p.pageOutput.TableOfContentsProvider = lcp p.pageOutput.PageRenderProvider = lcp } } return nil } // sourceRef returns the reference used by GetPage and ref/relref shortcodes to refer to // this page. It is prefixed with a "/". // // For pages that have a source file, it is returns the path to this file as an // absolute path rooted in this site's content dir. // For pages that do not (sections without content page etc.), it returns the // virtual path, consistent with where you would add a source file. func (p *pageState) sourceRef() string { if !p.File().IsZero() { sourcePath := p.File().Path() if sourcePath != "" { return "/" + filepath.ToSlash(sourcePath) } } if len(p.SectionsEntries()) > 0 { // no backing file, return the virtual source path return "/" + p.SectionsPath() } return "" } func (s *Site) sectionsFromFile(fi source.File) []string { dirname := fi.Dir() dirname = strings.Trim(dirname, helpers.FilePathSeparator) if dirname == "" { return nil } parts := strings.Split(dirname, helpers.FilePathSeparator) if fii, ok := fi.(*fileInfo); ok { if len(parts) > 0 && fii.FileInfo().Meta().Classifier == files.ContentClassLeaf { // my-section/mybundle/index.md => my-section return parts[:len(parts)-1] } } return parts } var ( _ page.Page = (*pageWithOrdinal)(nil) _ collections.Order = (*pageWithOrdinal)(nil) _ pageWrapper = (*pageWithOrdinal)(nil) ) type pageWithOrdinal struct { ordinal int *pageState } func (p pageWithOrdinal) Ordinal() int { return p.ordinal } func (p pageWithOrdinal) page() page.Page { return p.pageState }
ptgott
85d31f7bfb7a13c9ab7655829a315a820dc1b403
f22c4aba047e89130bf9921c5ded3823743a9ffa
Thanks for the feedback. Would you mind explaining the data race a bit more? Which goroutines, processes, I/O, etc. would be racing? I'll spend some time early this week implementing the approach you've suggested.
ptgott
123
gohugoio/hugo
9,398
Ensure page translation CPs are initialized
PR #9342 introduced a regression in which calling .Translations in a template and calling RenderString on a translated Page caused a nil pointer dereference. The issue was that some Pages returned from .Translations had a nil cp field at the time the calling template was being executed. While PR #9342 had attempted to ensure that all ContentProviders were initialized for translations at build time, it only performed the initialization for receivers of ContentProvider methods such as .Summary. However, the ContentProvider's *pageState.pageOutput.cp would remain uninitialized, causing the nil pointer dereference. This change edits the .Translations and .AllTranslations methods to ensure that all of a page's translations have an initialized content provider in time for a template to be executed. Since LazyContentProvider is no longer needed with this approach, this change also reverts the following commits: - cdcd15b6c2abbb76fd95fbbf90365c56e82f46aa - 25d645f47ae0a32470d303c9478c9e0b2fff0f0e Fixes #9383
null
2022-01-16 21:11:13+00:00
2022-01-27 10:51:13+00:00
hugolib/page.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 hugolib import ( "bytes" "fmt" "html/template" "os" "path" "path/filepath" "sort" "strings" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/hugofs/files" "github.com/bep/gitmap" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/pkg/errors" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, ContentProvider: page.NopPage, TableOfContentsProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter addDependency(dep identity.Provider) } // wrapErr adds some context to the given error if possible. func wrapErr(err error, ctx interface{}) error { if pc, ok := ctx.(pageContext); ok { return pc.wrapError(err) } return err } type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPageWithTemplateInfo(info tpl.Info, ref string) (page.Page, error) { p, err := pa.GetPage(ref) if p != nil { // Track pages referenced by templates/shortcodes // when in server mode. if im, ok := info.(identity.Manager); ok { im.Add(p) } } return p, err } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPageNew(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // This will be shifted out when we start to render a new output format. *pageOutput // Common for all output formats. *pageCommon } func (p *pageState) Err() error { return nil } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (p *pageState) Eq(other interface{}) bool { pp, err := unwrapPage(other) if err != nil { return false } return p == pp } func (p *pageState) GetIdentity() identity.Identity { return identity.NewPathIdentity(files.ComponentFolderContent, filepath.FromSlash(p.Pathc())) } func (p *pageState) GitInfo() *gitmap.GitInfo { return p.gitInfo } // GetTerms gets the terms defined on this page in the given taxonomy. // The pages returned will be ordered according to the front matter. func (p *pageState) GetTerms(taxonomy string) page.Pages { if p.treeRef == nil { return nil } m := p.s.pageMap taxonomy = strings.ToLower(taxonomy) prefix := cleanSectionTreeKey(taxonomy) self := strings.TrimPrefix(p.treeRef.key, "/") var pas page.Pages m.taxonomies.WalkQuery(pageMapQuery{Prefix: prefix}, func(s string, n *contentNode) bool { key := s + self if tn, found := m.taxonomyEntries.Get(key); found { vi := tn.(*contentNode).viewInfo pas = append(pas, pageWithOrdinal{pageState: n.p, ordinal: vi.ordinal}) } return false }) page.SortByDefault(pas) return pas } func (p *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(p) } func (p *pageState) getPages() page.Pages { b := p.bucket if b == nil { return nil } return b.getPages() } func (p *pageState) getPagesRecursive() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesRecursive() } func (p *pageState) getPagesAndSections() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesAndSections() } func (p *pageState) RegularPagesRecursive() page.Pages { p.regularPagesRecursiveInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindSection: pages = p.getPagesRecursive() default: pages = p.RegularPages() } p.regularPagesRecursive = pages }) return p.regularPagesRecursive } func (p *pageState) PagesRecursive() page.Pages { return nil } func (p *pageState) RegularPages() page.Pages { p.regularPagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome, page.KindTaxonomy: pages = p.getPages() case page.KindTerm: all := p.Pages() for _, p := range all { if p.IsPage() { pages = append(pages, p) } } default: pages = p.s.RegularPages() } p.regularPages = pages }) return p.regularPages } func (p *pageState) Pages() page.Pages { p.pagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome: pages = p.getPagesAndSections() case page.KindTerm: pages = p.bucket.getTaxonomyEntries() case page.KindTaxonomy: pages = p.bucket.getTaxonomies() default: pages = p.s.Pages() } p.pages = pages }) return p.pages } // RawContent returns the un-rendered source content without // any leading front matter. func (p *pageState) RawContent() string { if p.source.parsed == nil { return "" } start := p.source.posMainContent if start == -1 { start = 0 } return string(p.source.parsed.Input()[start:]) } func (p *pageState) sortResources() { sort.SliceStable(p.resources, func(i, j int) bool { ri, rj := p.resources[i], p.resources[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() }) } func (p *pageState) Resources() resource.Resources { p.resourcesInit.Do(func() { p.sortResources() if len(p.m.resourcesMetadata) > 0 { resources.AssignMetadata(p.m.resourcesMetadata, p.resources...) p.sortResources() } }) return p.resources } func (p *pageState) HasShortcode(name string) bool { if p.shortcodeState == nil { return false } return p.shortcodeState.nameSet[name] } func (p *pageState) Site() page.Site { return p.s.Info } func (p *pageState) String() string { if sourceRef := p.sourceRef(); sourceRef != "" { return fmt.Sprintf("Page(%s)", sourceRef) } return fmt.Sprintf("Page(%q)", p.Title()) } // IsTranslated returns whether this content file is translated to // other language(s). func (p *pageState) IsTranslated() bool { p.s.h.init.translations.Do() return len(p.translations) > 0 } // TranslationKey returns the key used to map language translations of this page. // It will use the translationKey set in front matter if set, or the content path and // filename (excluding any language code and extension), e.g. "about/index". // The Page Kind is always prepended. func (p *pageState) TranslationKey() string { p.translationKeyInit.Do(func() { if p.m.translationKey != "" { p.translationKey = p.Kind() + "/" + p.m.translationKey } else if p.IsPage() && !p.File().IsZero() { p.translationKey = path.Join(p.Kind(), filepath.ToSlash(p.File().Dir()), p.File().TranslationBaseName()) } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } }) return p.translationKey } // AllTranslations returns all translations, including the current Page. func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() return p.allTranslations } // Translations returns the translations excluding the current Page. func (p *pageState) Translations() page.Pages { p.s.h.init.translations.Do() return p.translations } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s.Info return nil } func (p *pageState) createRenderHooks(f output.Format) (hooks.Renderers, error) { layoutDescriptor := p.getLayoutDescriptor() layoutDescriptor.RenderingHook = true layoutDescriptor.LayoutOverride = false layoutDescriptor.Layout = "" var renderers hooks.Renderers layoutDescriptor.Kind = "render-link" templ, templFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.LinkRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-image" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.ImageRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-heading" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.HeadingRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } return renderers, nil } func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { p.layoutDescriptorInit.Do(func() { var section string sections := p.SectionsEntries() switch p.Kind() { case page.KindSection: if len(sections) > 0 { section = sections[0] } case page.KindTaxonomy, page.KindTerm: b := p.getTreeRef().n section = b.viewInfo.name.singular default: } p.layoutDescriptor = output.LayoutDescriptor{ Kind: p.Kind(), Type: p.Type(), Lang: p.Language().Lang, Layout: p.Layout(), Section: section, } }) return p.layoutDescriptor } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { f := p.outputFormat() if len(layouts) == 0 { selfLayout := p.selfLayoutForOutput(f) if selfLayout != "" { templ, found := p.s.Tmpl().Lookup(selfLayout) return templ, found, nil } } d := p.getLayoutDescriptor() if len(layouts) > 0 { d.Layout = layouts[0] d.LayoutOverride = true } return p.s.Tmpl().LookupLayout(d, f) } // This is serialized func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { if err := p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } // Must be run after the site section tree etc. is built and ready. func (p *pageState) initPage() error { if _, err := p.init.Do(); err != nil { return err } return nil } func (p *pageState) renderResources() (err error) { p.resourcesPublishInit.Do(func() { var toBeDeleted []int for i, r := range p.Resources() { if _, ok := r.(page.Page); ok { // Pages gets rendered with the owning page but we count them here. p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Pages) continue } src, ok := r.(resource.Source) if !ok { err = errors.Errorf("Resource %T does not support resource.Source", src) return } if err := src.Publish(); err != nil { if os.IsNotExist(err) { // The resource has been deleted from the file system. // This should be extremely rare, but can happen on live reload in server // mode when the same resource is member of different page bundles. toBeDeleted = append(toBeDeleted, i) } else { p.s.Log.Errorf("Failed to publish Resource for page %q: %s", p.pathOrTitle(), err) } } else { p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Files) } } for _, i := range toBeDeleted { p.deleteResource(i) } }) return } func (p *pageState) deleteResource(i int) { p.resources = append(p.resources[:i], p.resources[i+1:]...) } func (p *pageState) getTargetPaths() page.TargetPaths { return p.targetPaths() } func (p *pageState) setTranslations(pages page.Pages) { p.allTranslations = pages page.SortByLanguage(p.allTranslations) translations := make(page.Pages, 0) for _, t := range p.allTranslations { if !t.Eq(p) { translations = append(translations, t) } } p.translations = translations } func (p *pageState) AlternativeOutputFormats() page.OutputFormats { f := p.outputFormat() var o page.OutputFormats for _, of := range p.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defaultRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (p *pageState) RenderString(args ...interface{}) (template.HTML, error) { if len(args) < 1 || len(args) > 2 { return "", errors.New("want 1 or 2 arguments") } var s string opts := defaultRenderStringOpts sidx := 1 if len(args) == 1 { sidx = 0 } else { m, ok := args[0].(map[string]interface{}) if !ok { return "", errors.New("first argument must be a map") } if err := mapstructure.WeakDecode(m, &opts); err != nil { return "", errors.WithMessage(err, "failed to decode options") } } var err error s, err = cast.ToStringE(args[sidx]) if err != nil { return "", err } if err = p.pageOutput.initRenderHooks(); err != nil { return "", err } conv := p.getContentConverter() if opts.Markup != "" && opts.Markup != p.m.markup { var err error // TODO(bep) consider cache conv, err = p.m.newContentConverter(p, opts.Markup, nil) if err != nil { return "", p.wrapError(err) } } var cp *pageContentOutput // If the current content provider is not yet initialized, do so now. if lcp, ok := p.pageOutput.ContentProvider.(*page.LazyContentProvider); ok { c := lcp.Init() if pco, ok := c.(*pageContentOutput); ok { cp = pco } } else { cp = p.pageOutput.cp } c, err := cp.renderContentWithConverter(conv, []byte(s), false) if err != nil { return "", p.wrapError(err) } b := c.Bytes() if opts.Display == "inline" { // We may have to rethink this in the future when we get other // renderers. b = p.s.ContentSpec.TrimShortHTML(b) } return template.HTML(string(b)), nil } func (p *pageState) addDependency(dep identity.Provider) { if !p.s.running() || p.pageOutput.cp == nil { return } p.pageOutput.cp.dependencyTracker.Add(dep) } func (p *pageState) RenderWithTemplateInfo(info tpl.Info, layout ...string) (template.HTML, error) { p.addDependency(info) return p.Render(layout...) } func (p *pageState) Render(layout ...string) (template.HTML, error) { templ, found, err := p.resolveTemplate(layout...) if err != nil { return "", p.wrapError(err) } if !found { return "", nil } p.addDependency(templ.(tpl.Info)) res, err := executeToString(p.s.Tmpl(), templ, p) if err != nil { return "", p.wrapError(errors.Wrapf(err, "failed to execute template %q v", layout)) } return template.HTML(res), nil } // wrapError adds some more context to the given error if possible/needed func (p *pageState) wrapError(err error) error { if _, ok := err.(*herrors.ErrorWithFileContext); ok { // Preserve the first file context. return err } var filename string if !p.File().IsZero() { filename = p.File().Filename() } err, _ = herrors.WithFileContextForFile( err, filename, filename, p.s.SourceSpec.Fs.Source, herrors.SimpleLineMatcher) return err } func (p *pageState) getContentConverter() converter.Converter { var err error p.m.contentConverterInit.Do(func() { markup := p.m.markup if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) }) if err != nil { p.s.Log.Errorln("Failed to create content converter:", err) } return p.m.contentConverter } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { s := p.shortcodeState rn := &pageContentMap{ items: make([]interface{}, 0, 20), } iter := p.source.parsed.Iterator() fail := func(err error, i pageparser.Item) error { return p.parseError(err, iter.Input(), i.Pos) } // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var currShortcode shortcode var ordinal int var frontMatterSet bool Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): f := pageparser.FormatFromFrontMatterType(it.Type) m, err := metadecoders.Default.UnmarshalToMap(it.Val, f) if err != nil { if fe, ok := err.(herrors.FileError); ok { return herrors.ToFileErrorWithOffset(fe, iter.LineNumber()-1) } else { return err } } if err := meta.setMetadata(bucket, p, m); err != nil { return err } frontMatterSet = true next := iter.Peek() if !next.IsDone() { p.source.posMainContent = next.Pos } if !p.s.shouldBuild(p) { // Nothing more to do. return nil } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos } if item.IsNonWhitespace() { p.truncated = true // Done return false } return true } iter.PeekWalk(f) p.source.posSummaryEnd = it.Pos p.source.posBodyStart = posBody p.source.hasSummaryDivider = true if meta.markup != "html" { // The content will be rendered by Blackfriday or similar, // and we need to track the summary. rn.AddReplacement(internalSummaryDividerPre, it) } // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, iter) if err != nil { return fail(errors.Wrap(err, "failed to extract shortcode"), it) } currShortcode.pos = it.Pos currShortcode.length = iter.Current().Pos - it.Pos if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", currShortcode.ordinal) } if currShortcode.name != "" { s.nameSet[currShortcode.name] = true } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", ordinal) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) rn.AddShortcode(currShortcode) case it.Type == pageparser.TypeEmoji: if emoji := helpers.Emoji(it.ValStr()); emoji != nil { rn.AddReplacement(emoji, it) } else { rn.AddBytes(it) } case it.IsEOF(): break Loop case it.IsError(): err := fail(errors.WithStack(errors.New(it.ValStr())), it) currShortcode.err = err return err default: rn.AddBytes(it) } } if !frontMatterSet { // Page content without front matter. Assign default front matter from // cascades etc. if err := meta.setMetadata(bucket, p, nil); err != nil { return err } } p.cmap = rn return nil } func (p *pageState) errorf(err error, format string, a ...interface{}) error { if herrors.UnwrapErrorWithFileContext(err) != nil { // More isn't always better. return err } args := append([]interface{}{p.Language().Lang, p.pathOrTitle()}, a...) format = "[%s] page %q: " + format if err == nil { errors.Errorf(format, args...) return fmt.Errorf(format, args...) } return errors.Wrapf(err, format, args...) } func (p *pageState) outputFormat() (f output.Format) { if p.pageOutput == nil { panic("no pageOutput") } return p.pageOutput.f } func (p *pageState) parseError(err error, input []byte, offset int) error { if herrors.UnwrapFileError(err) != nil { // Use the most specific location. return err } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) } func (p *pageState) pathOrTitle() string { if !p.File().IsZero() { return p.File().Filename() } if p.Pathc() != "" { return p.Pathc() } return p.Title() } func (p *pageState) posFromPage(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } func (p *pageState) posFromInput(input []byte, offset int) text.Position { lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: p.pathOrTitle(), LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } func (p *pageState) posOffset(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := p.initPage(); err != nil { return err } if len(p.pageOutputs) == 1 { idx = 0 } p.pageOutput = p.pageOutputs[idx] if p.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && p.pageOutput.paginator != nil && p.pageOutput.paginator.current != nil { p.pageOutput.paginator.reset() } if isRenderingSite { cp := p.pageOutput.cp if cp == nil { // Look for content to reuse. for i := 0; i < len(p.pageOutputs); i++ { if i == idx { continue } po := p.pageOutputs[i] if po.cp != nil && po.cp.reuse { cp = po.cp break } } } if cp == nil { var err error cp, err = newPageContentOutput(p, p.pageOutput) if err != nil { return err } } p.pageOutput.initContentProvider(cp) } else { // We attempt to assign pageContentOutputs while preparing each site // for rendering and before rendering each site. This lets us share // content between page outputs to conserve resources. But if a template // unexpectedly calls a method of a ContentProvider that is not yet // initialized, we assign a LazyContentProvider that performs the // initialization just in time. if lcp, ok := (p.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok { lcp.Reset() } else { p.pageOutput.ContentProvider = page.NewLazyContentProvider(func() (page.ContentProvider, error) { cp, err := newPageContentOutput(p, p.pageOutput) if err != nil { return nil, err } return cp, nil }) } } return nil } // sourceRef returns the reference used by GetPage and ref/relref shortcodes to refer to // this page. It is prefixed with a "/". // // For pages that have a source file, it is returns the path to this file as an // absolute path rooted in this site's content dir. // For pages that do not (sections without content page etc.), it returns the // virtual path, consistent with where you would add a source file. func (p *pageState) sourceRef() string { if !p.File().IsZero() { sourcePath := p.File().Path() if sourcePath != "" { return "/" + filepath.ToSlash(sourcePath) } } if len(p.SectionsEntries()) > 0 { // no backing file, return the virtual source path return "/" + p.SectionsPath() } return "" } func (s *Site) sectionsFromFile(fi source.File) []string { dirname := fi.Dir() dirname = strings.Trim(dirname, helpers.FilePathSeparator) if dirname == "" { return nil } parts := strings.Split(dirname, helpers.FilePathSeparator) if fii, ok := fi.(*fileInfo); ok { if len(parts) > 0 && fii.FileInfo().Meta().Classifier == files.ContentClassLeaf { // my-section/mybundle/index.md => my-section return parts[:len(parts)-1] } } return parts } var ( _ page.Page = (*pageWithOrdinal)(nil) _ collections.Order = (*pageWithOrdinal)(nil) _ pageWrapper = (*pageWithOrdinal)(nil) ) type pageWithOrdinal struct { ordinal int *pageState } func (p pageWithOrdinal) Ordinal() int { return p.ordinal } func (p pageWithOrdinal) page() page.Page { return p.pageState }
// 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 hugolib import ( "bytes" "fmt" "os" "path" "path/filepath" "sort" "strings" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/hugofs/files" "github.com/bep/gitmap" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/pkg/errors" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, ContentProvider: page.NopPage, TableOfContentsProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter addDependency(dep identity.Provider) } // wrapErr adds some context to the given error if possible. func wrapErr(err error, ctx interface{}) error { if pc, ok := ctx.(pageContext); ok { return pc.wrapError(err) } return err } type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPageWithTemplateInfo(info tpl.Info, ref string) (page.Page, error) { p, err := pa.GetPage(ref) if p != nil { // Track pages referenced by templates/shortcodes // when in server mode. if im, ok := info.(identity.Manager); ok { im.Add(p) } } return p, err } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPageNew(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // This will be shifted out when we start to render a new output format. *pageOutput // Common for all output formats. *pageCommon } func (p *pageState) Err() error { return nil } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (p *pageState) Eq(other interface{}) bool { pp, err := unwrapPage(other) if err != nil { return false } return p == pp } func (p *pageState) GetIdentity() identity.Identity { return identity.NewPathIdentity(files.ComponentFolderContent, filepath.FromSlash(p.Pathc())) } func (p *pageState) GitInfo() *gitmap.GitInfo { return p.gitInfo } // GetTerms gets the terms defined on this page in the given taxonomy. // The pages returned will be ordered according to the front matter. func (p *pageState) GetTerms(taxonomy string) page.Pages { if p.treeRef == nil { return nil } m := p.s.pageMap taxonomy = strings.ToLower(taxonomy) prefix := cleanSectionTreeKey(taxonomy) self := strings.TrimPrefix(p.treeRef.key, "/") var pas page.Pages m.taxonomies.WalkQuery(pageMapQuery{Prefix: prefix}, func(s string, n *contentNode) bool { key := s + self if tn, found := m.taxonomyEntries.Get(key); found { vi := tn.(*contentNode).viewInfo pas = append(pas, pageWithOrdinal{pageState: n.p, ordinal: vi.ordinal}) } return false }) page.SortByDefault(pas) return pas } func (p *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(p) } func (p *pageState) getPages() page.Pages { b := p.bucket if b == nil { return nil } return b.getPages() } func (p *pageState) getPagesRecursive() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesRecursive() } func (p *pageState) getPagesAndSections() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesAndSections() } func (p *pageState) RegularPagesRecursive() page.Pages { p.regularPagesRecursiveInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindSection: pages = p.getPagesRecursive() default: pages = p.RegularPages() } p.regularPagesRecursive = pages }) return p.regularPagesRecursive } func (p *pageState) PagesRecursive() page.Pages { return nil } func (p *pageState) RegularPages() page.Pages { p.regularPagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome, page.KindTaxonomy: pages = p.getPages() case page.KindTerm: all := p.Pages() for _, p := range all { if p.IsPage() { pages = append(pages, p) } } default: pages = p.s.RegularPages() } p.regularPages = pages }) return p.regularPages } func (p *pageState) Pages() page.Pages { p.pagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome: pages = p.getPagesAndSections() case page.KindTerm: pages = p.bucket.getTaxonomyEntries() case page.KindTaxonomy: pages = p.bucket.getTaxonomies() default: pages = p.s.Pages() } p.pages = pages }) return p.pages } // RawContent returns the un-rendered source content without // any leading front matter. func (p *pageState) RawContent() string { if p.source.parsed == nil { return "" } start := p.source.posMainContent if start == -1 { start = 0 } return string(p.source.parsed.Input()[start:]) } func (p *pageState) sortResources() { sort.SliceStable(p.resources, func(i, j int) bool { ri, rj := p.resources[i], p.resources[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() }) } func (p *pageState) Resources() resource.Resources { p.resourcesInit.Do(func() { p.sortResources() if len(p.m.resourcesMetadata) > 0 { resources.AssignMetadata(p.m.resourcesMetadata, p.resources...) p.sortResources() } }) return p.resources } func (p *pageState) HasShortcode(name string) bool { if p.shortcodeState == nil { return false } return p.shortcodeState.nameSet[name] } func (p *pageState) Site() page.Site { return p.s.Info } func (p *pageState) String() string { if sourceRef := p.sourceRef(); sourceRef != "" { return fmt.Sprintf("Page(%s)", sourceRef) } return fmt.Sprintf("Page(%q)", p.Title()) } // IsTranslated returns whether this content file is translated to // other language(s). func (p *pageState) IsTranslated() bool { p.s.h.init.translations.Do() return len(p.translations) > 0 } // TranslationKey returns the key used to map language translations of this page. // It will use the translationKey set in front matter if set, or the content path and // filename (excluding any language code and extension), e.g. "about/index". // The Page Kind is always prepended. func (p *pageState) TranslationKey() string { p.translationKeyInit.Do(func() { if p.m.translationKey != "" { p.translationKey = p.Kind() + "/" + p.m.translationKey } else if p.IsPage() && !p.File().IsZero() { p.translationKey = path.Join(p.Kind(), filepath.ToSlash(p.File().Dir()), p.File().TranslationBaseName()) } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } }) return p.translationKey } // AllTranslations returns all translations, including the current Page. func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() return p.allTranslations } // Translations returns the translations excluding the current Page. func (p *pageState) Translations() page.Pages { p.s.h.init.translations.Do() return p.translations } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s.Info return nil } func (p *pageState) createRenderHooks(f output.Format) (hooks.Renderers, error) { layoutDescriptor := p.getLayoutDescriptor() layoutDescriptor.RenderingHook = true layoutDescriptor.LayoutOverride = false layoutDescriptor.Layout = "" var renderers hooks.Renderers layoutDescriptor.Kind = "render-link" templ, templFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.LinkRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-image" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.ImageRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-heading" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.HeadingRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } return renderers, nil } func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { p.layoutDescriptorInit.Do(func() { var section string sections := p.SectionsEntries() switch p.Kind() { case page.KindSection: if len(sections) > 0 { section = sections[0] } case page.KindTaxonomy, page.KindTerm: b := p.getTreeRef().n section = b.viewInfo.name.singular default: } p.layoutDescriptor = output.LayoutDescriptor{ Kind: p.Kind(), Type: p.Type(), Lang: p.Language().Lang, Layout: p.Layout(), Section: section, } }) return p.layoutDescriptor } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { f := p.outputFormat() if len(layouts) == 0 { selfLayout := p.selfLayoutForOutput(f) if selfLayout != "" { templ, found := p.s.Tmpl().Lookup(selfLayout) return templ, found, nil } } d := p.getLayoutDescriptor() if len(layouts) > 0 { d.Layout = layouts[0] d.LayoutOverride = true } return p.s.Tmpl().LookupLayout(d, f) } // This is serialized func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { if err := p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } // Must be run after the site section tree etc. is built and ready. func (p *pageState) initPage() error { if _, err := p.init.Do(); err != nil { return err } return nil } func (p *pageState) renderResources() (err error) { p.resourcesPublishInit.Do(func() { var toBeDeleted []int for i, r := range p.Resources() { if _, ok := r.(page.Page); ok { // Pages gets rendered with the owning page but we count them here. p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Pages) continue } src, ok := r.(resource.Source) if !ok { err = errors.Errorf("Resource %T does not support resource.Source", src) return } if err := src.Publish(); err != nil { if os.IsNotExist(err) { // The resource has been deleted from the file system. // This should be extremely rare, but can happen on live reload in server // mode when the same resource is member of different page bundles. toBeDeleted = append(toBeDeleted, i) } else { p.s.Log.Errorf("Failed to publish Resource for page %q: %s", p.pathOrTitle(), err) } } else { p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Files) } } for _, i := range toBeDeleted { p.deleteResource(i) } }) return } func (p *pageState) deleteResource(i int) { p.resources = append(p.resources[:i], p.resources[i+1:]...) } func (p *pageState) getTargetPaths() page.TargetPaths { return p.targetPaths() } func (p *pageState) setTranslations(pages page.Pages) { p.allTranslations = pages page.SortByLanguage(p.allTranslations) translations := make(page.Pages, 0) for _, t := range p.allTranslations { if !t.Eq(p) { translations = append(translations, t) } } p.translations = translations } func (p *pageState) AlternativeOutputFormats() page.OutputFormats { f := p.outputFormat() var o page.OutputFormats for _, of := range p.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defaultRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (p *pageState) addDependency(dep identity.Provider) { if !p.s.running() || p.pageOutput.cp == nil { return } p.pageOutput.cp.dependencyTracker.Add(dep) } // wrapError adds some more context to the given error if possible/needed func (p *pageState) wrapError(err error) error { if _, ok := err.(*herrors.ErrorWithFileContext); ok { // Preserve the first file context. return err } var filename string if !p.File().IsZero() { filename = p.File().Filename() } err, _ = herrors.WithFileContextForFile( err, filename, filename, p.s.SourceSpec.Fs.Source, herrors.SimpleLineMatcher) return err } func (p *pageState) getContentConverter() converter.Converter { var err error p.m.contentConverterInit.Do(func() { markup := p.m.markup if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) }) if err != nil { p.s.Log.Errorln("Failed to create content converter:", err) } return p.m.contentConverter } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { s := p.shortcodeState rn := &pageContentMap{ items: make([]interface{}, 0, 20), } iter := p.source.parsed.Iterator() fail := func(err error, i pageparser.Item) error { return p.parseError(err, iter.Input(), i.Pos) } // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var currShortcode shortcode var ordinal int var frontMatterSet bool Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): f := pageparser.FormatFromFrontMatterType(it.Type) m, err := metadecoders.Default.UnmarshalToMap(it.Val, f) if err != nil { if fe, ok := err.(herrors.FileError); ok { return herrors.ToFileErrorWithOffset(fe, iter.LineNumber()-1) } else { return err } } if err := meta.setMetadata(bucket, p, m); err != nil { return err } frontMatterSet = true next := iter.Peek() if !next.IsDone() { p.source.posMainContent = next.Pos } if !p.s.shouldBuild(p) { // Nothing more to do. return nil } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos } if item.IsNonWhitespace() { p.truncated = true // Done return false } return true } iter.PeekWalk(f) p.source.posSummaryEnd = it.Pos p.source.posBodyStart = posBody p.source.hasSummaryDivider = true if meta.markup != "html" { // The content will be rendered by Blackfriday or similar, // and we need to track the summary. rn.AddReplacement(internalSummaryDividerPre, it) } // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, iter) if err != nil { return fail(errors.Wrap(err, "failed to extract shortcode"), it) } currShortcode.pos = it.Pos currShortcode.length = iter.Current().Pos - it.Pos if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", currShortcode.ordinal) } if currShortcode.name != "" { s.nameSet[currShortcode.name] = true } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", ordinal) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) rn.AddShortcode(currShortcode) case it.Type == pageparser.TypeEmoji: if emoji := helpers.Emoji(it.ValStr()); emoji != nil { rn.AddReplacement(emoji, it) } else { rn.AddBytes(it) } case it.IsEOF(): break Loop case it.IsError(): err := fail(errors.WithStack(errors.New(it.ValStr())), it) currShortcode.err = err return err default: rn.AddBytes(it) } } if !frontMatterSet { // Page content without front matter. Assign default front matter from // cascades etc. if err := meta.setMetadata(bucket, p, nil); err != nil { return err } } p.cmap = rn return nil } func (p *pageState) errorf(err error, format string, a ...interface{}) error { if herrors.UnwrapErrorWithFileContext(err) != nil { // More isn't always better. return err } args := append([]interface{}{p.Language().Lang, p.pathOrTitle()}, a...) format = "[%s] page %q: " + format if err == nil { errors.Errorf(format, args...) return fmt.Errorf(format, args...) } return errors.Wrapf(err, format, args...) } func (p *pageState) outputFormat() (f output.Format) { if p.pageOutput == nil { panic("no pageOutput") } return p.pageOutput.f } func (p *pageState) parseError(err error, input []byte, offset int) error { if herrors.UnwrapFileError(err) != nil { // Use the most specific location. return err } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) } func (p *pageState) pathOrTitle() string { if !p.File().IsZero() { return p.File().Filename() } if p.Pathc() != "" { return p.Pathc() } return p.Title() } func (p *pageState) posFromPage(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } func (p *pageState) posFromInput(input []byte, offset int) text.Position { lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: p.pathOrTitle(), LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } func (p *pageState) posOffset(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := p.initPage(); err != nil { return err } if len(p.pageOutputs) == 1 { idx = 0 } p.pageOutput = p.pageOutputs[idx] if p.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && p.pageOutput.paginator != nil && p.pageOutput.paginator.current != nil { p.pageOutput.paginator.reset() } if isRenderingSite { cp := p.pageOutput.cp if cp == nil { // Look for content to reuse. for i := 0; i < len(p.pageOutputs); i++ { if i == idx { continue } po := p.pageOutputs[i] if po.cp != nil && po.cp.reuse { cp = po.cp break } } } if cp == nil { var err error cp, err = newPageContentOutput(p, p.pageOutput) if err != nil { return err } } p.pageOutput.initContentProvider(cp) } else { // We attempt to assign pageContentOutputs while preparing each site // for rendering and before rendering each site. This lets us share // content between page outputs to conserve resources. But if a template // unexpectedly calls a method of a ContentProvider that is not yet // initialized, we assign a LazyContentProvider that performs the // initialization just in time. if lcp, ok := (p.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok { lcp.Reset() } else { lcp = page.NewLazyContentProvider(func() (page.OutputFormatContentProvider, error) { cp, err := newPageContentOutput(p, p.pageOutput) if err != nil { return nil, err } return cp, nil }) p.pageOutput.ContentProvider = lcp p.pageOutput.TableOfContentsProvider = lcp p.pageOutput.PageRenderProvider = lcp } } return nil } // sourceRef returns the reference used by GetPage and ref/relref shortcodes to refer to // this page. It is prefixed with a "/". // // For pages that have a source file, it is returns the path to this file as an // absolute path rooted in this site's content dir. // For pages that do not (sections without content page etc.), it returns the // virtual path, consistent with where you would add a source file. func (p *pageState) sourceRef() string { if !p.File().IsZero() { sourcePath := p.File().Path() if sourcePath != "" { return "/" + filepath.ToSlash(sourcePath) } } if len(p.SectionsEntries()) > 0 { // no backing file, return the virtual source path return "/" + p.SectionsPath() } return "" } func (s *Site) sectionsFromFile(fi source.File) []string { dirname := fi.Dir() dirname = strings.Trim(dirname, helpers.FilePathSeparator) if dirname == "" { return nil } parts := strings.Split(dirname, helpers.FilePathSeparator) if fii, ok := fi.(*fileInfo); ok { if len(parts) > 0 && fii.FileInfo().Meta().Classifier == files.ContentClassLeaf { // my-section/mybundle/index.md => my-section return parts[:len(parts)-1] } } return parts } var ( _ page.Page = (*pageWithOrdinal)(nil) _ collections.Order = (*pageWithOrdinal)(nil) _ pageWrapper = (*pageWithOrdinal)(nil) ) type pageWithOrdinal struct { ordinal int *pageState } func (p pageWithOrdinal) Ordinal() int { return p.ordinal } func (p pageWithOrdinal) page() page.Page { return p.pageState }
ptgott
85d31f7bfb7a13c9ab7655829a315a820dc1b403
f22c4aba047e89130bf9921c5ded3823743a9ffa
1. We render pages in parallel. 2. Given the below, `AllTranslations` may be called from multiple go routines on the same page. 3. Any of the code lines reading or writing mutable page state below will be a potential data race (e.g. `if tp.pageOutput.cp == nil` and `tp.initContentProvider(cp)`). Go's race detector will fail the tests when run with `go test -race` (which we do on the CI server), but I guess you need to have test cases that trigger it. ```go func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() // Hugo attempts to reuse content providers while preparing each page for // rendering. This approach means that sometimes, content providers for // translations are not initialized. If needed, initialize them here. for _, tr := range p.allTranslations { tp, ok := tr.(*pageState) if !ok { continue } if tp.pageOutput.cp == nil { cp, err := newPageContentOutput(tp, tp.pageOutput) if err != nil { // This will be caught by texttemplate.safeCall panic(fmt.Errorf("error rendering page translation: %w", err)) } tp.initContentProvider(cp) } } return p.allTranslations } ```
bep
124
gohugoio/hugo
9,398
Ensure page translation CPs are initialized
PR #9342 introduced a regression in which calling .Translations in a template and calling RenderString on a translated Page caused a nil pointer dereference. The issue was that some Pages returned from .Translations had a nil cp field at the time the calling template was being executed. While PR #9342 had attempted to ensure that all ContentProviders were initialized for translations at build time, it only performed the initialization for receivers of ContentProvider methods such as .Summary. However, the ContentProvider's *pageState.pageOutput.cp would remain uninitialized, causing the nil pointer dereference. This change edits the .Translations and .AllTranslations methods to ensure that all of a page's translations have an initialized content provider in time for a template to be executed. Since LazyContentProvider is no longer needed with this approach, this change also reverts the following commits: - cdcd15b6c2abbb76fd95fbbf90365c56e82f46aa - 25d645f47ae0a32470d303c9478c9e0b2fff0f0e Fixes #9383
null
2022-01-16 21:11:13+00:00
2022-01-27 10:51:13+00:00
hugolib/page.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 hugolib import ( "bytes" "fmt" "html/template" "os" "path" "path/filepath" "sort" "strings" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/hugofs/files" "github.com/bep/gitmap" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/pkg/errors" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, ContentProvider: page.NopPage, TableOfContentsProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter addDependency(dep identity.Provider) } // wrapErr adds some context to the given error if possible. func wrapErr(err error, ctx interface{}) error { if pc, ok := ctx.(pageContext); ok { return pc.wrapError(err) } return err } type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPageWithTemplateInfo(info tpl.Info, ref string) (page.Page, error) { p, err := pa.GetPage(ref) if p != nil { // Track pages referenced by templates/shortcodes // when in server mode. if im, ok := info.(identity.Manager); ok { im.Add(p) } } return p, err } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPageNew(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // This will be shifted out when we start to render a new output format. *pageOutput // Common for all output formats. *pageCommon } func (p *pageState) Err() error { return nil } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (p *pageState) Eq(other interface{}) bool { pp, err := unwrapPage(other) if err != nil { return false } return p == pp } func (p *pageState) GetIdentity() identity.Identity { return identity.NewPathIdentity(files.ComponentFolderContent, filepath.FromSlash(p.Pathc())) } func (p *pageState) GitInfo() *gitmap.GitInfo { return p.gitInfo } // GetTerms gets the terms defined on this page in the given taxonomy. // The pages returned will be ordered according to the front matter. func (p *pageState) GetTerms(taxonomy string) page.Pages { if p.treeRef == nil { return nil } m := p.s.pageMap taxonomy = strings.ToLower(taxonomy) prefix := cleanSectionTreeKey(taxonomy) self := strings.TrimPrefix(p.treeRef.key, "/") var pas page.Pages m.taxonomies.WalkQuery(pageMapQuery{Prefix: prefix}, func(s string, n *contentNode) bool { key := s + self if tn, found := m.taxonomyEntries.Get(key); found { vi := tn.(*contentNode).viewInfo pas = append(pas, pageWithOrdinal{pageState: n.p, ordinal: vi.ordinal}) } return false }) page.SortByDefault(pas) return pas } func (p *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(p) } func (p *pageState) getPages() page.Pages { b := p.bucket if b == nil { return nil } return b.getPages() } func (p *pageState) getPagesRecursive() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesRecursive() } func (p *pageState) getPagesAndSections() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesAndSections() } func (p *pageState) RegularPagesRecursive() page.Pages { p.regularPagesRecursiveInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindSection: pages = p.getPagesRecursive() default: pages = p.RegularPages() } p.regularPagesRecursive = pages }) return p.regularPagesRecursive } func (p *pageState) PagesRecursive() page.Pages { return nil } func (p *pageState) RegularPages() page.Pages { p.regularPagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome, page.KindTaxonomy: pages = p.getPages() case page.KindTerm: all := p.Pages() for _, p := range all { if p.IsPage() { pages = append(pages, p) } } default: pages = p.s.RegularPages() } p.regularPages = pages }) return p.regularPages } func (p *pageState) Pages() page.Pages { p.pagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome: pages = p.getPagesAndSections() case page.KindTerm: pages = p.bucket.getTaxonomyEntries() case page.KindTaxonomy: pages = p.bucket.getTaxonomies() default: pages = p.s.Pages() } p.pages = pages }) return p.pages } // RawContent returns the un-rendered source content without // any leading front matter. func (p *pageState) RawContent() string { if p.source.parsed == nil { return "" } start := p.source.posMainContent if start == -1 { start = 0 } return string(p.source.parsed.Input()[start:]) } func (p *pageState) sortResources() { sort.SliceStable(p.resources, func(i, j int) bool { ri, rj := p.resources[i], p.resources[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() }) } func (p *pageState) Resources() resource.Resources { p.resourcesInit.Do(func() { p.sortResources() if len(p.m.resourcesMetadata) > 0 { resources.AssignMetadata(p.m.resourcesMetadata, p.resources...) p.sortResources() } }) return p.resources } func (p *pageState) HasShortcode(name string) bool { if p.shortcodeState == nil { return false } return p.shortcodeState.nameSet[name] } func (p *pageState) Site() page.Site { return p.s.Info } func (p *pageState) String() string { if sourceRef := p.sourceRef(); sourceRef != "" { return fmt.Sprintf("Page(%s)", sourceRef) } return fmt.Sprintf("Page(%q)", p.Title()) } // IsTranslated returns whether this content file is translated to // other language(s). func (p *pageState) IsTranslated() bool { p.s.h.init.translations.Do() return len(p.translations) > 0 } // TranslationKey returns the key used to map language translations of this page. // It will use the translationKey set in front matter if set, or the content path and // filename (excluding any language code and extension), e.g. "about/index". // The Page Kind is always prepended. func (p *pageState) TranslationKey() string { p.translationKeyInit.Do(func() { if p.m.translationKey != "" { p.translationKey = p.Kind() + "/" + p.m.translationKey } else if p.IsPage() && !p.File().IsZero() { p.translationKey = path.Join(p.Kind(), filepath.ToSlash(p.File().Dir()), p.File().TranslationBaseName()) } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } }) return p.translationKey } // AllTranslations returns all translations, including the current Page. func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() return p.allTranslations } // Translations returns the translations excluding the current Page. func (p *pageState) Translations() page.Pages { p.s.h.init.translations.Do() return p.translations } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s.Info return nil } func (p *pageState) createRenderHooks(f output.Format) (hooks.Renderers, error) { layoutDescriptor := p.getLayoutDescriptor() layoutDescriptor.RenderingHook = true layoutDescriptor.LayoutOverride = false layoutDescriptor.Layout = "" var renderers hooks.Renderers layoutDescriptor.Kind = "render-link" templ, templFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.LinkRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-image" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.ImageRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-heading" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.HeadingRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } return renderers, nil } func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { p.layoutDescriptorInit.Do(func() { var section string sections := p.SectionsEntries() switch p.Kind() { case page.KindSection: if len(sections) > 0 { section = sections[0] } case page.KindTaxonomy, page.KindTerm: b := p.getTreeRef().n section = b.viewInfo.name.singular default: } p.layoutDescriptor = output.LayoutDescriptor{ Kind: p.Kind(), Type: p.Type(), Lang: p.Language().Lang, Layout: p.Layout(), Section: section, } }) return p.layoutDescriptor } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { f := p.outputFormat() if len(layouts) == 0 { selfLayout := p.selfLayoutForOutput(f) if selfLayout != "" { templ, found := p.s.Tmpl().Lookup(selfLayout) return templ, found, nil } } d := p.getLayoutDescriptor() if len(layouts) > 0 { d.Layout = layouts[0] d.LayoutOverride = true } return p.s.Tmpl().LookupLayout(d, f) } // This is serialized func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { if err := p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } // Must be run after the site section tree etc. is built and ready. func (p *pageState) initPage() error { if _, err := p.init.Do(); err != nil { return err } return nil } func (p *pageState) renderResources() (err error) { p.resourcesPublishInit.Do(func() { var toBeDeleted []int for i, r := range p.Resources() { if _, ok := r.(page.Page); ok { // Pages gets rendered with the owning page but we count them here. p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Pages) continue } src, ok := r.(resource.Source) if !ok { err = errors.Errorf("Resource %T does not support resource.Source", src) return } if err := src.Publish(); err != nil { if os.IsNotExist(err) { // The resource has been deleted from the file system. // This should be extremely rare, but can happen on live reload in server // mode when the same resource is member of different page bundles. toBeDeleted = append(toBeDeleted, i) } else { p.s.Log.Errorf("Failed to publish Resource for page %q: %s", p.pathOrTitle(), err) } } else { p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Files) } } for _, i := range toBeDeleted { p.deleteResource(i) } }) return } func (p *pageState) deleteResource(i int) { p.resources = append(p.resources[:i], p.resources[i+1:]...) } func (p *pageState) getTargetPaths() page.TargetPaths { return p.targetPaths() } func (p *pageState) setTranslations(pages page.Pages) { p.allTranslations = pages page.SortByLanguage(p.allTranslations) translations := make(page.Pages, 0) for _, t := range p.allTranslations { if !t.Eq(p) { translations = append(translations, t) } } p.translations = translations } func (p *pageState) AlternativeOutputFormats() page.OutputFormats { f := p.outputFormat() var o page.OutputFormats for _, of := range p.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defaultRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (p *pageState) RenderString(args ...interface{}) (template.HTML, error) { if len(args) < 1 || len(args) > 2 { return "", errors.New("want 1 or 2 arguments") } var s string opts := defaultRenderStringOpts sidx := 1 if len(args) == 1 { sidx = 0 } else { m, ok := args[0].(map[string]interface{}) if !ok { return "", errors.New("first argument must be a map") } if err := mapstructure.WeakDecode(m, &opts); err != nil { return "", errors.WithMessage(err, "failed to decode options") } } var err error s, err = cast.ToStringE(args[sidx]) if err != nil { return "", err } if err = p.pageOutput.initRenderHooks(); err != nil { return "", err } conv := p.getContentConverter() if opts.Markup != "" && opts.Markup != p.m.markup { var err error // TODO(bep) consider cache conv, err = p.m.newContentConverter(p, opts.Markup, nil) if err != nil { return "", p.wrapError(err) } } var cp *pageContentOutput // If the current content provider is not yet initialized, do so now. if lcp, ok := p.pageOutput.ContentProvider.(*page.LazyContentProvider); ok { c := lcp.Init() if pco, ok := c.(*pageContentOutput); ok { cp = pco } } else { cp = p.pageOutput.cp } c, err := cp.renderContentWithConverter(conv, []byte(s), false) if err != nil { return "", p.wrapError(err) } b := c.Bytes() if opts.Display == "inline" { // We may have to rethink this in the future when we get other // renderers. b = p.s.ContentSpec.TrimShortHTML(b) } return template.HTML(string(b)), nil } func (p *pageState) addDependency(dep identity.Provider) { if !p.s.running() || p.pageOutput.cp == nil { return } p.pageOutput.cp.dependencyTracker.Add(dep) } func (p *pageState) RenderWithTemplateInfo(info tpl.Info, layout ...string) (template.HTML, error) { p.addDependency(info) return p.Render(layout...) } func (p *pageState) Render(layout ...string) (template.HTML, error) { templ, found, err := p.resolveTemplate(layout...) if err != nil { return "", p.wrapError(err) } if !found { return "", nil } p.addDependency(templ.(tpl.Info)) res, err := executeToString(p.s.Tmpl(), templ, p) if err != nil { return "", p.wrapError(errors.Wrapf(err, "failed to execute template %q v", layout)) } return template.HTML(res), nil } // wrapError adds some more context to the given error if possible/needed func (p *pageState) wrapError(err error) error { if _, ok := err.(*herrors.ErrorWithFileContext); ok { // Preserve the first file context. return err } var filename string if !p.File().IsZero() { filename = p.File().Filename() } err, _ = herrors.WithFileContextForFile( err, filename, filename, p.s.SourceSpec.Fs.Source, herrors.SimpleLineMatcher) return err } func (p *pageState) getContentConverter() converter.Converter { var err error p.m.contentConverterInit.Do(func() { markup := p.m.markup if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) }) if err != nil { p.s.Log.Errorln("Failed to create content converter:", err) } return p.m.contentConverter } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { s := p.shortcodeState rn := &pageContentMap{ items: make([]interface{}, 0, 20), } iter := p.source.parsed.Iterator() fail := func(err error, i pageparser.Item) error { return p.parseError(err, iter.Input(), i.Pos) } // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var currShortcode shortcode var ordinal int var frontMatterSet bool Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): f := pageparser.FormatFromFrontMatterType(it.Type) m, err := metadecoders.Default.UnmarshalToMap(it.Val, f) if err != nil { if fe, ok := err.(herrors.FileError); ok { return herrors.ToFileErrorWithOffset(fe, iter.LineNumber()-1) } else { return err } } if err := meta.setMetadata(bucket, p, m); err != nil { return err } frontMatterSet = true next := iter.Peek() if !next.IsDone() { p.source.posMainContent = next.Pos } if !p.s.shouldBuild(p) { // Nothing more to do. return nil } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos } if item.IsNonWhitespace() { p.truncated = true // Done return false } return true } iter.PeekWalk(f) p.source.posSummaryEnd = it.Pos p.source.posBodyStart = posBody p.source.hasSummaryDivider = true if meta.markup != "html" { // The content will be rendered by Blackfriday or similar, // and we need to track the summary. rn.AddReplacement(internalSummaryDividerPre, it) } // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, iter) if err != nil { return fail(errors.Wrap(err, "failed to extract shortcode"), it) } currShortcode.pos = it.Pos currShortcode.length = iter.Current().Pos - it.Pos if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", currShortcode.ordinal) } if currShortcode.name != "" { s.nameSet[currShortcode.name] = true } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", ordinal) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) rn.AddShortcode(currShortcode) case it.Type == pageparser.TypeEmoji: if emoji := helpers.Emoji(it.ValStr()); emoji != nil { rn.AddReplacement(emoji, it) } else { rn.AddBytes(it) } case it.IsEOF(): break Loop case it.IsError(): err := fail(errors.WithStack(errors.New(it.ValStr())), it) currShortcode.err = err return err default: rn.AddBytes(it) } } if !frontMatterSet { // Page content without front matter. Assign default front matter from // cascades etc. if err := meta.setMetadata(bucket, p, nil); err != nil { return err } } p.cmap = rn return nil } func (p *pageState) errorf(err error, format string, a ...interface{}) error { if herrors.UnwrapErrorWithFileContext(err) != nil { // More isn't always better. return err } args := append([]interface{}{p.Language().Lang, p.pathOrTitle()}, a...) format = "[%s] page %q: " + format if err == nil { errors.Errorf(format, args...) return fmt.Errorf(format, args...) } return errors.Wrapf(err, format, args...) } func (p *pageState) outputFormat() (f output.Format) { if p.pageOutput == nil { panic("no pageOutput") } return p.pageOutput.f } func (p *pageState) parseError(err error, input []byte, offset int) error { if herrors.UnwrapFileError(err) != nil { // Use the most specific location. return err } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) } func (p *pageState) pathOrTitle() string { if !p.File().IsZero() { return p.File().Filename() } if p.Pathc() != "" { return p.Pathc() } return p.Title() } func (p *pageState) posFromPage(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } func (p *pageState) posFromInput(input []byte, offset int) text.Position { lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: p.pathOrTitle(), LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } func (p *pageState) posOffset(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := p.initPage(); err != nil { return err } if len(p.pageOutputs) == 1 { idx = 0 } p.pageOutput = p.pageOutputs[idx] if p.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && p.pageOutput.paginator != nil && p.pageOutput.paginator.current != nil { p.pageOutput.paginator.reset() } if isRenderingSite { cp := p.pageOutput.cp if cp == nil { // Look for content to reuse. for i := 0; i < len(p.pageOutputs); i++ { if i == idx { continue } po := p.pageOutputs[i] if po.cp != nil && po.cp.reuse { cp = po.cp break } } } if cp == nil { var err error cp, err = newPageContentOutput(p, p.pageOutput) if err != nil { return err } } p.pageOutput.initContentProvider(cp) } else { // We attempt to assign pageContentOutputs while preparing each site // for rendering and before rendering each site. This lets us share // content between page outputs to conserve resources. But if a template // unexpectedly calls a method of a ContentProvider that is not yet // initialized, we assign a LazyContentProvider that performs the // initialization just in time. if lcp, ok := (p.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok { lcp.Reset() } else { p.pageOutput.ContentProvider = page.NewLazyContentProvider(func() (page.ContentProvider, error) { cp, err := newPageContentOutput(p, p.pageOutput) if err != nil { return nil, err } return cp, nil }) } } return nil } // sourceRef returns the reference used by GetPage and ref/relref shortcodes to refer to // this page. It is prefixed with a "/". // // For pages that have a source file, it is returns the path to this file as an // absolute path rooted in this site's content dir. // For pages that do not (sections without content page etc.), it returns the // virtual path, consistent with where you would add a source file. func (p *pageState) sourceRef() string { if !p.File().IsZero() { sourcePath := p.File().Path() if sourcePath != "" { return "/" + filepath.ToSlash(sourcePath) } } if len(p.SectionsEntries()) > 0 { // no backing file, return the virtual source path return "/" + p.SectionsPath() } return "" } func (s *Site) sectionsFromFile(fi source.File) []string { dirname := fi.Dir() dirname = strings.Trim(dirname, helpers.FilePathSeparator) if dirname == "" { return nil } parts := strings.Split(dirname, helpers.FilePathSeparator) if fii, ok := fi.(*fileInfo); ok { if len(parts) > 0 && fii.FileInfo().Meta().Classifier == files.ContentClassLeaf { // my-section/mybundle/index.md => my-section return parts[:len(parts)-1] } } return parts } var ( _ page.Page = (*pageWithOrdinal)(nil) _ collections.Order = (*pageWithOrdinal)(nil) _ pageWrapper = (*pageWithOrdinal)(nil) ) type pageWithOrdinal struct { ordinal int *pageState } func (p pageWithOrdinal) Ordinal() int { return p.ordinal } func (p pageWithOrdinal) page() page.Page { return p.pageState }
// 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 hugolib import ( "bytes" "fmt" "os" "path" "path/filepath" "sort" "strings" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/hugofs/files" "github.com/bep/gitmap" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/pkg/errors" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, ContentProvider: page.NopPage, TableOfContentsProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter addDependency(dep identity.Provider) } // wrapErr adds some context to the given error if possible. func wrapErr(err error, ctx interface{}) error { if pc, ok := ctx.(pageContext); ok { return pc.wrapError(err) } return err } type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPageWithTemplateInfo(info tpl.Info, ref string) (page.Page, error) { p, err := pa.GetPage(ref) if p != nil { // Track pages referenced by templates/shortcodes // when in server mode. if im, ok := info.(identity.Manager); ok { im.Add(p) } } return p, err } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPageNew(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // This will be shifted out when we start to render a new output format. *pageOutput // Common for all output formats. *pageCommon } func (p *pageState) Err() error { return nil } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (p *pageState) Eq(other interface{}) bool { pp, err := unwrapPage(other) if err != nil { return false } return p == pp } func (p *pageState) GetIdentity() identity.Identity { return identity.NewPathIdentity(files.ComponentFolderContent, filepath.FromSlash(p.Pathc())) } func (p *pageState) GitInfo() *gitmap.GitInfo { return p.gitInfo } // GetTerms gets the terms defined on this page in the given taxonomy. // The pages returned will be ordered according to the front matter. func (p *pageState) GetTerms(taxonomy string) page.Pages { if p.treeRef == nil { return nil } m := p.s.pageMap taxonomy = strings.ToLower(taxonomy) prefix := cleanSectionTreeKey(taxonomy) self := strings.TrimPrefix(p.treeRef.key, "/") var pas page.Pages m.taxonomies.WalkQuery(pageMapQuery{Prefix: prefix}, func(s string, n *contentNode) bool { key := s + self if tn, found := m.taxonomyEntries.Get(key); found { vi := tn.(*contentNode).viewInfo pas = append(pas, pageWithOrdinal{pageState: n.p, ordinal: vi.ordinal}) } return false }) page.SortByDefault(pas) return pas } func (p *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(p) } func (p *pageState) getPages() page.Pages { b := p.bucket if b == nil { return nil } return b.getPages() } func (p *pageState) getPagesRecursive() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesRecursive() } func (p *pageState) getPagesAndSections() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesAndSections() } func (p *pageState) RegularPagesRecursive() page.Pages { p.regularPagesRecursiveInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindSection: pages = p.getPagesRecursive() default: pages = p.RegularPages() } p.regularPagesRecursive = pages }) return p.regularPagesRecursive } func (p *pageState) PagesRecursive() page.Pages { return nil } func (p *pageState) RegularPages() page.Pages { p.regularPagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome, page.KindTaxonomy: pages = p.getPages() case page.KindTerm: all := p.Pages() for _, p := range all { if p.IsPage() { pages = append(pages, p) } } default: pages = p.s.RegularPages() } p.regularPages = pages }) return p.regularPages } func (p *pageState) Pages() page.Pages { p.pagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome: pages = p.getPagesAndSections() case page.KindTerm: pages = p.bucket.getTaxonomyEntries() case page.KindTaxonomy: pages = p.bucket.getTaxonomies() default: pages = p.s.Pages() } p.pages = pages }) return p.pages } // RawContent returns the un-rendered source content without // any leading front matter. func (p *pageState) RawContent() string { if p.source.parsed == nil { return "" } start := p.source.posMainContent if start == -1 { start = 0 } return string(p.source.parsed.Input()[start:]) } func (p *pageState) sortResources() { sort.SliceStable(p.resources, func(i, j int) bool { ri, rj := p.resources[i], p.resources[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() }) } func (p *pageState) Resources() resource.Resources { p.resourcesInit.Do(func() { p.sortResources() if len(p.m.resourcesMetadata) > 0 { resources.AssignMetadata(p.m.resourcesMetadata, p.resources...) p.sortResources() } }) return p.resources } func (p *pageState) HasShortcode(name string) bool { if p.shortcodeState == nil { return false } return p.shortcodeState.nameSet[name] } func (p *pageState) Site() page.Site { return p.s.Info } func (p *pageState) String() string { if sourceRef := p.sourceRef(); sourceRef != "" { return fmt.Sprintf("Page(%s)", sourceRef) } return fmt.Sprintf("Page(%q)", p.Title()) } // IsTranslated returns whether this content file is translated to // other language(s). func (p *pageState) IsTranslated() bool { p.s.h.init.translations.Do() return len(p.translations) > 0 } // TranslationKey returns the key used to map language translations of this page. // It will use the translationKey set in front matter if set, or the content path and // filename (excluding any language code and extension), e.g. "about/index". // The Page Kind is always prepended. func (p *pageState) TranslationKey() string { p.translationKeyInit.Do(func() { if p.m.translationKey != "" { p.translationKey = p.Kind() + "/" + p.m.translationKey } else if p.IsPage() && !p.File().IsZero() { p.translationKey = path.Join(p.Kind(), filepath.ToSlash(p.File().Dir()), p.File().TranslationBaseName()) } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } }) return p.translationKey } // AllTranslations returns all translations, including the current Page. func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() return p.allTranslations } // Translations returns the translations excluding the current Page. func (p *pageState) Translations() page.Pages { p.s.h.init.translations.Do() return p.translations } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s.Info return nil } func (p *pageState) createRenderHooks(f output.Format) (hooks.Renderers, error) { layoutDescriptor := p.getLayoutDescriptor() layoutDescriptor.RenderingHook = true layoutDescriptor.LayoutOverride = false layoutDescriptor.Layout = "" var renderers hooks.Renderers layoutDescriptor.Kind = "render-link" templ, templFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.LinkRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-image" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.ImageRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } layoutDescriptor.Kind = "render-heading" templ, templFound, err = p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return renderers, err } if templFound { renderers.HeadingRenderer = hookRenderer{ templateHandler: p.s.Tmpl(), SearchProvider: templ.(identity.SearchProvider), templ: templ, } } return renderers, nil } func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { p.layoutDescriptorInit.Do(func() { var section string sections := p.SectionsEntries() switch p.Kind() { case page.KindSection: if len(sections) > 0 { section = sections[0] } case page.KindTaxonomy, page.KindTerm: b := p.getTreeRef().n section = b.viewInfo.name.singular default: } p.layoutDescriptor = output.LayoutDescriptor{ Kind: p.Kind(), Type: p.Type(), Lang: p.Language().Lang, Layout: p.Layout(), Section: section, } }) return p.layoutDescriptor } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { f := p.outputFormat() if len(layouts) == 0 { selfLayout := p.selfLayoutForOutput(f) if selfLayout != "" { templ, found := p.s.Tmpl().Lookup(selfLayout) return templ, found, nil } } d := p.getLayoutDescriptor() if len(layouts) > 0 { d.Layout = layouts[0] d.LayoutOverride = true } return p.s.Tmpl().LookupLayout(d, f) } // This is serialized func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { if err := p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } // Must be run after the site section tree etc. is built and ready. func (p *pageState) initPage() error { if _, err := p.init.Do(); err != nil { return err } return nil } func (p *pageState) renderResources() (err error) { p.resourcesPublishInit.Do(func() { var toBeDeleted []int for i, r := range p.Resources() { if _, ok := r.(page.Page); ok { // Pages gets rendered with the owning page but we count them here. p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Pages) continue } src, ok := r.(resource.Source) if !ok { err = errors.Errorf("Resource %T does not support resource.Source", src) return } if err := src.Publish(); err != nil { if os.IsNotExist(err) { // The resource has been deleted from the file system. // This should be extremely rare, but can happen on live reload in server // mode when the same resource is member of different page bundles. toBeDeleted = append(toBeDeleted, i) } else { p.s.Log.Errorf("Failed to publish Resource for page %q: %s", p.pathOrTitle(), err) } } else { p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Files) } } for _, i := range toBeDeleted { p.deleteResource(i) } }) return } func (p *pageState) deleteResource(i int) { p.resources = append(p.resources[:i], p.resources[i+1:]...) } func (p *pageState) getTargetPaths() page.TargetPaths { return p.targetPaths() } func (p *pageState) setTranslations(pages page.Pages) { p.allTranslations = pages page.SortByLanguage(p.allTranslations) translations := make(page.Pages, 0) for _, t := range p.allTranslations { if !t.Eq(p) { translations = append(translations, t) } } p.translations = translations } func (p *pageState) AlternativeOutputFormats() page.OutputFormats { f := p.outputFormat() var o page.OutputFormats for _, of := range p.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defaultRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (p *pageState) addDependency(dep identity.Provider) { if !p.s.running() || p.pageOutput.cp == nil { return } p.pageOutput.cp.dependencyTracker.Add(dep) } // wrapError adds some more context to the given error if possible/needed func (p *pageState) wrapError(err error) error { if _, ok := err.(*herrors.ErrorWithFileContext); ok { // Preserve the first file context. return err } var filename string if !p.File().IsZero() { filename = p.File().Filename() } err, _ = herrors.WithFileContextForFile( err, filename, filename, p.s.SourceSpec.Fs.Source, herrors.SimpleLineMatcher) return err } func (p *pageState) getContentConverter() converter.Converter { var err error p.m.contentConverterInit.Do(func() { markup := p.m.markup if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) }) if err != nil { p.s.Log.Errorln("Failed to create content converter:", err) } return p.m.contentConverter } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { s := p.shortcodeState rn := &pageContentMap{ items: make([]interface{}, 0, 20), } iter := p.source.parsed.Iterator() fail := func(err error, i pageparser.Item) error { return p.parseError(err, iter.Input(), i.Pos) } // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var currShortcode shortcode var ordinal int var frontMatterSet bool Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): f := pageparser.FormatFromFrontMatterType(it.Type) m, err := metadecoders.Default.UnmarshalToMap(it.Val, f) if err != nil { if fe, ok := err.(herrors.FileError); ok { return herrors.ToFileErrorWithOffset(fe, iter.LineNumber()-1) } else { return err } } if err := meta.setMetadata(bucket, p, m); err != nil { return err } frontMatterSet = true next := iter.Peek() if !next.IsDone() { p.source.posMainContent = next.Pos } if !p.s.shouldBuild(p) { // Nothing more to do. return nil } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos } if item.IsNonWhitespace() { p.truncated = true // Done return false } return true } iter.PeekWalk(f) p.source.posSummaryEnd = it.Pos p.source.posBodyStart = posBody p.source.hasSummaryDivider = true if meta.markup != "html" { // The content will be rendered by Blackfriday or similar, // and we need to track the summary. rn.AddReplacement(internalSummaryDividerPre, it) } // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, iter) if err != nil { return fail(errors.Wrap(err, "failed to extract shortcode"), it) } currShortcode.pos = it.Pos currShortcode.length = iter.Current().Pos - it.Pos if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", currShortcode.ordinal) } if currShortcode.name != "" { s.nameSet[currShortcode.name] = true } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", ordinal) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) rn.AddShortcode(currShortcode) case it.Type == pageparser.TypeEmoji: if emoji := helpers.Emoji(it.ValStr()); emoji != nil { rn.AddReplacement(emoji, it) } else { rn.AddBytes(it) } case it.IsEOF(): break Loop case it.IsError(): err := fail(errors.WithStack(errors.New(it.ValStr())), it) currShortcode.err = err return err default: rn.AddBytes(it) } } if !frontMatterSet { // Page content without front matter. Assign default front matter from // cascades etc. if err := meta.setMetadata(bucket, p, nil); err != nil { return err } } p.cmap = rn return nil } func (p *pageState) errorf(err error, format string, a ...interface{}) error { if herrors.UnwrapErrorWithFileContext(err) != nil { // More isn't always better. return err } args := append([]interface{}{p.Language().Lang, p.pathOrTitle()}, a...) format = "[%s] page %q: " + format if err == nil { errors.Errorf(format, args...) return fmt.Errorf(format, args...) } return errors.Wrapf(err, format, args...) } func (p *pageState) outputFormat() (f output.Format) { if p.pageOutput == nil { panic("no pageOutput") } return p.pageOutput.f } func (p *pageState) parseError(err error, input []byte, offset int) error { if herrors.UnwrapFileError(err) != nil { // Use the most specific location. return err } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) } func (p *pageState) pathOrTitle() string { if !p.File().IsZero() { return p.File().Filename() } if p.Pathc() != "" { return p.Pathc() } return p.Title() } func (p *pageState) posFromPage(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } func (p *pageState) posFromInput(input []byte, offset int) text.Position { lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: p.pathOrTitle(), LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } func (p *pageState) posOffset(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := p.initPage(); err != nil { return err } if len(p.pageOutputs) == 1 { idx = 0 } p.pageOutput = p.pageOutputs[idx] if p.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && p.pageOutput.paginator != nil && p.pageOutput.paginator.current != nil { p.pageOutput.paginator.reset() } if isRenderingSite { cp := p.pageOutput.cp if cp == nil { // Look for content to reuse. for i := 0; i < len(p.pageOutputs); i++ { if i == idx { continue } po := p.pageOutputs[i] if po.cp != nil && po.cp.reuse { cp = po.cp break } } } if cp == nil { var err error cp, err = newPageContentOutput(p, p.pageOutput) if err != nil { return err } } p.pageOutput.initContentProvider(cp) } else { // We attempt to assign pageContentOutputs while preparing each site // for rendering and before rendering each site. This lets us share // content between page outputs to conserve resources. But if a template // unexpectedly calls a method of a ContentProvider that is not yet // initialized, we assign a LazyContentProvider that performs the // initialization just in time. if lcp, ok := (p.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok { lcp.Reset() } else { lcp = page.NewLazyContentProvider(func() (page.OutputFormatContentProvider, error) { cp, err := newPageContentOutput(p, p.pageOutput) if err != nil { return nil, err } return cp, nil }) p.pageOutput.ContentProvider = lcp p.pageOutput.TableOfContentsProvider = lcp p.pageOutput.PageRenderProvider = lcp } } return nil } // sourceRef returns the reference used by GetPage and ref/relref shortcodes to refer to // this page. It is prefixed with a "/". // // For pages that have a source file, it is returns the path to this file as an // absolute path rooted in this site's content dir. // For pages that do not (sections without content page etc.), it returns the // virtual path, consistent with where you would add a source file. func (p *pageState) sourceRef() string { if !p.File().IsZero() { sourcePath := p.File().Path() if sourcePath != "" { return "/" + filepath.ToSlash(sourcePath) } } if len(p.SectionsEntries()) > 0 { // no backing file, return the virtual source path return "/" + p.SectionsPath() } return "" } func (s *Site) sectionsFromFile(fi source.File) []string { dirname := fi.Dir() dirname = strings.Trim(dirname, helpers.FilePathSeparator) if dirname == "" { return nil } parts := strings.Split(dirname, helpers.FilePathSeparator) if fii, ok := fi.(*fileInfo); ok { if len(parts) > 0 && fii.FileInfo().Meta().Classifier == files.ContentClassLeaf { // my-section/mybundle/index.md => my-section return parts[:len(parts)-1] } } return parts } var ( _ page.Page = (*pageWithOrdinal)(nil) _ collections.Order = (*pageWithOrdinal)(nil) _ pageWrapper = (*pageWithOrdinal)(nil) ) type pageWithOrdinal struct { ordinal int *pageState } func (p pageWithOrdinal) Ordinal() int { return p.ordinal } func (p pageWithOrdinal) page() page.Page { return p.pageState }
ptgott
85d31f7bfb7a13c9ab7655829a315a820dc1b403
f22c4aba047e89130bf9921c5ded3823743a9ffa
So, this is conceptually what we need, but I would love if we could do this in one place. I think that if we use the same "interface approach" for RenderString (and potentially others) and make LazyContentProvider implement that interface, that should work.
bep
125
gohugoio/hugo
9,382
deps: Update github.com/tdewolff/minify/v2 v2.9.22 => v2.9.29
Fixes #9244 Fixes #9132 Fixes https://discourse.gohugo.io/t/36523
null
2022-01-14 02:27:23+00:00
2022-02-15 16:36:29+00:00
hugolib/resource_chain_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 hugolib import ( "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestResourceChainBasic(t *testing.T) { ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.GetRemote "%[1]s/sunset.jpg" }} {{ $remotenotfound := resources.GetRemote "%[1]s/notfound.jpg" }} {{ $localnotfound := resources.Get "images/notfound.jpg" }} {{ $gopherprotocol := resources.GetRemote "gopher://example.org" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} REMOTE NOT FOUND: {{ if $remotenotfound }}FAILED{{ else}}OK{{ end }} LOCAL NOT FOUND: {{ if $localnotfound }}FAILED{{ else}}OK{{ end }} PRINT PROTOCOL ERROR1: {{ with $gopherprotocol }}{{ . | safeHTML }}{{ end }} PRINT PROTOCOL ERROR2: {{ with $gopherprotocol }}{{ .Err | safeHTML }}{{ end }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 REMOTE NOT FOUND: OK LOCAL NOT FOUND: OK PRINT PROTOCOL ERROR1: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" PRINT PROTOCOL ERROR2: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": w.Header().Set("Content-Type", "text/plain") if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": w.Header().Set("Content-Type", "text/plain") if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.GetRemote "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.GetRemote "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.GetRemote "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.GetRemote "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.GetRemote "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.GetRemote "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.GetRemote "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.GetRemote "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.GetRemote "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.GetRemote "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} {{ $xml := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>You</to><from>Me</from><heading>Reminder</heading><body>Do not forget XML</body></note>" | transform.Unmarshal }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} XML: {{ $xml.body }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, `XML: Do not forget XML`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) }
// 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 hugolib import ( "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestResourceChainBasic(t *testing.T) { ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.GetRemote "%[1]s/sunset.jpg" }} {{ $remotenotfound := resources.GetRemote "%[1]s/notfound.jpg" }} {{ $localnotfound := resources.Get "images/notfound.jpg" }} {{ $gopherprotocol := resources.GetRemote "gopher://example.org" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} REMOTE NOT FOUND: {{ if $remotenotfound }}FAILED{{ else}}OK{{ end }} LOCAL NOT FOUND: {{ if $localnotfound }}FAILED{{ else}}OK{{ end }} PRINT PROTOCOL ERROR1: {{ with $gopherprotocol }}{{ . | safeHTML }}{{ end }} PRINT PROTOCOL ERROR2: {{ with $gopherprotocol }}{{ .Err | safeHTML }}{{ end }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 REMOTE NOT FOUND: OK LOCAL NOT FOUND: OK PRINT PROTOCOL ERROR1: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" PRINT PROTOCOL ERROR2: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": w.Header().Set("Content-Type", "text/plain") if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": w.Header().Set("Content-Type", "text/plain") if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.GetRemote "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.GetRemote "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.GetRemote "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.GetRemote "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.GetRemote "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.GetRemote "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.GetRemote "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.GetRemote "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.GetRemote "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.GetRemote "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} {{ $xml := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>You</to><from>Me</from><heading>Reminder</heading><body>Do not forget XML</body></note>" | transform.Unmarshal }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} XML: {{ $xml.body }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, `XML: Do not forget XML`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) }
jmooring
837fdfdf45014e3d5ef3b00b01548b68a4489c5f
923419d7fde2056f47668acb0981135bce543b7e
Not that there was ever an ambition that these tests should somehow "unit test" the upstream library, I cannot help questioning the behaviour above: Why is is behaving differently when applied to the same JS file when pulled in remotely?
bep
126
gohugoio/hugo
9,382
deps: Update github.com/tdewolff/minify/v2 v2.9.22 => v2.9.29
Fixes #9244 Fixes #9132 Fixes https://discourse.gohugo.io/t/36523
null
2022-01-14 02:27:23+00:00
2022-02-15 16:36:29+00:00
hugolib/resource_chain_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 hugolib import ( "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestResourceChainBasic(t *testing.T) { ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.GetRemote "%[1]s/sunset.jpg" }} {{ $remotenotfound := resources.GetRemote "%[1]s/notfound.jpg" }} {{ $localnotfound := resources.Get "images/notfound.jpg" }} {{ $gopherprotocol := resources.GetRemote "gopher://example.org" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} REMOTE NOT FOUND: {{ if $remotenotfound }}FAILED{{ else}}OK{{ end }} LOCAL NOT FOUND: {{ if $localnotfound }}FAILED{{ else}}OK{{ end }} PRINT PROTOCOL ERROR1: {{ with $gopherprotocol }}{{ . | safeHTML }}{{ end }} PRINT PROTOCOL ERROR2: {{ with $gopherprotocol }}{{ .Err | safeHTML }}{{ end }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 REMOTE NOT FOUND: OK LOCAL NOT FOUND: OK PRINT PROTOCOL ERROR1: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" PRINT PROTOCOL ERROR2: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": w.Header().Set("Content-Type", "text/plain") if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": w.Header().Set("Content-Type", "text/plain") if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.GetRemote "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.GetRemote "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.GetRemote "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.GetRemote "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.GetRemote "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.GetRemote "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.GetRemote "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.GetRemote "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.GetRemote "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.GetRemote "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} {{ $xml := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>You</to><from>Me</from><heading>Reminder</heading><body>Do not forget XML</body></note>" | transform.Unmarshal }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} XML: {{ $xml.body }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, `XML: Do not forget XML`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) }
// 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 hugolib import ( "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestResourceChainBasic(t *testing.T) { ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.GetRemote "%[1]s/sunset.jpg" }} {{ $remotenotfound := resources.GetRemote "%[1]s/notfound.jpg" }} {{ $localnotfound := resources.Get "images/notfound.jpg" }} {{ $gopherprotocol := resources.GetRemote "gopher://example.org" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} REMOTE NOT FOUND: {{ if $remotenotfound }}FAILED{{ else}}OK{{ end }} LOCAL NOT FOUND: {{ if $localnotfound }}FAILED{{ else}}OK{{ end }} PRINT PROTOCOL ERROR1: {{ with $gopherprotocol }}{{ . | safeHTML }}{{ end }} PRINT PROTOCOL ERROR2: {{ with $gopherprotocol }}{{ .Err | safeHTML }}{{ end }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 REMOTE NOT FOUND: OK LOCAL NOT FOUND: OK PRINT PROTOCOL ERROR1: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" PRINT PROTOCOL ERROR2: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": w.Header().Set("Content-Type", "text/plain") if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": w.Header().Set("Content-Type", "text/plain") if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.GetRemote "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.GetRemote "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.GetRemote "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.GetRemote "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.GetRemote "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.GetRemote "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.GetRemote "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.GetRemote "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.GetRemote "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.GetRemote "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} {{ $xml := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>You</to><from>Me</from><heading>Reminder</heading><body>Do not forget XML</body></note>" | transform.Unmarshal }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} XML: {{ $xml.body }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, `XML: Do not forget XML`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) }
jmooring
837fdfdf45014e3d5ef3b00b01548b68a4489c5f
923419d7fde2056f47668acb0981135bce543b7e
> Why is it behaving differently when applied to the same JS file when pulled in remotely? Because it's not the same JS file. The "Min JS" test uses this data: <https://github.com/gohugoio/hugo/blob/master/hugolib/resource_chain_test.go#L942-L944> The "Min JS Remote" test uses this data: <https://github.com/gohugoio/hugo/blob/master/hugolib/resource_chain_test.go#L568>
jmooring
127
gohugoio/hugo
9,382
deps: Update github.com/tdewolff/minify/v2 v2.9.22 => v2.9.29
Fixes #9244 Fixes #9132 Fixes https://discourse.gohugo.io/t/36523
null
2022-01-14 02:27:23+00:00
2022-02-15 16:36:29+00:00
hugolib/resource_chain_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 hugolib import ( "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestResourceChainBasic(t *testing.T) { ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.GetRemote "%[1]s/sunset.jpg" }} {{ $remotenotfound := resources.GetRemote "%[1]s/notfound.jpg" }} {{ $localnotfound := resources.Get "images/notfound.jpg" }} {{ $gopherprotocol := resources.GetRemote "gopher://example.org" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} REMOTE NOT FOUND: {{ if $remotenotfound }}FAILED{{ else}}OK{{ end }} LOCAL NOT FOUND: {{ if $localnotfound }}FAILED{{ else}}OK{{ end }} PRINT PROTOCOL ERROR1: {{ with $gopherprotocol }}{{ . | safeHTML }}{{ end }} PRINT PROTOCOL ERROR2: {{ with $gopherprotocol }}{{ .Err | safeHTML }}{{ end }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 REMOTE NOT FOUND: OK LOCAL NOT FOUND: OK PRINT PROTOCOL ERROR1: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" PRINT PROTOCOL ERROR2: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": w.Header().Set("Content-Type", "text/plain") if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": w.Header().Set("Content-Type", "text/plain") if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.GetRemote "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.GetRemote "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.GetRemote "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.GetRemote "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.GetRemote "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.GetRemote "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.GetRemote "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.GetRemote "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.GetRemote "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.GetRemote "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} {{ $xml := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>You</to><from>Me</from><heading>Reminder</heading><body>Do not forget XML</body></note>" | transform.Unmarshal }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} XML: {{ $xml.body }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, `XML: Do not forget XML`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) }
// 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 hugolib import ( "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestResourceChainBasic(t *testing.T) { ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.GetRemote "%[1]s/sunset.jpg" }} {{ $remotenotfound := resources.GetRemote "%[1]s/notfound.jpg" }} {{ $localnotfound := resources.Get "images/notfound.jpg" }} {{ $gopherprotocol := resources.GetRemote "gopher://example.org" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} REMOTE NOT FOUND: {{ if $remotenotfound }}FAILED{{ else}}OK{{ end }} LOCAL NOT FOUND: {{ if $localnotfound }}FAILED{{ else}}OK{{ end }} PRINT PROTOCOL ERROR1: {{ with $gopherprotocol }}{{ . | safeHTML }}{{ end }} PRINT PROTOCOL ERROR2: {{ with $gopherprotocol }}{{ .Err | safeHTML }}{{ end }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 REMOTE NOT FOUND: OK LOCAL NOT FOUND: OK PRINT PROTOCOL ERROR1: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" PRINT PROTOCOL ERROR2: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": w.Header().Set("Content-Type", "text/plain") if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": w.Header().Set("Content-Type", "text/plain") if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.GetRemote "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.GetRemote "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.GetRemote "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.GetRemote "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.GetRemote "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.GetRemote "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.GetRemote "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.GetRemote "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.GetRemote "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.GetRemote "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} {{ $xml := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>You</to><from>Me</from><heading>Reminder</heading><body>Do not forget XML</body></note>" | transform.Unmarshal }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} XML: {{ $xml.body }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, `XML: Do not forget XML`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) }
jmooring
837fdfdf45014e3d5ef3b00b01548b68a4489c5f
923419d7fde2056f47668acb0981135bce543b7e
I've asked a question about the differences: <https://github.com/tdewolff/minify/issues/455>
jmooring
128
gohugoio/hugo
9,382
deps: Update github.com/tdewolff/minify/v2 v2.9.22 => v2.9.29
Fixes #9244 Fixes #9132 Fixes https://discourse.gohugo.io/t/36523
null
2022-01-14 02:27:23+00:00
2022-02-15 16:36:29+00:00
hugolib/resource_chain_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 hugolib import ( "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestResourceChainBasic(t *testing.T) { ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.GetRemote "%[1]s/sunset.jpg" }} {{ $remotenotfound := resources.GetRemote "%[1]s/notfound.jpg" }} {{ $localnotfound := resources.Get "images/notfound.jpg" }} {{ $gopherprotocol := resources.GetRemote "gopher://example.org" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} REMOTE NOT FOUND: {{ if $remotenotfound }}FAILED{{ else}}OK{{ end }} LOCAL NOT FOUND: {{ if $localnotfound }}FAILED{{ else}}OK{{ end }} PRINT PROTOCOL ERROR1: {{ with $gopherprotocol }}{{ . | safeHTML }}{{ end }} PRINT PROTOCOL ERROR2: {{ with $gopherprotocol }}{{ .Err | safeHTML }}{{ end }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 REMOTE NOT FOUND: OK LOCAL NOT FOUND: OK PRINT PROTOCOL ERROR1: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" PRINT PROTOCOL ERROR2: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": w.Header().Set("Content-Type", "text/plain") if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": w.Header().Set("Content-Type", "text/plain") if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.GetRemote "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.GetRemote "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.GetRemote "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.GetRemote "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.GetRemote "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.GetRemote "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.GetRemote "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.GetRemote "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.GetRemote "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.GetRemote "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} {{ $xml := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>You</to><from>Me</from><heading>Reminder</heading><body>Do not forget XML</body></note>" | transform.Unmarshal }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} XML: {{ $xml.body }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, `XML: Do not forget XML`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) }
// 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 hugolib import ( "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/helpers" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestResourceChainBasic(t *testing.T) { ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.GetRemote "%[1]s/sunset.jpg" }} {{ $remotenotfound := resources.GetRemote "%[1]s/notfound.jpg" }} {{ $localnotfound := resources.Get "images/notfound.jpg" }} {{ $gopherprotocol := resources.GetRemote "gopher://example.org" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} REMOTE NOT FOUND: {{ if $remotenotfound }}FAILED{{ else}}OK{{ end }} LOCAL NOT FOUND: {{ if $localnotfound }}FAILED{{ else}}OK{{ end }} PRINT PROTOCOL ERROR1: {{ with $gopherprotocol }}{{ . | safeHTML }}{{ end }} PRINT PROTOCOL ERROR2: {{ with $gopherprotocol }}{{ .Err | safeHTML }}{{ end }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 REMOTE NOT FOUND: OK LOCAL NOT FOUND: OK PRINT PROTOCOL ERROR1: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" PRINT PROTOCOL ERROR2: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher" `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": w.Header().Set("Content-Type", "text/plain") if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": w.Header().Set("Content-Type", "text/plain") if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.GetRemote "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.GetRemote "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.GetRemote "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.GetRemote "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.GetRemote "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.GetRemote "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.GetRemote "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.GetRemote "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.GetRemote "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.GetRemote "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} {{ $xml := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>You</to><from>Me</from><heading>Reminder</heading><body>Do not forget XML</body></note>" | transform.Unmarshal }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} XML: {{ $xml.body }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, `XML: Do not forget XML`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) }
jmooring
837fdfdf45014e3d5ef3b00b01548b68a4489c5f
923419d7fde2056f47668acb0981135bce543b7e
Differences unexpected, resolved with new release 2.9.29.
jmooring
129
gohugoio/hugo
9,298
Allow for return partials with falsy arguments
Partials with returns values are parsed, then inserted into a partial return wrapper via wrapInPartialReturnWrapper in order to assign the return value via *contextWrapper.Set. The predefined wrapper template for partials inserts a partial's nodes into a "with" template action in order to set dot to a *contextWrapper within the partial. However, because "with" is skipped if its argument is falsy, partials with falsy arguments were not being evaluated. This replaces the "with" action in the partial wrapper with a "range" action that isn't skipped if .Arg is falsy. Fixes #7528
null
2021-12-16 14:41:57+00:00
2021-12-17 07:35:22+00:00
tpl/tplimpl/template_ast_transformers.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 tplimpl import ( "regexp" "strings" htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate" texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/tpl" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" ) type templateType int const ( templateUndefined templateType = iota templateShortcode templatePartial ) type templateContext struct { visited map[string]bool templateNotFound map[string]bool identityNotFound map[string]bool lookupFn func(name string) *templateState // The last error encountered. err error // Set when we're done checking for config header. configChecked bool t *templateState // Store away the return node in partials. returnNode *parse.CommandNode } func (c templateContext) getIfNotVisited(name string) *templateState { if c.visited[name] { return nil } c.visited[name] = true templ := c.lookupFn(name) if templ == nil { // This may be a inline template defined outside of this file // and not yet parsed. Unusual, but it happens. // Store the name to try again later. c.templateNotFound[name] = true } return templ } func newTemplateContext( t *templateState, lookupFn func(name string) *templateState) *templateContext { return &templateContext{ t: t, lookupFn: lookupFn, visited: make(map[string]bool), templateNotFound: make(map[string]bool), identityNotFound: make(map[string]bool), } } func applyTemplateTransformers( t *templateState, lookupFn func(name string) *templateState) (*templateContext, error) { if t == nil { return nil, errors.New("expected template, but none provided") } c := newTemplateContext(t, lookupFn) tree := getParseTree(t.Template) _, err := c.applyTransformations(tree.Root) if err == nil && c.returnNode != nil { // This is a partial with a return statement. c.t.parseInfo.HasReturn = true tree.Root = c.wrapInPartialReturnWrapper(tree.Root) } return c, err } func getParseTree(templ tpl.Template) *parse.Tree { templ = unwrap(templ) if text, ok := templ.(*texttemplate.Template); ok { return text.Tree } return templ.(*htmltemplate.Template).Tree } const ( partialReturnWrapperTempl = `{{ $_hugo_dot := $ }}{{ $ := .Arg }}{{ with .Arg }}{{ $_hugo_dot.Set ("PLACEHOLDER") }}{{ end }}` ) var partialReturnWrapper *parse.ListNode func init() { templ, err := texttemplate.New("").Parse(partialReturnWrapperTempl) if err != nil { panic(err) } partialReturnWrapper = templ.Tree.Root } func (c *templateContext) wrapInPartialReturnWrapper(n *parse.ListNode) *parse.ListNode { wrapper := partialReturnWrapper.CopyList() withNode := wrapper.Nodes[2].(*parse.WithNode) retn := withNode.List.Nodes[0] setCmd := retn.(*parse.ActionNode).Pipe.Cmds[0] setPipe := setCmd.Args[1].(*parse.PipeNode) // Replace PLACEHOLDER with the real return value. // Note that this is a PipeNode, so it will be wrapped in parens. setPipe.Cmds = []*parse.CommandNode{c.returnNode} withNode.List.Nodes = append(n.Nodes, retn) return wrapper } // applyTransformations do 2 things: // 1) Parses partial return statement. // 2) Tracks template (partial) dependencies and some other info. func (c *templateContext) applyTransformations(n parse.Node) (bool, error) { switch x := n.(type) { case *parse.ListNode: if x != nil { c.applyTransformationsToNodes(x.Nodes...) } case *parse.ActionNode: c.applyTransformationsToNodes(x.Pipe) case *parse.IfNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.WithNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.RangeNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.TemplateNode: subTempl := c.getIfNotVisited(x.Name) if subTempl != nil { c.applyTransformationsToNodes(getParseTree(subTempl.Template).Root) } case *parse.PipeNode: c.collectConfig(x) for i, cmd := range x.Cmds { keep, _ := c.applyTransformations(cmd) if !keep { x.Cmds = append(x.Cmds[:i], x.Cmds[i+1:]...) } } case *parse.CommandNode: c.collectPartialInfo(x) c.collectInner(x) keep := c.collectReturnNode(x) for _, elem := range x.Args { switch an := elem.(type) { case *parse.PipeNode: c.applyTransformations(an) } } return keep, c.err } return true, c.err } func (c *templateContext) applyTransformationsToNodes(nodes ...parse.Node) { for _, node := range nodes { c.applyTransformations(node) } } func (c *templateContext) hasIdent(idents []string, ident string) bool { for _, id := range idents { if id == ident { return true } } return false } // collectConfig collects and parses any leading template config variable declaration. // This will be the first PipeNode in the template, and will be a variable declaration // on the form: // {{ $_hugo_config:= `{ "version": 1 }` }} func (c *templateContext) collectConfig(n *parse.PipeNode) { if c.t.typ != templateShortcode { return } if c.configChecked { return } c.configChecked = true if len(n.Decl) != 1 || len(n.Cmds) != 1 { // This cannot be a config declaration return } v := n.Decl[0] if len(v.Ident) == 0 || v.Ident[0] != "$_hugo_config" { return } cmd := n.Cmds[0] if len(cmd.Args) == 0 { return } if s, ok := cmd.Args[0].(*parse.StringNode); ok { errMsg := "failed to decode $_hugo_config in template" m, err := maps.ToStringMapE(s.Text) if err != nil { c.err = errors.Wrap(err, errMsg) return } if err := mapstructure.WeakDecode(m, &c.t.parseInfo.Config); err != nil { c.err = errors.Wrap(err, errMsg) } } } // collectInner determines if the given CommandNode represents a // shortcode call to its .Inner. func (c *templateContext) collectInner(n *parse.CommandNode) { if c.t.typ != templateShortcode { return } if c.t.parseInfo.IsInner || len(n.Args) == 0 { return } for _, arg := range n.Args { var idents []string switch nt := arg.(type) { case *parse.FieldNode: idents = nt.Ident case *parse.VariableNode: idents = nt.Ident } if c.hasIdent(idents, "Inner") { c.t.parseInfo.IsInner = true break } } } var partialRe = regexp.MustCompile(`^partial(Cached)?$|^partials\.Include(Cached)?$`) func (c *templateContext) collectPartialInfo(x *parse.CommandNode) { if len(x.Args) < 2 { return } first := x.Args[0] var id string switch v := first.(type) { case *parse.IdentifierNode: id = v.Ident case *parse.ChainNode: id = v.String() } if partialRe.MatchString(id) { partialName := strings.Trim(x.Args[1].String(), "\"") if !strings.Contains(partialName, ".") { partialName += ".html" } partialName = "partials/" + partialName info := c.lookupFn(partialName) if info != nil { c.t.Add(info) } else { // Delay for later c.identityNotFound[partialName] = true } } } func (c *templateContext) collectReturnNode(n *parse.CommandNode) bool { if c.t.typ != templatePartial || c.returnNode != nil { return true } if len(n.Args) < 2 { return true } ident, ok := n.Args[0].(*parse.IdentifierNode) if !ok || ident.Ident != "return" { return true } c.returnNode = n // Remove the "return" identifiers c.returnNode.Args = c.returnNode.Args[1:] return false } func findTemplateIn(name string, in tpl.Template) (tpl.Template, bool) { in = unwrap(in) if text, ok := in.(*texttemplate.Template); ok { if templ := text.Lookup(name); templ != nil { return templ, true } return nil, false } if templ := in.(*htmltemplate.Template).Lookup(name); templ != nil { return templ, true } return nil, false }
// 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 tplimpl import ( "regexp" "strings" htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate" texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/tpl" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" ) type templateType int const ( templateUndefined templateType = iota templateShortcode templatePartial ) type templateContext struct { visited map[string]bool templateNotFound map[string]bool identityNotFound map[string]bool lookupFn func(name string) *templateState // The last error encountered. err error // Set when we're done checking for config header. configChecked bool t *templateState // Store away the return node in partials. returnNode *parse.CommandNode } func (c templateContext) getIfNotVisited(name string) *templateState { if c.visited[name] { return nil } c.visited[name] = true templ := c.lookupFn(name) if templ == nil { // This may be a inline template defined outside of this file // and not yet parsed. Unusual, but it happens. // Store the name to try again later. c.templateNotFound[name] = true } return templ } func newTemplateContext( t *templateState, lookupFn func(name string) *templateState) *templateContext { return &templateContext{ t: t, lookupFn: lookupFn, visited: make(map[string]bool), templateNotFound: make(map[string]bool), identityNotFound: make(map[string]bool), } } func applyTemplateTransformers( t *templateState, lookupFn func(name string) *templateState) (*templateContext, error) { if t == nil { return nil, errors.New("expected template, but none provided") } c := newTemplateContext(t, lookupFn) tree := getParseTree(t.Template) _, err := c.applyTransformations(tree.Root) if err == nil && c.returnNode != nil { // This is a partial with a return statement. c.t.parseInfo.HasReturn = true tree.Root = c.wrapInPartialReturnWrapper(tree.Root) } return c, err } func getParseTree(templ tpl.Template) *parse.Tree { templ = unwrap(templ) if text, ok := templ.(*texttemplate.Template); ok { return text.Tree } return templ.(*htmltemplate.Template).Tree } const ( // We parse this template and modify the nodes in order to assign // the return value of a partial to a contextWrapper via Set. We use // "range" over a one-element slice so we can shift dot to the // partial's argument, Arg, while allowing Arg to be falsy. partialReturnWrapperTempl = `{{ $_hugo_dot := $ }}{{ $ := .Arg }}{{ range (slice .Arg) }}{{ $_hugo_dot.Set ("PLACEHOLDER") }}{{ end }}` ) var partialReturnWrapper *parse.ListNode func init() { templ, err := texttemplate.New("").Parse(partialReturnWrapperTempl) if err != nil { panic(err) } partialReturnWrapper = templ.Tree.Root } // wrapInPartialReturnWrapper copies and modifies the parsed nodes of a // predefined partial return wrapper to insert those of a user-defined partial. func (c *templateContext) wrapInPartialReturnWrapper(n *parse.ListNode) *parse.ListNode { wrapper := partialReturnWrapper.CopyList() rangeNode := wrapper.Nodes[2].(*parse.RangeNode) retn := rangeNode.List.Nodes[0] setCmd := retn.(*parse.ActionNode).Pipe.Cmds[0] setPipe := setCmd.Args[1].(*parse.PipeNode) // Replace PLACEHOLDER with the real return value. // Note that this is a PipeNode, so it will be wrapped in parens. setPipe.Cmds = []*parse.CommandNode{c.returnNode} rangeNode.List.Nodes = append(n.Nodes, retn) return wrapper } // applyTransformations do 2 things: // 1) Parses partial return statement. // 2) Tracks template (partial) dependencies and some other info. func (c *templateContext) applyTransformations(n parse.Node) (bool, error) { switch x := n.(type) { case *parse.ListNode: if x != nil { c.applyTransformationsToNodes(x.Nodes...) } case *parse.ActionNode: c.applyTransformationsToNodes(x.Pipe) case *parse.IfNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.WithNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.RangeNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.TemplateNode: subTempl := c.getIfNotVisited(x.Name) if subTempl != nil { c.applyTransformationsToNodes(getParseTree(subTempl.Template).Root) } case *parse.PipeNode: c.collectConfig(x) for i, cmd := range x.Cmds { keep, _ := c.applyTransformations(cmd) if !keep { x.Cmds = append(x.Cmds[:i], x.Cmds[i+1:]...) } } case *parse.CommandNode: c.collectPartialInfo(x) c.collectInner(x) keep := c.collectReturnNode(x) for _, elem := range x.Args { switch an := elem.(type) { case *parse.PipeNode: c.applyTransformations(an) } } return keep, c.err } return true, c.err } func (c *templateContext) applyTransformationsToNodes(nodes ...parse.Node) { for _, node := range nodes { c.applyTransformations(node) } } func (c *templateContext) hasIdent(idents []string, ident string) bool { for _, id := range idents { if id == ident { return true } } return false } // collectConfig collects and parses any leading template config variable declaration. // This will be the first PipeNode in the template, and will be a variable declaration // on the form: // {{ $_hugo_config:= `{ "version": 1 }` }} func (c *templateContext) collectConfig(n *parse.PipeNode) { if c.t.typ != templateShortcode { return } if c.configChecked { return } c.configChecked = true if len(n.Decl) != 1 || len(n.Cmds) != 1 { // This cannot be a config declaration return } v := n.Decl[0] if len(v.Ident) == 0 || v.Ident[0] != "$_hugo_config" { return } cmd := n.Cmds[0] if len(cmd.Args) == 0 { return } if s, ok := cmd.Args[0].(*parse.StringNode); ok { errMsg := "failed to decode $_hugo_config in template" m, err := maps.ToStringMapE(s.Text) if err != nil { c.err = errors.Wrap(err, errMsg) return } if err := mapstructure.WeakDecode(m, &c.t.parseInfo.Config); err != nil { c.err = errors.Wrap(err, errMsg) } } } // collectInner determines if the given CommandNode represents a // shortcode call to its .Inner. func (c *templateContext) collectInner(n *parse.CommandNode) { if c.t.typ != templateShortcode { return } if c.t.parseInfo.IsInner || len(n.Args) == 0 { return } for _, arg := range n.Args { var idents []string switch nt := arg.(type) { case *parse.FieldNode: idents = nt.Ident case *parse.VariableNode: idents = nt.Ident } if c.hasIdent(idents, "Inner") { c.t.parseInfo.IsInner = true break } } } var partialRe = regexp.MustCompile(`^partial(Cached)?$|^partials\.Include(Cached)?$`) func (c *templateContext) collectPartialInfo(x *parse.CommandNode) { if len(x.Args) < 2 { return } first := x.Args[0] var id string switch v := first.(type) { case *parse.IdentifierNode: id = v.Ident case *parse.ChainNode: id = v.String() } if partialRe.MatchString(id) { partialName := strings.Trim(x.Args[1].String(), "\"") if !strings.Contains(partialName, ".") { partialName += ".html" } partialName = "partials/" + partialName info := c.lookupFn(partialName) if info != nil { c.t.Add(info) } else { // Delay for later c.identityNotFound[partialName] = true } } } func (c *templateContext) collectReturnNode(n *parse.CommandNode) bool { if c.t.typ != templatePartial || c.returnNode != nil { return true } if len(n.Args) < 2 { return true } ident, ok := n.Args[0].(*parse.IdentifierNode) if !ok || ident.Ident != "return" { return true } c.returnNode = n // Remove the "return" identifiers c.returnNode.Args = c.returnNode.Args[1:] return false } func findTemplateIn(name string, in tpl.Template) (tpl.Template, bool) { in = unwrap(in) if text, ok := in.(*texttemplate.Template); ok { if templ := text.Lookup(name); templ != nil { return templ, true } return nil, false } if templ := in.(*htmltemplate.Template).Lookup(name); templ != nil { return templ, true } return nil, false }
ptgott
8ee6de6d96a64395d27416d4f2ad7d172a2686d0
5758c370eac6c4460cd6bb34d4475c8d347585f6
I suspect it would be easier to understand if you make `contextWrapper.Arg` a `[]interface{}` -- and just add a comment there explaining why it's a slice with a single value.
bep
130
gohugoio/hugo
9,298
Allow for return partials with falsy arguments
Partials with returns values are parsed, then inserted into a partial return wrapper via wrapInPartialReturnWrapper in order to assign the return value via *contextWrapper.Set. The predefined wrapper template for partials inserts a partial's nodes into a "with" template action in order to set dot to a *contextWrapper within the partial. However, because "with" is skipped if its argument is falsy, partials with falsy arguments were not being evaluated. This replaces the "with" action in the partial wrapper with a "range" action that isn't skipped if .Arg is falsy. Fixes #7528
null
2021-12-16 14:41:57+00:00
2021-12-17 07:35:22+00:00
tpl/tplimpl/template_ast_transformers.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 tplimpl import ( "regexp" "strings" htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate" texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/tpl" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" ) type templateType int const ( templateUndefined templateType = iota templateShortcode templatePartial ) type templateContext struct { visited map[string]bool templateNotFound map[string]bool identityNotFound map[string]bool lookupFn func(name string) *templateState // The last error encountered. err error // Set when we're done checking for config header. configChecked bool t *templateState // Store away the return node in partials. returnNode *parse.CommandNode } func (c templateContext) getIfNotVisited(name string) *templateState { if c.visited[name] { return nil } c.visited[name] = true templ := c.lookupFn(name) if templ == nil { // This may be a inline template defined outside of this file // and not yet parsed. Unusual, but it happens. // Store the name to try again later. c.templateNotFound[name] = true } return templ } func newTemplateContext( t *templateState, lookupFn func(name string) *templateState) *templateContext { return &templateContext{ t: t, lookupFn: lookupFn, visited: make(map[string]bool), templateNotFound: make(map[string]bool), identityNotFound: make(map[string]bool), } } func applyTemplateTransformers( t *templateState, lookupFn func(name string) *templateState) (*templateContext, error) { if t == nil { return nil, errors.New("expected template, but none provided") } c := newTemplateContext(t, lookupFn) tree := getParseTree(t.Template) _, err := c.applyTransformations(tree.Root) if err == nil && c.returnNode != nil { // This is a partial with a return statement. c.t.parseInfo.HasReturn = true tree.Root = c.wrapInPartialReturnWrapper(tree.Root) } return c, err } func getParseTree(templ tpl.Template) *parse.Tree { templ = unwrap(templ) if text, ok := templ.(*texttemplate.Template); ok { return text.Tree } return templ.(*htmltemplate.Template).Tree } const ( partialReturnWrapperTempl = `{{ $_hugo_dot := $ }}{{ $ := .Arg }}{{ with .Arg }}{{ $_hugo_dot.Set ("PLACEHOLDER") }}{{ end }}` ) var partialReturnWrapper *parse.ListNode func init() { templ, err := texttemplate.New("").Parse(partialReturnWrapperTempl) if err != nil { panic(err) } partialReturnWrapper = templ.Tree.Root } func (c *templateContext) wrapInPartialReturnWrapper(n *parse.ListNode) *parse.ListNode { wrapper := partialReturnWrapper.CopyList() withNode := wrapper.Nodes[2].(*parse.WithNode) retn := withNode.List.Nodes[0] setCmd := retn.(*parse.ActionNode).Pipe.Cmds[0] setPipe := setCmd.Args[1].(*parse.PipeNode) // Replace PLACEHOLDER with the real return value. // Note that this is a PipeNode, so it will be wrapped in parens. setPipe.Cmds = []*parse.CommandNode{c.returnNode} withNode.List.Nodes = append(n.Nodes, retn) return wrapper } // applyTransformations do 2 things: // 1) Parses partial return statement. // 2) Tracks template (partial) dependencies and some other info. func (c *templateContext) applyTransformations(n parse.Node) (bool, error) { switch x := n.(type) { case *parse.ListNode: if x != nil { c.applyTransformationsToNodes(x.Nodes...) } case *parse.ActionNode: c.applyTransformationsToNodes(x.Pipe) case *parse.IfNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.WithNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.RangeNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.TemplateNode: subTempl := c.getIfNotVisited(x.Name) if subTempl != nil { c.applyTransformationsToNodes(getParseTree(subTempl.Template).Root) } case *parse.PipeNode: c.collectConfig(x) for i, cmd := range x.Cmds { keep, _ := c.applyTransformations(cmd) if !keep { x.Cmds = append(x.Cmds[:i], x.Cmds[i+1:]...) } } case *parse.CommandNode: c.collectPartialInfo(x) c.collectInner(x) keep := c.collectReturnNode(x) for _, elem := range x.Args { switch an := elem.(type) { case *parse.PipeNode: c.applyTransformations(an) } } return keep, c.err } return true, c.err } func (c *templateContext) applyTransformationsToNodes(nodes ...parse.Node) { for _, node := range nodes { c.applyTransformations(node) } } func (c *templateContext) hasIdent(idents []string, ident string) bool { for _, id := range idents { if id == ident { return true } } return false } // collectConfig collects and parses any leading template config variable declaration. // This will be the first PipeNode in the template, and will be a variable declaration // on the form: // {{ $_hugo_config:= `{ "version": 1 }` }} func (c *templateContext) collectConfig(n *parse.PipeNode) { if c.t.typ != templateShortcode { return } if c.configChecked { return } c.configChecked = true if len(n.Decl) != 1 || len(n.Cmds) != 1 { // This cannot be a config declaration return } v := n.Decl[0] if len(v.Ident) == 0 || v.Ident[0] != "$_hugo_config" { return } cmd := n.Cmds[0] if len(cmd.Args) == 0 { return } if s, ok := cmd.Args[0].(*parse.StringNode); ok { errMsg := "failed to decode $_hugo_config in template" m, err := maps.ToStringMapE(s.Text) if err != nil { c.err = errors.Wrap(err, errMsg) return } if err := mapstructure.WeakDecode(m, &c.t.parseInfo.Config); err != nil { c.err = errors.Wrap(err, errMsg) } } } // collectInner determines if the given CommandNode represents a // shortcode call to its .Inner. func (c *templateContext) collectInner(n *parse.CommandNode) { if c.t.typ != templateShortcode { return } if c.t.parseInfo.IsInner || len(n.Args) == 0 { return } for _, arg := range n.Args { var idents []string switch nt := arg.(type) { case *parse.FieldNode: idents = nt.Ident case *parse.VariableNode: idents = nt.Ident } if c.hasIdent(idents, "Inner") { c.t.parseInfo.IsInner = true break } } } var partialRe = regexp.MustCompile(`^partial(Cached)?$|^partials\.Include(Cached)?$`) func (c *templateContext) collectPartialInfo(x *parse.CommandNode) { if len(x.Args) < 2 { return } first := x.Args[0] var id string switch v := first.(type) { case *parse.IdentifierNode: id = v.Ident case *parse.ChainNode: id = v.String() } if partialRe.MatchString(id) { partialName := strings.Trim(x.Args[1].String(), "\"") if !strings.Contains(partialName, ".") { partialName += ".html" } partialName = "partials/" + partialName info := c.lookupFn(partialName) if info != nil { c.t.Add(info) } else { // Delay for later c.identityNotFound[partialName] = true } } } func (c *templateContext) collectReturnNode(n *parse.CommandNode) bool { if c.t.typ != templatePartial || c.returnNode != nil { return true } if len(n.Args) < 2 { return true } ident, ok := n.Args[0].(*parse.IdentifierNode) if !ok || ident.Ident != "return" { return true } c.returnNode = n // Remove the "return" identifiers c.returnNode.Args = c.returnNode.Args[1:] return false } func findTemplateIn(name string, in tpl.Template) (tpl.Template, bool) { in = unwrap(in) if text, ok := in.(*texttemplate.Template); ok { if templ := text.Lookup(name); templ != nil { return templ, true } return nil, false } if templ := in.(*htmltemplate.Template).Lookup(name); templ != nil { return templ, true } return nil, false }
// 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 tplimpl import ( "regexp" "strings" htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate" texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/tpl" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" ) type templateType int const ( templateUndefined templateType = iota templateShortcode templatePartial ) type templateContext struct { visited map[string]bool templateNotFound map[string]bool identityNotFound map[string]bool lookupFn func(name string) *templateState // The last error encountered. err error // Set when we're done checking for config header. configChecked bool t *templateState // Store away the return node in partials. returnNode *parse.CommandNode } func (c templateContext) getIfNotVisited(name string) *templateState { if c.visited[name] { return nil } c.visited[name] = true templ := c.lookupFn(name) if templ == nil { // This may be a inline template defined outside of this file // and not yet parsed. Unusual, but it happens. // Store the name to try again later. c.templateNotFound[name] = true } return templ } func newTemplateContext( t *templateState, lookupFn func(name string) *templateState) *templateContext { return &templateContext{ t: t, lookupFn: lookupFn, visited: make(map[string]bool), templateNotFound: make(map[string]bool), identityNotFound: make(map[string]bool), } } func applyTemplateTransformers( t *templateState, lookupFn func(name string) *templateState) (*templateContext, error) { if t == nil { return nil, errors.New("expected template, but none provided") } c := newTemplateContext(t, lookupFn) tree := getParseTree(t.Template) _, err := c.applyTransformations(tree.Root) if err == nil && c.returnNode != nil { // This is a partial with a return statement. c.t.parseInfo.HasReturn = true tree.Root = c.wrapInPartialReturnWrapper(tree.Root) } return c, err } func getParseTree(templ tpl.Template) *parse.Tree { templ = unwrap(templ) if text, ok := templ.(*texttemplate.Template); ok { return text.Tree } return templ.(*htmltemplate.Template).Tree } const ( // We parse this template and modify the nodes in order to assign // the return value of a partial to a contextWrapper via Set. We use // "range" over a one-element slice so we can shift dot to the // partial's argument, Arg, while allowing Arg to be falsy. partialReturnWrapperTempl = `{{ $_hugo_dot := $ }}{{ $ := .Arg }}{{ range (slice .Arg) }}{{ $_hugo_dot.Set ("PLACEHOLDER") }}{{ end }}` ) var partialReturnWrapper *parse.ListNode func init() { templ, err := texttemplate.New("").Parse(partialReturnWrapperTempl) if err != nil { panic(err) } partialReturnWrapper = templ.Tree.Root } // wrapInPartialReturnWrapper copies and modifies the parsed nodes of a // predefined partial return wrapper to insert those of a user-defined partial. func (c *templateContext) wrapInPartialReturnWrapper(n *parse.ListNode) *parse.ListNode { wrapper := partialReturnWrapper.CopyList() rangeNode := wrapper.Nodes[2].(*parse.RangeNode) retn := rangeNode.List.Nodes[0] setCmd := retn.(*parse.ActionNode).Pipe.Cmds[0] setPipe := setCmd.Args[1].(*parse.PipeNode) // Replace PLACEHOLDER with the real return value. // Note that this is a PipeNode, so it will be wrapped in parens. setPipe.Cmds = []*parse.CommandNode{c.returnNode} rangeNode.List.Nodes = append(n.Nodes, retn) return wrapper } // applyTransformations do 2 things: // 1) Parses partial return statement. // 2) Tracks template (partial) dependencies and some other info. func (c *templateContext) applyTransformations(n parse.Node) (bool, error) { switch x := n.(type) { case *parse.ListNode: if x != nil { c.applyTransformationsToNodes(x.Nodes...) } case *parse.ActionNode: c.applyTransformationsToNodes(x.Pipe) case *parse.IfNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.WithNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.RangeNode: c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList) case *parse.TemplateNode: subTempl := c.getIfNotVisited(x.Name) if subTempl != nil { c.applyTransformationsToNodes(getParseTree(subTempl.Template).Root) } case *parse.PipeNode: c.collectConfig(x) for i, cmd := range x.Cmds { keep, _ := c.applyTransformations(cmd) if !keep { x.Cmds = append(x.Cmds[:i], x.Cmds[i+1:]...) } } case *parse.CommandNode: c.collectPartialInfo(x) c.collectInner(x) keep := c.collectReturnNode(x) for _, elem := range x.Args { switch an := elem.(type) { case *parse.PipeNode: c.applyTransformations(an) } } return keep, c.err } return true, c.err } func (c *templateContext) applyTransformationsToNodes(nodes ...parse.Node) { for _, node := range nodes { c.applyTransformations(node) } } func (c *templateContext) hasIdent(idents []string, ident string) bool { for _, id := range idents { if id == ident { return true } } return false } // collectConfig collects and parses any leading template config variable declaration. // This will be the first PipeNode in the template, and will be a variable declaration // on the form: // {{ $_hugo_config:= `{ "version": 1 }` }} func (c *templateContext) collectConfig(n *parse.PipeNode) { if c.t.typ != templateShortcode { return } if c.configChecked { return } c.configChecked = true if len(n.Decl) != 1 || len(n.Cmds) != 1 { // This cannot be a config declaration return } v := n.Decl[0] if len(v.Ident) == 0 || v.Ident[0] != "$_hugo_config" { return } cmd := n.Cmds[0] if len(cmd.Args) == 0 { return } if s, ok := cmd.Args[0].(*parse.StringNode); ok { errMsg := "failed to decode $_hugo_config in template" m, err := maps.ToStringMapE(s.Text) if err != nil { c.err = errors.Wrap(err, errMsg) return } if err := mapstructure.WeakDecode(m, &c.t.parseInfo.Config); err != nil { c.err = errors.Wrap(err, errMsg) } } } // collectInner determines if the given CommandNode represents a // shortcode call to its .Inner. func (c *templateContext) collectInner(n *parse.CommandNode) { if c.t.typ != templateShortcode { return } if c.t.parseInfo.IsInner || len(n.Args) == 0 { return } for _, arg := range n.Args { var idents []string switch nt := arg.(type) { case *parse.FieldNode: idents = nt.Ident case *parse.VariableNode: idents = nt.Ident } if c.hasIdent(idents, "Inner") { c.t.parseInfo.IsInner = true break } } } var partialRe = regexp.MustCompile(`^partial(Cached)?$|^partials\.Include(Cached)?$`) func (c *templateContext) collectPartialInfo(x *parse.CommandNode) { if len(x.Args) < 2 { return } first := x.Args[0] var id string switch v := first.(type) { case *parse.IdentifierNode: id = v.Ident case *parse.ChainNode: id = v.String() } if partialRe.MatchString(id) { partialName := strings.Trim(x.Args[1].String(), "\"") if !strings.Contains(partialName, ".") { partialName += ".html" } partialName = "partials/" + partialName info := c.lookupFn(partialName) if info != nil { c.t.Add(info) } else { // Delay for later c.identityNotFound[partialName] = true } } } func (c *templateContext) collectReturnNode(n *parse.CommandNode) bool { if c.t.typ != templatePartial || c.returnNode != nil { return true } if len(n.Args) < 2 { return true } ident, ok := n.Args[0].(*parse.IdentifierNode) if !ok || ident.Ident != "return" { return true } c.returnNode = n // Remove the "return" identifiers c.returnNode.Args = c.returnNode.Args[1:] return false } func findTemplateIn(name string, in tpl.Template) (tpl.Template, bool) { in = unwrap(in) if text, ok := in.(*texttemplate.Template); ok { if templ := text.Lookup(name); templ != nil { return templ, true } return nil, false } if templ := in.(*htmltemplate.Template).Lookup(name); templ != nil { return templ, true } return nil, false }
ptgott
8ee6de6d96a64395d27416d4f2ad7d172a2686d0
5758c370eac6c4460cd6bb34d4475c8d347585f6
I gave this a go, though my attempt at a comment depended on explaining what we were doing with the `partialReturnWrapperTempl`. In the end, I found it simpler to add a comment above `partialReturnWrapperTempl` while leaving `contextWrapper.Arg` as it was. How does that sound?
ptgott
131
gohugoio/hugo
9,278
Improve handling of remote image/jpeg resources
Closes #9275
null
2021-12-12 00:07:30+00:00
2021-12-13 07:55:15+00:00
resources/images/config.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 images import ( "fmt" "image/color" "strconv" "strings" "github.com/gohugoio/hugo/helpers" "github.com/pkg/errors" "github.com/bep/gowebp/libwebp/webpoptions" "github.com/disintegration/gift" "github.com/mitchellh/mapstructure" ) var ( imageFormats = map[string]Format{ ".jpg": JPEG, ".jpeg": JPEG, ".png": PNG, ".tif": TIFF, ".tiff": TIFF, ".bmp": BMP, ".gif": GIF, ".webp": WEBP, } // Add or increment if changes to an image format's processing requires // re-generation. imageFormatsVersions = map[Format]int{ PNG: 3, // Fix transparency issue with 32 bit images. WEBP: 2, // Fix transparency issue with 32 bit images. } // Increment to mark all processed images as stale. Only use when absolutely needed. // See the finer grained smartCropVersionNumber and imageFormatsVersions. mainImageVersionNumber = 0 ) var anchorPositions = map[string]gift.Anchor{ strings.ToLower("Center"): gift.CenterAnchor, strings.ToLower("TopLeft"): gift.TopLeftAnchor, strings.ToLower("Top"): gift.TopAnchor, strings.ToLower("TopRight"): gift.TopRightAnchor, strings.ToLower("Left"): gift.LeftAnchor, strings.ToLower("Right"): gift.RightAnchor, strings.ToLower("BottomLeft"): gift.BottomLeftAnchor, strings.ToLower("Bottom"): gift.BottomAnchor, strings.ToLower("BottomRight"): gift.BottomRightAnchor, } // These encoding hints are currently only relevant for Webp. var hints = map[string]webpoptions.EncodingPreset{ "picture": webpoptions.EncodingPresetPicture, "photo": webpoptions.EncodingPresetPhoto, "drawing": webpoptions.EncodingPresetDrawing, "icon": webpoptions.EncodingPresetIcon, "text": webpoptions.EncodingPresetText, } var imageFilters = map[string]gift.Resampling{ strings.ToLower("NearestNeighbor"): gift.NearestNeighborResampling, strings.ToLower("Box"): gift.BoxResampling, strings.ToLower("Linear"): gift.LinearResampling, strings.ToLower("Hermite"): hermiteResampling, strings.ToLower("MitchellNetravali"): mitchellNetravaliResampling, strings.ToLower("CatmullRom"): catmullRomResampling, strings.ToLower("BSpline"): bSplineResampling, strings.ToLower("Gaussian"): gaussianResampling, strings.ToLower("Lanczos"): gift.LanczosResampling, strings.ToLower("Hann"): hannResampling, strings.ToLower("Hamming"): hammingResampling, strings.ToLower("Blackman"): blackmanResampling, strings.ToLower("Bartlett"): bartlettResampling, strings.ToLower("Welch"): welchResampling, strings.ToLower("Cosine"): cosineResampling, } func ImageFormatFromExt(ext string) (Format, bool) { f, found := imageFormats[ext] return f, found } const ( defaultJPEGQuality = 75 defaultResampleFilter = "box" defaultBgColor = "ffffff" defaultHint = "photo" ) var defaultImaging = Imaging{ ResampleFilter: defaultResampleFilter, BgColor: defaultBgColor, Hint: defaultHint, Quality: defaultJPEGQuality, } func DecodeConfig(m map[string]interface{}) (ImagingConfig, error) { if m == nil { m = make(map[string]interface{}) } i := ImagingConfig{ Cfg: defaultImaging, CfgHash: helpers.HashString(m), } if err := mapstructure.WeakDecode(m, &i.Cfg); err != nil { return i, err } if err := i.Cfg.init(); err != nil { return i, err } var err error i.BgColor, err = hexStringToColor(i.Cfg.BgColor) if err != nil { return i, err } if i.Cfg.Anchor != "" && i.Cfg.Anchor != smartCropIdentifier { anchor, found := anchorPositions[i.Cfg.Anchor] if !found { return i, errors.Errorf("invalid anchor value %q in imaging config", i.Anchor) } i.Anchor = anchor } else { i.Cfg.Anchor = smartCropIdentifier } filter, found := imageFilters[i.Cfg.ResampleFilter] if !found { return i, fmt.Errorf("%q is not a valid resample filter", filter) } i.ResampleFilter = filter if strings.TrimSpace(i.Cfg.Exif.IncludeFields) == "" && strings.TrimSpace(i.Cfg.Exif.ExcludeFields) == "" { // Don't change this for no good reason. Please don't. i.Cfg.Exif.ExcludeFields = "GPS|Exif|Exposure[M|P|B]|Contrast|Resolution|Sharp|JPEG|Metering|Sensing|Saturation|ColorSpace|Flash|WhiteBalance" } return i, nil } func DecodeImageConfig(action, config string, defaults ImagingConfig, sourceFormat Format) (ImageConfig, error) { var ( c ImageConfig = GetDefaultImageConfig(action, defaults) err error ) c.Action = action if config == "" { return c, errors.New("image config cannot be empty") } parts := strings.Fields(config) for _, part := range parts { part = strings.ToLower(part) if part == smartCropIdentifier { c.AnchorStr = smartCropIdentifier } else if pos, ok := anchorPositions[part]; ok { c.Anchor = pos c.AnchorStr = part } else if filter, ok := imageFilters[part]; ok { c.Filter = filter c.FilterStr = part } else if hint, ok := hints[part]; ok { c.Hint = hint } else if part[0] == '#' { c.BgColorStr = part[1:] c.BgColor, err = hexStringToColor(c.BgColorStr) if err != nil { return c, err } } else if part[0] == 'q' { c.Quality, err = strconv.Atoi(part[1:]) if err != nil { return c, err } if c.Quality < 1 || c.Quality > 100 { return c, errors.New("quality ranges from 1 to 100 inclusive") } c.qualitySetForImage = true } else if part[0] == 'r' { c.Rotate, err = strconv.Atoi(part[1:]) if err != nil { return c, err } } else if strings.Contains(part, "x") { widthHeight := strings.Split(part, "x") if len(widthHeight) <= 2 { first := widthHeight[0] if first != "" { c.Width, err = strconv.Atoi(first) if err != nil { return c, err } } if len(widthHeight) == 2 { second := widthHeight[1] if second != "" { c.Height, err = strconv.Atoi(second) if err != nil { return c, err } } } } else { return c, errors.New("invalid image dimensions") } } else if f, ok := ImageFormatFromExt("." + part); ok { c.TargetFormat = f } } if c.Width == 0 && c.Height == 0 { return c, errors.New("must provide Width or Height") } if c.FilterStr == "" { c.FilterStr = defaults.Cfg.ResampleFilter c.Filter = defaults.ResampleFilter } if c.Hint == 0 { c.Hint = webpoptions.EncodingPresetPhoto } if c.AnchorStr == "" { c.AnchorStr = defaults.Cfg.Anchor c.Anchor = defaults.Anchor } // default to the source format if c.TargetFormat == 0 { c.TargetFormat = sourceFormat } if c.Quality <= 0 && c.TargetFormat.RequiresDefaultQuality() { // We need a quality setting for all JPEGs and WEBPs. c.Quality = defaults.Cfg.Quality } if c.BgColor == nil && c.TargetFormat != sourceFormat { if sourceFormat.SupportsTransparency() && !c.TargetFormat.SupportsTransparency() { c.BgColor = defaults.BgColor c.BgColorStr = defaults.Cfg.BgColor } } return c, nil } // ImageConfig holds configuration to create a new image from an existing one, resize etc. type ImageConfig struct { // This defines the output format of the output image. It defaults to the source format. TargetFormat Format Action string // If set, this will be used as the key in filenames etc. Key string // Quality ranges from 1 to 100 inclusive, higher is better. // This is only relevant for JPEG and WEBP images. // Default is 75. Quality int qualitySetForImage bool // Whether the above is set for this image. // Rotate rotates an image by the given angle counter-clockwise. // The rotation will be performed first. Rotate int // Used to fill any transparency. // When set in site config, it's used when converting to a format that does // not support transparency. // When set per image operation, it's used even for formats that does support // transparency. BgColor color.Color BgColorStr string // Hint about what type of picture this is. Used to optimize encoding // when target is set to webp. Hint webpoptions.EncodingPreset Width int Height int Filter gift.Resampling FilterStr string Anchor gift.Anchor AnchorStr string } func (i ImageConfig) GetKey(format Format) string { if i.Key != "" { return i.Action + "_" + i.Key } k := strconv.Itoa(i.Width) + "x" + strconv.Itoa(i.Height) if i.Action != "" { k += "_" + i.Action } // This slightly odd construct is here to preserve the old image keys. if i.qualitySetForImage || i.TargetFormat.RequiresDefaultQuality() { k += "_q" + strconv.Itoa(i.Quality) } if i.Rotate != 0 { k += "_r" + strconv.Itoa(i.Rotate) } if i.BgColorStr != "" { k += "_bg" + i.BgColorStr } if i.TargetFormat == WEBP { k += "_h" + strconv.Itoa(int(i.Hint)) } anchor := i.AnchorStr if anchor == smartCropIdentifier { anchor = anchor + strconv.Itoa(smartCropVersionNumber) } k += "_" + i.FilterStr if strings.EqualFold(i.Action, "fill") { k += "_" + anchor } if v, ok := imageFormatsVersions[format]; ok { k += "_" + strconv.Itoa(v) } if mainImageVersionNumber > 0 { k += "_" + strconv.Itoa(mainImageVersionNumber) } return k } type ImagingConfig struct { BgColor color.Color Hint webpoptions.EncodingPreset ResampleFilter gift.Resampling Anchor gift.Anchor // Config as provided by the user. Cfg Imaging // Hash of the config map provided by the user. CfgHash string } // Imaging contains default image processing configuration. This will be fetched // from site (or language) config. type Imaging struct { // Default image quality setting (1-100). Only used for JPEG images. Quality int // Resample filter to use in resize operations. ResampleFilter string // Hint about what type of image this is. // Currently only used when encoding to Webp. // Default is "photo". // Valid values are "picture", "photo", "drawing", "icon", or "text". Hint string // The anchor to use in Fill. Default is "smart", i.e. Smart Crop. Anchor string // Default color used in fill operations (e.g. "fff" for white). BgColor string Exif ExifConfig } func (cfg *Imaging) init() error { if cfg.Quality < 0 || cfg.Quality > 100 { return errors.New("image quality must be a number between 1 and 100") } cfg.BgColor = strings.ToLower(strings.TrimPrefix(cfg.BgColor, "#")) cfg.Anchor = strings.ToLower(cfg.Anchor) cfg.ResampleFilter = strings.ToLower(cfg.ResampleFilter) cfg.Hint = strings.ToLower(cfg.Hint) return nil } type ExifConfig struct { // Regexp matching the Exif fields you want from the (massive) set of Exif info // available. As we cache this info to disk, this is for performance and // disk space reasons more than anything. // If you want it all, put ".*" in this config setting. // Note that if neither this or ExcludeFields is set, Hugo will return a small // default set. IncludeFields string // Regexp matching the Exif fields you want to exclude. This may be easier to use // than IncludeFields above, depending on what you want. ExcludeFields string // Hugo extracts the "photo taken" date/time into .Date by default. // Set this to true to turn it off. DisableDate bool // Hugo extracts the "photo taken where" (GPS latitude and longitude) into // .Long and .Lat. Set this to true to turn it off. DisableLatLong bool }
// 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 images import ( "fmt" "image/color" "strconv" "strings" "github.com/gohugoio/hugo/helpers" "github.com/pkg/errors" "github.com/bep/gowebp/libwebp/webpoptions" "github.com/disintegration/gift" "github.com/mitchellh/mapstructure" ) var ( imageFormats = map[string]Format{ ".jpg": JPEG, ".jpeg": JPEG, ".jpe": JPEG, ".jif": JPEG, ".jfif": JPEG, ".png": PNG, ".tif": TIFF, ".tiff": TIFF, ".bmp": BMP, ".gif": GIF, ".webp": WEBP, } // Add or increment if changes to an image format's processing requires // re-generation. imageFormatsVersions = map[Format]int{ PNG: 3, // Fix transparency issue with 32 bit images. WEBP: 2, // Fix transparency issue with 32 bit images. } // Increment to mark all processed images as stale. Only use when absolutely needed. // See the finer grained smartCropVersionNumber and imageFormatsVersions. mainImageVersionNumber = 0 ) var anchorPositions = map[string]gift.Anchor{ strings.ToLower("Center"): gift.CenterAnchor, strings.ToLower("TopLeft"): gift.TopLeftAnchor, strings.ToLower("Top"): gift.TopAnchor, strings.ToLower("TopRight"): gift.TopRightAnchor, strings.ToLower("Left"): gift.LeftAnchor, strings.ToLower("Right"): gift.RightAnchor, strings.ToLower("BottomLeft"): gift.BottomLeftAnchor, strings.ToLower("Bottom"): gift.BottomAnchor, strings.ToLower("BottomRight"): gift.BottomRightAnchor, } // These encoding hints are currently only relevant for Webp. var hints = map[string]webpoptions.EncodingPreset{ "picture": webpoptions.EncodingPresetPicture, "photo": webpoptions.EncodingPresetPhoto, "drawing": webpoptions.EncodingPresetDrawing, "icon": webpoptions.EncodingPresetIcon, "text": webpoptions.EncodingPresetText, } var imageFilters = map[string]gift.Resampling{ strings.ToLower("NearestNeighbor"): gift.NearestNeighborResampling, strings.ToLower("Box"): gift.BoxResampling, strings.ToLower("Linear"): gift.LinearResampling, strings.ToLower("Hermite"): hermiteResampling, strings.ToLower("MitchellNetravali"): mitchellNetravaliResampling, strings.ToLower("CatmullRom"): catmullRomResampling, strings.ToLower("BSpline"): bSplineResampling, strings.ToLower("Gaussian"): gaussianResampling, strings.ToLower("Lanczos"): gift.LanczosResampling, strings.ToLower("Hann"): hannResampling, strings.ToLower("Hamming"): hammingResampling, strings.ToLower("Blackman"): blackmanResampling, strings.ToLower("Bartlett"): bartlettResampling, strings.ToLower("Welch"): welchResampling, strings.ToLower("Cosine"): cosineResampling, } func ImageFormatFromExt(ext string) (Format, bool) { f, found := imageFormats[ext] return f, found } const ( defaultJPEGQuality = 75 defaultResampleFilter = "box" defaultBgColor = "ffffff" defaultHint = "photo" ) var defaultImaging = Imaging{ ResampleFilter: defaultResampleFilter, BgColor: defaultBgColor, Hint: defaultHint, Quality: defaultJPEGQuality, } func DecodeConfig(m map[string]interface{}) (ImagingConfig, error) { if m == nil { m = make(map[string]interface{}) } i := ImagingConfig{ Cfg: defaultImaging, CfgHash: helpers.HashString(m), } if err := mapstructure.WeakDecode(m, &i.Cfg); err != nil { return i, err } if err := i.Cfg.init(); err != nil { return i, err } var err error i.BgColor, err = hexStringToColor(i.Cfg.BgColor) if err != nil { return i, err } if i.Cfg.Anchor != "" && i.Cfg.Anchor != smartCropIdentifier { anchor, found := anchorPositions[i.Cfg.Anchor] if !found { return i, errors.Errorf("invalid anchor value %q in imaging config", i.Anchor) } i.Anchor = anchor } else { i.Cfg.Anchor = smartCropIdentifier } filter, found := imageFilters[i.Cfg.ResampleFilter] if !found { return i, fmt.Errorf("%q is not a valid resample filter", filter) } i.ResampleFilter = filter if strings.TrimSpace(i.Cfg.Exif.IncludeFields) == "" && strings.TrimSpace(i.Cfg.Exif.ExcludeFields) == "" { // Don't change this for no good reason. Please don't. i.Cfg.Exif.ExcludeFields = "GPS|Exif|Exposure[M|P|B]|Contrast|Resolution|Sharp|JPEG|Metering|Sensing|Saturation|ColorSpace|Flash|WhiteBalance" } return i, nil } func DecodeImageConfig(action, config string, defaults ImagingConfig, sourceFormat Format) (ImageConfig, error) { var ( c ImageConfig = GetDefaultImageConfig(action, defaults) err error ) c.Action = action if config == "" { return c, errors.New("image config cannot be empty") } parts := strings.Fields(config) for _, part := range parts { part = strings.ToLower(part) if part == smartCropIdentifier { c.AnchorStr = smartCropIdentifier } else if pos, ok := anchorPositions[part]; ok { c.Anchor = pos c.AnchorStr = part } else if filter, ok := imageFilters[part]; ok { c.Filter = filter c.FilterStr = part } else if hint, ok := hints[part]; ok { c.Hint = hint } else if part[0] == '#' { c.BgColorStr = part[1:] c.BgColor, err = hexStringToColor(c.BgColorStr) if err != nil { return c, err } } else if part[0] == 'q' { c.Quality, err = strconv.Atoi(part[1:]) if err != nil { return c, err } if c.Quality < 1 || c.Quality > 100 { return c, errors.New("quality ranges from 1 to 100 inclusive") } c.qualitySetForImage = true } else if part[0] == 'r' { c.Rotate, err = strconv.Atoi(part[1:]) if err != nil { return c, err } } else if strings.Contains(part, "x") { widthHeight := strings.Split(part, "x") if len(widthHeight) <= 2 { first := widthHeight[0] if first != "" { c.Width, err = strconv.Atoi(first) if err != nil { return c, err } } if len(widthHeight) == 2 { second := widthHeight[1] if second != "" { c.Height, err = strconv.Atoi(second) if err != nil { return c, err } } } } else { return c, errors.New("invalid image dimensions") } } else if f, ok := ImageFormatFromExt("." + part); ok { c.TargetFormat = f } } if c.Width == 0 && c.Height == 0 { return c, errors.New("must provide Width or Height") } if c.FilterStr == "" { c.FilterStr = defaults.Cfg.ResampleFilter c.Filter = defaults.ResampleFilter } if c.Hint == 0 { c.Hint = webpoptions.EncodingPresetPhoto } if c.AnchorStr == "" { c.AnchorStr = defaults.Cfg.Anchor c.Anchor = defaults.Anchor } // default to the source format if c.TargetFormat == 0 { c.TargetFormat = sourceFormat } if c.Quality <= 0 && c.TargetFormat.RequiresDefaultQuality() { // We need a quality setting for all JPEGs and WEBPs. c.Quality = defaults.Cfg.Quality } if c.BgColor == nil && c.TargetFormat != sourceFormat { if sourceFormat.SupportsTransparency() && !c.TargetFormat.SupportsTransparency() { c.BgColor = defaults.BgColor c.BgColorStr = defaults.Cfg.BgColor } } return c, nil } // ImageConfig holds configuration to create a new image from an existing one, resize etc. type ImageConfig struct { // This defines the output format of the output image. It defaults to the source format. TargetFormat Format Action string // If set, this will be used as the key in filenames etc. Key string // Quality ranges from 1 to 100 inclusive, higher is better. // This is only relevant for JPEG and WEBP images. // Default is 75. Quality int qualitySetForImage bool // Whether the above is set for this image. // Rotate rotates an image by the given angle counter-clockwise. // The rotation will be performed first. Rotate int // Used to fill any transparency. // When set in site config, it's used when converting to a format that does // not support transparency. // When set per image operation, it's used even for formats that does support // transparency. BgColor color.Color BgColorStr string // Hint about what type of picture this is. Used to optimize encoding // when target is set to webp. Hint webpoptions.EncodingPreset Width int Height int Filter gift.Resampling FilterStr string Anchor gift.Anchor AnchorStr string } func (i ImageConfig) GetKey(format Format) string { if i.Key != "" { return i.Action + "_" + i.Key } k := strconv.Itoa(i.Width) + "x" + strconv.Itoa(i.Height) if i.Action != "" { k += "_" + i.Action } // This slightly odd construct is here to preserve the old image keys. if i.qualitySetForImage || i.TargetFormat.RequiresDefaultQuality() { k += "_q" + strconv.Itoa(i.Quality) } if i.Rotate != 0 { k += "_r" + strconv.Itoa(i.Rotate) } if i.BgColorStr != "" { k += "_bg" + i.BgColorStr } if i.TargetFormat == WEBP { k += "_h" + strconv.Itoa(int(i.Hint)) } anchor := i.AnchorStr if anchor == smartCropIdentifier { anchor = anchor + strconv.Itoa(smartCropVersionNumber) } k += "_" + i.FilterStr if strings.EqualFold(i.Action, "fill") { k += "_" + anchor } if v, ok := imageFormatsVersions[format]; ok { k += "_" + strconv.Itoa(v) } if mainImageVersionNumber > 0 { k += "_" + strconv.Itoa(mainImageVersionNumber) } return k } type ImagingConfig struct { BgColor color.Color Hint webpoptions.EncodingPreset ResampleFilter gift.Resampling Anchor gift.Anchor // Config as provided by the user. Cfg Imaging // Hash of the config map provided by the user. CfgHash string } // Imaging contains default image processing configuration. This will be fetched // from site (or language) config. type Imaging struct { // Default image quality setting (1-100). Only used for JPEG images. Quality int // Resample filter to use in resize operations. ResampleFilter string // Hint about what type of image this is. // Currently only used when encoding to Webp. // Default is "photo". // Valid values are "picture", "photo", "drawing", "icon", or "text". Hint string // The anchor to use in Fill. Default is "smart", i.e. Smart Crop. Anchor string // Default color used in fill operations (e.g. "fff" for white). BgColor string Exif ExifConfig } func (cfg *Imaging) init() error { if cfg.Quality < 0 || cfg.Quality > 100 { return errors.New("image quality must be a number between 1 and 100") } cfg.BgColor = strings.ToLower(strings.TrimPrefix(cfg.BgColor, "#")) cfg.Anchor = strings.ToLower(cfg.Anchor) cfg.ResampleFilter = strings.ToLower(cfg.ResampleFilter) cfg.Hint = strings.ToLower(cfg.Hint) return nil } type ExifConfig struct { // Regexp matching the Exif fields you want from the (massive) set of Exif info // available. As we cache this info to disk, this is for performance and // disk space reasons more than anything. // If you want it all, put ".*" in this config setting. // Note that if neither this or ExcludeFields is set, Hugo will return a small // default set. IncludeFields string // Regexp matching the Exif fields you want to exclude. This may be easier to use // than IncludeFields above, depending on what you want. ExcludeFields string // Hugo extracts the "photo taken" date/time into .Date by default. // Set this to true to turn it off. DisableDate bool // Hugo extracts the "photo taken where" (GPS latitude and longitude) into // .Long and .Lat. Set this to true to turn it off. DisableLatLong bool }
jmooring
8a005538db5789e25ba2b092104b6cc53c6c1ece
a037be774d567c6a29cc7f10c94c9f746ca6d2aa
OK, I think I misunderstood the problem. I thought this was a "media type" problem. I see that there are some rooms for improvements in the above, but I suggest that you instead just do the mapping to `jpg` early (inside `FromRemote`).
bep
132
gohugoio/hugo
9,278
Improve handling of remote image/jpeg resources
Closes #9275
null
2021-12-12 00:07:30+00:00
2021-12-13 07:55:15+00:00
resources/images/config.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 images import ( "fmt" "image/color" "strconv" "strings" "github.com/gohugoio/hugo/helpers" "github.com/pkg/errors" "github.com/bep/gowebp/libwebp/webpoptions" "github.com/disintegration/gift" "github.com/mitchellh/mapstructure" ) var ( imageFormats = map[string]Format{ ".jpg": JPEG, ".jpeg": JPEG, ".png": PNG, ".tif": TIFF, ".tiff": TIFF, ".bmp": BMP, ".gif": GIF, ".webp": WEBP, } // Add or increment if changes to an image format's processing requires // re-generation. imageFormatsVersions = map[Format]int{ PNG: 3, // Fix transparency issue with 32 bit images. WEBP: 2, // Fix transparency issue with 32 bit images. } // Increment to mark all processed images as stale. Only use when absolutely needed. // See the finer grained smartCropVersionNumber and imageFormatsVersions. mainImageVersionNumber = 0 ) var anchorPositions = map[string]gift.Anchor{ strings.ToLower("Center"): gift.CenterAnchor, strings.ToLower("TopLeft"): gift.TopLeftAnchor, strings.ToLower("Top"): gift.TopAnchor, strings.ToLower("TopRight"): gift.TopRightAnchor, strings.ToLower("Left"): gift.LeftAnchor, strings.ToLower("Right"): gift.RightAnchor, strings.ToLower("BottomLeft"): gift.BottomLeftAnchor, strings.ToLower("Bottom"): gift.BottomAnchor, strings.ToLower("BottomRight"): gift.BottomRightAnchor, } // These encoding hints are currently only relevant for Webp. var hints = map[string]webpoptions.EncodingPreset{ "picture": webpoptions.EncodingPresetPicture, "photo": webpoptions.EncodingPresetPhoto, "drawing": webpoptions.EncodingPresetDrawing, "icon": webpoptions.EncodingPresetIcon, "text": webpoptions.EncodingPresetText, } var imageFilters = map[string]gift.Resampling{ strings.ToLower("NearestNeighbor"): gift.NearestNeighborResampling, strings.ToLower("Box"): gift.BoxResampling, strings.ToLower("Linear"): gift.LinearResampling, strings.ToLower("Hermite"): hermiteResampling, strings.ToLower("MitchellNetravali"): mitchellNetravaliResampling, strings.ToLower("CatmullRom"): catmullRomResampling, strings.ToLower("BSpline"): bSplineResampling, strings.ToLower("Gaussian"): gaussianResampling, strings.ToLower("Lanczos"): gift.LanczosResampling, strings.ToLower("Hann"): hannResampling, strings.ToLower("Hamming"): hammingResampling, strings.ToLower("Blackman"): blackmanResampling, strings.ToLower("Bartlett"): bartlettResampling, strings.ToLower("Welch"): welchResampling, strings.ToLower("Cosine"): cosineResampling, } func ImageFormatFromExt(ext string) (Format, bool) { f, found := imageFormats[ext] return f, found } const ( defaultJPEGQuality = 75 defaultResampleFilter = "box" defaultBgColor = "ffffff" defaultHint = "photo" ) var defaultImaging = Imaging{ ResampleFilter: defaultResampleFilter, BgColor: defaultBgColor, Hint: defaultHint, Quality: defaultJPEGQuality, } func DecodeConfig(m map[string]interface{}) (ImagingConfig, error) { if m == nil { m = make(map[string]interface{}) } i := ImagingConfig{ Cfg: defaultImaging, CfgHash: helpers.HashString(m), } if err := mapstructure.WeakDecode(m, &i.Cfg); err != nil { return i, err } if err := i.Cfg.init(); err != nil { return i, err } var err error i.BgColor, err = hexStringToColor(i.Cfg.BgColor) if err != nil { return i, err } if i.Cfg.Anchor != "" && i.Cfg.Anchor != smartCropIdentifier { anchor, found := anchorPositions[i.Cfg.Anchor] if !found { return i, errors.Errorf("invalid anchor value %q in imaging config", i.Anchor) } i.Anchor = anchor } else { i.Cfg.Anchor = smartCropIdentifier } filter, found := imageFilters[i.Cfg.ResampleFilter] if !found { return i, fmt.Errorf("%q is not a valid resample filter", filter) } i.ResampleFilter = filter if strings.TrimSpace(i.Cfg.Exif.IncludeFields) == "" && strings.TrimSpace(i.Cfg.Exif.ExcludeFields) == "" { // Don't change this for no good reason. Please don't. i.Cfg.Exif.ExcludeFields = "GPS|Exif|Exposure[M|P|B]|Contrast|Resolution|Sharp|JPEG|Metering|Sensing|Saturation|ColorSpace|Flash|WhiteBalance" } return i, nil } func DecodeImageConfig(action, config string, defaults ImagingConfig, sourceFormat Format) (ImageConfig, error) { var ( c ImageConfig = GetDefaultImageConfig(action, defaults) err error ) c.Action = action if config == "" { return c, errors.New("image config cannot be empty") } parts := strings.Fields(config) for _, part := range parts { part = strings.ToLower(part) if part == smartCropIdentifier { c.AnchorStr = smartCropIdentifier } else if pos, ok := anchorPositions[part]; ok { c.Anchor = pos c.AnchorStr = part } else if filter, ok := imageFilters[part]; ok { c.Filter = filter c.FilterStr = part } else if hint, ok := hints[part]; ok { c.Hint = hint } else if part[0] == '#' { c.BgColorStr = part[1:] c.BgColor, err = hexStringToColor(c.BgColorStr) if err != nil { return c, err } } else if part[0] == 'q' { c.Quality, err = strconv.Atoi(part[1:]) if err != nil { return c, err } if c.Quality < 1 || c.Quality > 100 { return c, errors.New("quality ranges from 1 to 100 inclusive") } c.qualitySetForImage = true } else if part[0] == 'r' { c.Rotate, err = strconv.Atoi(part[1:]) if err != nil { return c, err } } else if strings.Contains(part, "x") { widthHeight := strings.Split(part, "x") if len(widthHeight) <= 2 { first := widthHeight[0] if first != "" { c.Width, err = strconv.Atoi(first) if err != nil { return c, err } } if len(widthHeight) == 2 { second := widthHeight[1] if second != "" { c.Height, err = strconv.Atoi(second) if err != nil { return c, err } } } } else { return c, errors.New("invalid image dimensions") } } else if f, ok := ImageFormatFromExt("." + part); ok { c.TargetFormat = f } } if c.Width == 0 && c.Height == 0 { return c, errors.New("must provide Width or Height") } if c.FilterStr == "" { c.FilterStr = defaults.Cfg.ResampleFilter c.Filter = defaults.ResampleFilter } if c.Hint == 0 { c.Hint = webpoptions.EncodingPresetPhoto } if c.AnchorStr == "" { c.AnchorStr = defaults.Cfg.Anchor c.Anchor = defaults.Anchor } // default to the source format if c.TargetFormat == 0 { c.TargetFormat = sourceFormat } if c.Quality <= 0 && c.TargetFormat.RequiresDefaultQuality() { // We need a quality setting for all JPEGs and WEBPs. c.Quality = defaults.Cfg.Quality } if c.BgColor == nil && c.TargetFormat != sourceFormat { if sourceFormat.SupportsTransparency() && !c.TargetFormat.SupportsTransparency() { c.BgColor = defaults.BgColor c.BgColorStr = defaults.Cfg.BgColor } } return c, nil } // ImageConfig holds configuration to create a new image from an existing one, resize etc. type ImageConfig struct { // This defines the output format of the output image. It defaults to the source format. TargetFormat Format Action string // If set, this will be used as the key in filenames etc. Key string // Quality ranges from 1 to 100 inclusive, higher is better. // This is only relevant for JPEG and WEBP images. // Default is 75. Quality int qualitySetForImage bool // Whether the above is set for this image. // Rotate rotates an image by the given angle counter-clockwise. // The rotation will be performed first. Rotate int // Used to fill any transparency. // When set in site config, it's used when converting to a format that does // not support transparency. // When set per image operation, it's used even for formats that does support // transparency. BgColor color.Color BgColorStr string // Hint about what type of picture this is. Used to optimize encoding // when target is set to webp. Hint webpoptions.EncodingPreset Width int Height int Filter gift.Resampling FilterStr string Anchor gift.Anchor AnchorStr string } func (i ImageConfig) GetKey(format Format) string { if i.Key != "" { return i.Action + "_" + i.Key } k := strconv.Itoa(i.Width) + "x" + strconv.Itoa(i.Height) if i.Action != "" { k += "_" + i.Action } // This slightly odd construct is here to preserve the old image keys. if i.qualitySetForImage || i.TargetFormat.RequiresDefaultQuality() { k += "_q" + strconv.Itoa(i.Quality) } if i.Rotate != 0 { k += "_r" + strconv.Itoa(i.Rotate) } if i.BgColorStr != "" { k += "_bg" + i.BgColorStr } if i.TargetFormat == WEBP { k += "_h" + strconv.Itoa(int(i.Hint)) } anchor := i.AnchorStr if anchor == smartCropIdentifier { anchor = anchor + strconv.Itoa(smartCropVersionNumber) } k += "_" + i.FilterStr if strings.EqualFold(i.Action, "fill") { k += "_" + anchor } if v, ok := imageFormatsVersions[format]; ok { k += "_" + strconv.Itoa(v) } if mainImageVersionNumber > 0 { k += "_" + strconv.Itoa(mainImageVersionNumber) } return k } type ImagingConfig struct { BgColor color.Color Hint webpoptions.EncodingPreset ResampleFilter gift.Resampling Anchor gift.Anchor // Config as provided by the user. Cfg Imaging // Hash of the config map provided by the user. CfgHash string } // Imaging contains default image processing configuration. This will be fetched // from site (or language) config. type Imaging struct { // Default image quality setting (1-100). Only used for JPEG images. Quality int // Resample filter to use in resize operations. ResampleFilter string // Hint about what type of image this is. // Currently only used when encoding to Webp. // Default is "photo". // Valid values are "picture", "photo", "drawing", "icon", or "text". Hint string // The anchor to use in Fill. Default is "smart", i.e. Smart Crop. Anchor string // Default color used in fill operations (e.g. "fff" for white). BgColor string Exif ExifConfig } func (cfg *Imaging) init() error { if cfg.Quality < 0 || cfg.Quality > 100 { return errors.New("image quality must be a number between 1 and 100") } cfg.BgColor = strings.ToLower(strings.TrimPrefix(cfg.BgColor, "#")) cfg.Anchor = strings.ToLower(cfg.Anchor) cfg.ResampleFilter = strings.ToLower(cfg.ResampleFilter) cfg.Hint = strings.ToLower(cfg.Hint) return nil } type ExifConfig struct { // Regexp matching the Exif fields you want from the (massive) set of Exif info // available. As we cache this info to disk, this is for performance and // disk space reasons more than anything. // If you want it all, put ".*" in this config setting. // Note that if neither this or ExcludeFields is set, Hugo will return a small // default set. IncludeFields string // Regexp matching the Exif fields you want to exclude. This may be easier to use // than IncludeFields above, depending on what you want. ExcludeFields string // Hugo extracts the "photo taken" date/time into .Date by default. // Set this to true to turn it off. DisableDate bool // Hugo extracts the "photo taken where" (GPS latitude and longitude) into // .Long and .Lat. Set this to true to turn it off. DisableLatLong bool }
// 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 images import ( "fmt" "image/color" "strconv" "strings" "github.com/gohugoio/hugo/helpers" "github.com/pkg/errors" "github.com/bep/gowebp/libwebp/webpoptions" "github.com/disintegration/gift" "github.com/mitchellh/mapstructure" ) var ( imageFormats = map[string]Format{ ".jpg": JPEG, ".jpeg": JPEG, ".jpe": JPEG, ".jif": JPEG, ".jfif": JPEG, ".png": PNG, ".tif": TIFF, ".tiff": TIFF, ".bmp": BMP, ".gif": GIF, ".webp": WEBP, } // Add or increment if changes to an image format's processing requires // re-generation. imageFormatsVersions = map[Format]int{ PNG: 3, // Fix transparency issue with 32 bit images. WEBP: 2, // Fix transparency issue with 32 bit images. } // Increment to mark all processed images as stale. Only use when absolutely needed. // See the finer grained smartCropVersionNumber and imageFormatsVersions. mainImageVersionNumber = 0 ) var anchorPositions = map[string]gift.Anchor{ strings.ToLower("Center"): gift.CenterAnchor, strings.ToLower("TopLeft"): gift.TopLeftAnchor, strings.ToLower("Top"): gift.TopAnchor, strings.ToLower("TopRight"): gift.TopRightAnchor, strings.ToLower("Left"): gift.LeftAnchor, strings.ToLower("Right"): gift.RightAnchor, strings.ToLower("BottomLeft"): gift.BottomLeftAnchor, strings.ToLower("Bottom"): gift.BottomAnchor, strings.ToLower("BottomRight"): gift.BottomRightAnchor, } // These encoding hints are currently only relevant for Webp. var hints = map[string]webpoptions.EncodingPreset{ "picture": webpoptions.EncodingPresetPicture, "photo": webpoptions.EncodingPresetPhoto, "drawing": webpoptions.EncodingPresetDrawing, "icon": webpoptions.EncodingPresetIcon, "text": webpoptions.EncodingPresetText, } var imageFilters = map[string]gift.Resampling{ strings.ToLower("NearestNeighbor"): gift.NearestNeighborResampling, strings.ToLower("Box"): gift.BoxResampling, strings.ToLower("Linear"): gift.LinearResampling, strings.ToLower("Hermite"): hermiteResampling, strings.ToLower("MitchellNetravali"): mitchellNetravaliResampling, strings.ToLower("CatmullRom"): catmullRomResampling, strings.ToLower("BSpline"): bSplineResampling, strings.ToLower("Gaussian"): gaussianResampling, strings.ToLower("Lanczos"): gift.LanczosResampling, strings.ToLower("Hann"): hannResampling, strings.ToLower("Hamming"): hammingResampling, strings.ToLower("Blackman"): blackmanResampling, strings.ToLower("Bartlett"): bartlettResampling, strings.ToLower("Welch"): welchResampling, strings.ToLower("Cosine"): cosineResampling, } func ImageFormatFromExt(ext string) (Format, bool) { f, found := imageFormats[ext] return f, found } const ( defaultJPEGQuality = 75 defaultResampleFilter = "box" defaultBgColor = "ffffff" defaultHint = "photo" ) var defaultImaging = Imaging{ ResampleFilter: defaultResampleFilter, BgColor: defaultBgColor, Hint: defaultHint, Quality: defaultJPEGQuality, } func DecodeConfig(m map[string]interface{}) (ImagingConfig, error) { if m == nil { m = make(map[string]interface{}) } i := ImagingConfig{ Cfg: defaultImaging, CfgHash: helpers.HashString(m), } if err := mapstructure.WeakDecode(m, &i.Cfg); err != nil { return i, err } if err := i.Cfg.init(); err != nil { return i, err } var err error i.BgColor, err = hexStringToColor(i.Cfg.BgColor) if err != nil { return i, err } if i.Cfg.Anchor != "" && i.Cfg.Anchor != smartCropIdentifier { anchor, found := anchorPositions[i.Cfg.Anchor] if !found { return i, errors.Errorf("invalid anchor value %q in imaging config", i.Anchor) } i.Anchor = anchor } else { i.Cfg.Anchor = smartCropIdentifier } filter, found := imageFilters[i.Cfg.ResampleFilter] if !found { return i, fmt.Errorf("%q is not a valid resample filter", filter) } i.ResampleFilter = filter if strings.TrimSpace(i.Cfg.Exif.IncludeFields) == "" && strings.TrimSpace(i.Cfg.Exif.ExcludeFields) == "" { // Don't change this for no good reason. Please don't. i.Cfg.Exif.ExcludeFields = "GPS|Exif|Exposure[M|P|B]|Contrast|Resolution|Sharp|JPEG|Metering|Sensing|Saturation|ColorSpace|Flash|WhiteBalance" } return i, nil } func DecodeImageConfig(action, config string, defaults ImagingConfig, sourceFormat Format) (ImageConfig, error) { var ( c ImageConfig = GetDefaultImageConfig(action, defaults) err error ) c.Action = action if config == "" { return c, errors.New("image config cannot be empty") } parts := strings.Fields(config) for _, part := range parts { part = strings.ToLower(part) if part == smartCropIdentifier { c.AnchorStr = smartCropIdentifier } else if pos, ok := anchorPositions[part]; ok { c.Anchor = pos c.AnchorStr = part } else if filter, ok := imageFilters[part]; ok { c.Filter = filter c.FilterStr = part } else if hint, ok := hints[part]; ok { c.Hint = hint } else if part[0] == '#' { c.BgColorStr = part[1:] c.BgColor, err = hexStringToColor(c.BgColorStr) if err != nil { return c, err } } else if part[0] == 'q' { c.Quality, err = strconv.Atoi(part[1:]) if err != nil { return c, err } if c.Quality < 1 || c.Quality > 100 { return c, errors.New("quality ranges from 1 to 100 inclusive") } c.qualitySetForImage = true } else if part[0] == 'r' { c.Rotate, err = strconv.Atoi(part[1:]) if err != nil { return c, err } } else if strings.Contains(part, "x") { widthHeight := strings.Split(part, "x") if len(widthHeight) <= 2 { first := widthHeight[0] if first != "" { c.Width, err = strconv.Atoi(first) if err != nil { return c, err } } if len(widthHeight) == 2 { second := widthHeight[1] if second != "" { c.Height, err = strconv.Atoi(second) if err != nil { return c, err } } } } else { return c, errors.New("invalid image dimensions") } } else if f, ok := ImageFormatFromExt("." + part); ok { c.TargetFormat = f } } if c.Width == 0 && c.Height == 0 { return c, errors.New("must provide Width or Height") } if c.FilterStr == "" { c.FilterStr = defaults.Cfg.ResampleFilter c.Filter = defaults.ResampleFilter } if c.Hint == 0 { c.Hint = webpoptions.EncodingPresetPhoto } if c.AnchorStr == "" { c.AnchorStr = defaults.Cfg.Anchor c.Anchor = defaults.Anchor } // default to the source format if c.TargetFormat == 0 { c.TargetFormat = sourceFormat } if c.Quality <= 0 && c.TargetFormat.RequiresDefaultQuality() { // We need a quality setting for all JPEGs and WEBPs. c.Quality = defaults.Cfg.Quality } if c.BgColor == nil && c.TargetFormat != sourceFormat { if sourceFormat.SupportsTransparency() && !c.TargetFormat.SupportsTransparency() { c.BgColor = defaults.BgColor c.BgColorStr = defaults.Cfg.BgColor } } return c, nil } // ImageConfig holds configuration to create a new image from an existing one, resize etc. type ImageConfig struct { // This defines the output format of the output image. It defaults to the source format. TargetFormat Format Action string // If set, this will be used as the key in filenames etc. Key string // Quality ranges from 1 to 100 inclusive, higher is better. // This is only relevant for JPEG and WEBP images. // Default is 75. Quality int qualitySetForImage bool // Whether the above is set for this image. // Rotate rotates an image by the given angle counter-clockwise. // The rotation will be performed first. Rotate int // Used to fill any transparency. // When set in site config, it's used when converting to a format that does // not support transparency. // When set per image operation, it's used even for formats that does support // transparency. BgColor color.Color BgColorStr string // Hint about what type of picture this is. Used to optimize encoding // when target is set to webp. Hint webpoptions.EncodingPreset Width int Height int Filter gift.Resampling FilterStr string Anchor gift.Anchor AnchorStr string } func (i ImageConfig) GetKey(format Format) string { if i.Key != "" { return i.Action + "_" + i.Key } k := strconv.Itoa(i.Width) + "x" + strconv.Itoa(i.Height) if i.Action != "" { k += "_" + i.Action } // This slightly odd construct is here to preserve the old image keys. if i.qualitySetForImage || i.TargetFormat.RequiresDefaultQuality() { k += "_q" + strconv.Itoa(i.Quality) } if i.Rotate != 0 { k += "_r" + strconv.Itoa(i.Rotate) } if i.BgColorStr != "" { k += "_bg" + i.BgColorStr } if i.TargetFormat == WEBP { k += "_h" + strconv.Itoa(int(i.Hint)) } anchor := i.AnchorStr if anchor == smartCropIdentifier { anchor = anchor + strconv.Itoa(smartCropVersionNumber) } k += "_" + i.FilterStr if strings.EqualFold(i.Action, "fill") { k += "_" + anchor } if v, ok := imageFormatsVersions[format]; ok { k += "_" + strconv.Itoa(v) } if mainImageVersionNumber > 0 { k += "_" + strconv.Itoa(mainImageVersionNumber) } return k } type ImagingConfig struct { BgColor color.Color Hint webpoptions.EncodingPreset ResampleFilter gift.Resampling Anchor gift.Anchor // Config as provided by the user. Cfg Imaging // Hash of the config map provided by the user. CfgHash string } // Imaging contains default image processing configuration. This will be fetched // from site (or language) config. type Imaging struct { // Default image quality setting (1-100). Only used for JPEG images. Quality int // Resample filter to use in resize operations. ResampleFilter string // Hint about what type of image this is. // Currently only used when encoding to Webp. // Default is "photo". // Valid values are "picture", "photo", "drawing", "icon", or "text". Hint string // The anchor to use in Fill. Default is "smart", i.e. Smart Crop. Anchor string // Default color used in fill operations (e.g. "fff" for white). BgColor string Exif ExifConfig } func (cfg *Imaging) init() error { if cfg.Quality < 0 || cfg.Quality > 100 { return errors.New("image quality must be a number between 1 and 100") } cfg.BgColor = strings.ToLower(strings.TrimPrefix(cfg.BgColor, "#")) cfg.Anchor = strings.ToLower(cfg.Anchor) cfg.ResampleFilter = strings.ToLower(cfg.ResampleFilter) cfg.Hint = strings.ToLower(cfg.Hint) return nil } type ExifConfig struct { // Regexp matching the Exif fields you want from the (massive) set of Exif info // available. As we cache this info to disk, this is for performance and // disk space reasons more than anything. // If you want it all, put ".*" in this config setting. // Note that if neither this or ExcludeFields is set, Hugo will return a small // default set. IncludeFields string // Regexp matching the Exif fields you want to exclude. This may be easier to use // than IncludeFields above, depending on what you want. ExcludeFields string // Hugo extracts the "photo taken" date/time into .Date by default. // Set this to true to turn it off. DisableDate bool // Hugo extracts the "photo taken where" (GPS latitude and longitude) into // .Long and .Lat. Set this to true to turn it off. DisableLatLong bool }
jmooring
8a005538db5789e25ba2b092104b6cc53c6c1ece
a037be774d567c6a29cc7f10c94c9f746ca6d2aa
Well, we should also be able to process local files with `.jpe` and `.jfif` extensions, so I'll enable that. But yeah, with image/jpeg, it would nice to say "use the .jpg extension if an extension wasn't provided." So I'll do that too.
jmooring
133
gohugoio/hugo
9,278
Improve handling of remote image/jpeg resources
Closes #9275
null
2021-12-12 00:07:30+00:00
2021-12-13 07:55:15+00:00
resources/images/config.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 images import ( "fmt" "image/color" "strconv" "strings" "github.com/gohugoio/hugo/helpers" "github.com/pkg/errors" "github.com/bep/gowebp/libwebp/webpoptions" "github.com/disintegration/gift" "github.com/mitchellh/mapstructure" ) var ( imageFormats = map[string]Format{ ".jpg": JPEG, ".jpeg": JPEG, ".png": PNG, ".tif": TIFF, ".tiff": TIFF, ".bmp": BMP, ".gif": GIF, ".webp": WEBP, } // Add or increment if changes to an image format's processing requires // re-generation. imageFormatsVersions = map[Format]int{ PNG: 3, // Fix transparency issue with 32 bit images. WEBP: 2, // Fix transparency issue with 32 bit images. } // Increment to mark all processed images as stale. Only use when absolutely needed. // See the finer grained smartCropVersionNumber and imageFormatsVersions. mainImageVersionNumber = 0 ) var anchorPositions = map[string]gift.Anchor{ strings.ToLower("Center"): gift.CenterAnchor, strings.ToLower("TopLeft"): gift.TopLeftAnchor, strings.ToLower("Top"): gift.TopAnchor, strings.ToLower("TopRight"): gift.TopRightAnchor, strings.ToLower("Left"): gift.LeftAnchor, strings.ToLower("Right"): gift.RightAnchor, strings.ToLower("BottomLeft"): gift.BottomLeftAnchor, strings.ToLower("Bottom"): gift.BottomAnchor, strings.ToLower("BottomRight"): gift.BottomRightAnchor, } // These encoding hints are currently only relevant for Webp. var hints = map[string]webpoptions.EncodingPreset{ "picture": webpoptions.EncodingPresetPicture, "photo": webpoptions.EncodingPresetPhoto, "drawing": webpoptions.EncodingPresetDrawing, "icon": webpoptions.EncodingPresetIcon, "text": webpoptions.EncodingPresetText, } var imageFilters = map[string]gift.Resampling{ strings.ToLower("NearestNeighbor"): gift.NearestNeighborResampling, strings.ToLower("Box"): gift.BoxResampling, strings.ToLower("Linear"): gift.LinearResampling, strings.ToLower("Hermite"): hermiteResampling, strings.ToLower("MitchellNetravali"): mitchellNetravaliResampling, strings.ToLower("CatmullRom"): catmullRomResampling, strings.ToLower("BSpline"): bSplineResampling, strings.ToLower("Gaussian"): gaussianResampling, strings.ToLower("Lanczos"): gift.LanczosResampling, strings.ToLower("Hann"): hannResampling, strings.ToLower("Hamming"): hammingResampling, strings.ToLower("Blackman"): blackmanResampling, strings.ToLower("Bartlett"): bartlettResampling, strings.ToLower("Welch"): welchResampling, strings.ToLower("Cosine"): cosineResampling, } func ImageFormatFromExt(ext string) (Format, bool) { f, found := imageFormats[ext] return f, found } const ( defaultJPEGQuality = 75 defaultResampleFilter = "box" defaultBgColor = "ffffff" defaultHint = "photo" ) var defaultImaging = Imaging{ ResampleFilter: defaultResampleFilter, BgColor: defaultBgColor, Hint: defaultHint, Quality: defaultJPEGQuality, } func DecodeConfig(m map[string]interface{}) (ImagingConfig, error) { if m == nil { m = make(map[string]interface{}) } i := ImagingConfig{ Cfg: defaultImaging, CfgHash: helpers.HashString(m), } if err := mapstructure.WeakDecode(m, &i.Cfg); err != nil { return i, err } if err := i.Cfg.init(); err != nil { return i, err } var err error i.BgColor, err = hexStringToColor(i.Cfg.BgColor) if err != nil { return i, err } if i.Cfg.Anchor != "" && i.Cfg.Anchor != smartCropIdentifier { anchor, found := anchorPositions[i.Cfg.Anchor] if !found { return i, errors.Errorf("invalid anchor value %q in imaging config", i.Anchor) } i.Anchor = anchor } else { i.Cfg.Anchor = smartCropIdentifier } filter, found := imageFilters[i.Cfg.ResampleFilter] if !found { return i, fmt.Errorf("%q is not a valid resample filter", filter) } i.ResampleFilter = filter if strings.TrimSpace(i.Cfg.Exif.IncludeFields) == "" && strings.TrimSpace(i.Cfg.Exif.ExcludeFields) == "" { // Don't change this for no good reason. Please don't. i.Cfg.Exif.ExcludeFields = "GPS|Exif|Exposure[M|P|B]|Contrast|Resolution|Sharp|JPEG|Metering|Sensing|Saturation|ColorSpace|Flash|WhiteBalance" } return i, nil } func DecodeImageConfig(action, config string, defaults ImagingConfig, sourceFormat Format) (ImageConfig, error) { var ( c ImageConfig = GetDefaultImageConfig(action, defaults) err error ) c.Action = action if config == "" { return c, errors.New("image config cannot be empty") } parts := strings.Fields(config) for _, part := range parts { part = strings.ToLower(part) if part == smartCropIdentifier { c.AnchorStr = smartCropIdentifier } else if pos, ok := anchorPositions[part]; ok { c.Anchor = pos c.AnchorStr = part } else if filter, ok := imageFilters[part]; ok { c.Filter = filter c.FilterStr = part } else if hint, ok := hints[part]; ok { c.Hint = hint } else if part[0] == '#' { c.BgColorStr = part[1:] c.BgColor, err = hexStringToColor(c.BgColorStr) if err != nil { return c, err } } else if part[0] == 'q' { c.Quality, err = strconv.Atoi(part[1:]) if err != nil { return c, err } if c.Quality < 1 || c.Quality > 100 { return c, errors.New("quality ranges from 1 to 100 inclusive") } c.qualitySetForImage = true } else if part[0] == 'r' { c.Rotate, err = strconv.Atoi(part[1:]) if err != nil { return c, err } } else if strings.Contains(part, "x") { widthHeight := strings.Split(part, "x") if len(widthHeight) <= 2 { first := widthHeight[0] if first != "" { c.Width, err = strconv.Atoi(first) if err != nil { return c, err } } if len(widthHeight) == 2 { second := widthHeight[1] if second != "" { c.Height, err = strconv.Atoi(second) if err != nil { return c, err } } } } else { return c, errors.New("invalid image dimensions") } } else if f, ok := ImageFormatFromExt("." + part); ok { c.TargetFormat = f } } if c.Width == 0 && c.Height == 0 { return c, errors.New("must provide Width or Height") } if c.FilterStr == "" { c.FilterStr = defaults.Cfg.ResampleFilter c.Filter = defaults.ResampleFilter } if c.Hint == 0 { c.Hint = webpoptions.EncodingPresetPhoto } if c.AnchorStr == "" { c.AnchorStr = defaults.Cfg.Anchor c.Anchor = defaults.Anchor } // default to the source format if c.TargetFormat == 0 { c.TargetFormat = sourceFormat } if c.Quality <= 0 && c.TargetFormat.RequiresDefaultQuality() { // We need a quality setting for all JPEGs and WEBPs. c.Quality = defaults.Cfg.Quality } if c.BgColor == nil && c.TargetFormat != sourceFormat { if sourceFormat.SupportsTransparency() && !c.TargetFormat.SupportsTransparency() { c.BgColor = defaults.BgColor c.BgColorStr = defaults.Cfg.BgColor } } return c, nil } // ImageConfig holds configuration to create a new image from an existing one, resize etc. type ImageConfig struct { // This defines the output format of the output image. It defaults to the source format. TargetFormat Format Action string // If set, this will be used as the key in filenames etc. Key string // Quality ranges from 1 to 100 inclusive, higher is better. // This is only relevant for JPEG and WEBP images. // Default is 75. Quality int qualitySetForImage bool // Whether the above is set for this image. // Rotate rotates an image by the given angle counter-clockwise. // The rotation will be performed first. Rotate int // Used to fill any transparency. // When set in site config, it's used when converting to a format that does // not support transparency. // When set per image operation, it's used even for formats that does support // transparency. BgColor color.Color BgColorStr string // Hint about what type of picture this is. Used to optimize encoding // when target is set to webp. Hint webpoptions.EncodingPreset Width int Height int Filter gift.Resampling FilterStr string Anchor gift.Anchor AnchorStr string } func (i ImageConfig) GetKey(format Format) string { if i.Key != "" { return i.Action + "_" + i.Key } k := strconv.Itoa(i.Width) + "x" + strconv.Itoa(i.Height) if i.Action != "" { k += "_" + i.Action } // This slightly odd construct is here to preserve the old image keys. if i.qualitySetForImage || i.TargetFormat.RequiresDefaultQuality() { k += "_q" + strconv.Itoa(i.Quality) } if i.Rotate != 0 { k += "_r" + strconv.Itoa(i.Rotate) } if i.BgColorStr != "" { k += "_bg" + i.BgColorStr } if i.TargetFormat == WEBP { k += "_h" + strconv.Itoa(int(i.Hint)) } anchor := i.AnchorStr if anchor == smartCropIdentifier { anchor = anchor + strconv.Itoa(smartCropVersionNumber) } k += "_" + i.FilterStr if strings.EqualFold(i.Action, "fill") { k += "_" + anchor } if v, ok := imageFormatsVersions[format]; ok { k += "_" + strconv.Itoa(v) } if mainImageVersionNumber > 0 { k += "_" + strconv.Itoa(mainImageVersionNumber) } return k } type ImagingConfig struct { BgColor color.Color Hint webpoptions.EncodingPreset ResampleFilter gift.Resampling Anchor gift.Anchor // Config as provided by the user. Cfg Imaging // Hash of the config map provided by the user. CfgHash string } // Imaging contains default image processing configuration. This will be fetched // from site (or language) config. type Imaging struct { // Default image quality setting (1-100). Only used for JPEG images. Quality int // Resample filter to use in resize operations. ResampleFilter string // Hint about what type of image this is. // Currently only used when encoding to Webp. // Default is "photo". // Valid values are "picture", "photo", "drawing", "icon", or "text". Hint string // The anchor to use in Fill. Default is "smart", i.e. Smart Crop. Anchor string // Default color used in fill operations (e.g. "fff" for white). BgColor string Exif ExifConfig } func (cfg *Imaging) init() error { if cfg.Quality < 0 || cfg.Quality > 100 { return errors.New("image quality must be a number between 1 and 100") } cfg.BgColor = strings.ToLower(strings.TrimPrefix(cfg.BgColor, "#")) cfg.Anchor = strings.ToLower(cfg.Anchor) cfg.ResampleFilter = strings.ToLower(cfg.ResampleFilter) cfg.Hint = strings.ToLower(cfg.Hint) return nil } type ExifConfig struct { // Regexp matching the Exif fields you want from the (massive) set of Exif info // available. As we cache this info to disk, this is for performance and // disk space reasons more than anything. // If you want it all, put ".*" in this config setting. // Note that if neither this or ExcludeFields is set, Hugo will return a small // default set. IncludeFields string // Regexp matching the Exif fields you want to exclude. This may be easier to use // than IncludeFields above, depending on what you want. ExcludeFields string // Hugo extracts the "photo taken" date/time into .Date by default. // Set this to true to turn it off. DisableDate bool // Hugo extracts the "photo taken where" (GPS latitude and longitude) into // .Long and .Lat. Set this to true to turn it off. DisableLatLong bool }
// 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 images import ( "fmt" "image/color" "strconv" "strings" "github.com/gohugoio/hugo/helpers" "github.com/pkg/errors" "github.com/bep/gowebp/libwebp/webpoptions" "github.com/disintegration/gift" "github.com/mitchellh/mapstructure" ) var ( imageFormats = map[string]Format{ ".jpg": JPEG, ".jpeg": JPEG, ".jpe": JPEG, ".jif": JPEG, ".jfif": JPEG, ".png": PNG, ".tif": TIFF, ".tiff": TIFF, ".bmp": BMP, ".gif": GIF, ".webp": WEBP, } // Add or increment if changes to an image format's processing requires // re-generation. imageFormatsVersions = map[Format]int{ PNG: 3, // Fix transparency issue with 32 bit images. WEBP: 2, // Fix transparency issue with 32 bit images. } // Increment to mark all processed images as stale. Only use when absolutely needed. // See the finer grained smartCropVersionNumber and imageFormatsVersions. mainImageVersionNumber = 0 ) var anchorPositions = map[string]gift.Anchor{ strings.ToLower("Center"): gift.CenterAnchor, strings.ToLower("TopLeft"): gift.TopLeftAnchor, strings.ToLower("Top"): gift.TopAnchor, strings.ToLower("TopRight"): gift.TopRightAnchor, strings.ToLower("Left"): gift.LeftAnchor, strings.ToLower("Right"): gift.RightAnchor, strings.ToLower("BottomLeft"): gift.BottomLeftAnchor, strings.ToLower("Bottom"): gift.BottomAnchor, strings.ToLower("BottomRight"): gift.BottomRightAnchor, } // These encoding hints are currently only relevant for Webp. var hints = map[string]webpoptions.EncodingPreset{ "picture": webpoptions.EncodingPresetPicture, "photo": webpoptions.EncodingPresetPhoto, "drawing": webpoptions.EncodingPresetDrawing, "icon": webpoptions.EncodingPresetIcon, "text": webpoptions.EncodingPresetText, } var imageFilters = map[string]gift.Resampling{ strings.ToLower("NearestNeighbor"): gift.NearestNeighborResampling, strings.ToLower("Box"): gift.BoxResampling, strings.ToLower("Linear"): gift.LinearResampling, strings.ToLower("Hermite"): hermiteResampling, strings.ToLower("MitchellNetravali"): mitchellNetravaliResampling, strings.ToLower("CatmullRom"): catmullRomResampling, strings.ToLower("BSpline"): bSplineResampling, strings.ToLower("Gaussian"): gaussianResampling, strings.ToLower("Lanczos"): gift.LanczosResampling, strings.ToLower("Hann"): hannResampling, strings.ToLower("Hamming"): hammingResampling, strings.ToLower("Blackman"): blackmanResampling, strings.ToLower("Bartlett"): bartlettResampling, strings.ToLower("Welch"): welchResampling, strings.ToLower("Cosine"): cosineResampling, } func ImageFormatFromExt(ext string) (Format, bool) { f, found := imageFormats[ext] return f, found } const ( defaultJPEGQuality = 75 defaultResampleFilter = "box" defaultBgColor = "ffffff" defaultHint = "photo" ) var defaultImaging = Imaging{ ResampleFilter: defaultResampleFilter, BgColor: defaultBgColor, Hint: defaultHint, Quality: defaultJPEGQuality, } func DecodeConfig(m map[string]interface{}) (ImagingConfig, error) { if m == nil { m = make(map[string]interface{}) } i := ImagingConfig{ Cfg: defaultImaging, CfgHash: helpers.HashString(m), } if err := mapstructure.WeakDecode(m, &i.Cfg); err != nil { return i, err } if err := i.Cfg.init(); err != nil { return i, err } var err error i.BgColor, err = hexStringToColor(i.Cfg.BgColor) if err != nil { return i, err } if i.Cfg.Anchor != "" && i.Cfg.Anchor != smartCropIdentifier { anchor, found := anchorPositions[i.Cfg.Anchor] if !found { return i, errors.Errorf("invalid anchor value %q in imaging config", i.Anchor) } i.Anchor = anchor } else { i.Cfg.Anchor = smartCropIdentifier } filter, found := imageFilters[i.Cfg.ResampleFilter] if !found { return i, fmt.Errorf("%q is not a valid resample filter", filter) } i.ResampleFilter = filter if strings.TrimSpace(i.Cfg.Exif.IncludeFields) == "" && strings.TrimSpace(i.Cfg.Exif.ExcludeFields) == "" { // Don't change this for no good reason. Please don't. i.Cfg.Exif.ExcludeFields = "GPS|Exif|Exposure[M|P|B]|Contrast|Resolution|Sharp|JPEG|Metering|Sensing|Saturation|ColorSpace|Flash|WhiteBalance" } return i, nil } func DecodeImageConfig(action, config string, defaults ImagingConfig, sourceFormat Format) (ImageConfig, error) { var ( c ImageConfig = GetDefaultImageConfig(action, defaults) err error ) c.Action = action if config == "" { return c, errors.New("image config cannot be empty") } parts := strings.Fields(config) for _, part := range parts { part = strings.ToLower(part) if part == smartCropIdentifier { c.AnchorStr = smartCropIdentifier } else if pos, ok := anchorPositions[part]; ok { c.Anchor = pos c.AnchorStr = part } else if filter, ok := imageFilters[part]; ok { c.Filter = filter c.FilterStr = part } else if hint, ok := hints[part]; ok { c.Hint = hint } else if part[0] == '#' { c.BgColorStr = part[1:] c.BgColor, err = hexStringToColor(c.BgColorStr) if err != nil { return c, err } } else if part[0] == 'q' { c.Quality, err = strconv.Atoi(part[1:]) if err != nil { return c, err } if c.Quality < 1 || c.Quality > 100 { return c, errors.New("quality ranges from 1 to 100 inclusive") } c.qualitySetForImage = true } else if part[0] == 'r' { c.Rotate, err = strconv.Atoi(part[1:]) if err != nil { return c, err } } else if strings.Contains(part, "x") { widthHeight := strings.Split(part, "x") if len(widthHeight) <= 2 { first := widthHeight[0] if first != "" { c.Width, err = strconv.Atoi(first) if err != nil { return c, err } } if len(widthHeight) == 2 { second := widthHeight[1] if second != "" { c.Height, err = strconv.Atoi(second) if err != nil { return c, err } } } } else { return c, errors.New("invalid image dimensions") } } else if f, ok := ImageFormatFromExt("." + part); ok { c.TargetFormat = f } } if c.Width == 0 && c.Height == 0 { return c, errors.New("must provide Width or Height") } if c.FilterStr == "" { c.FilterStr = defaults.Cfg.ResampleFilter c.Filter = defaults.ResampleFilter } if c.Hint == 0 { c.Hint = webpoptions.EncodingPresetPhoto } if c.AnchorStr == "" { c.AnchorStr = defaults.Cfg.Anchor c.Anchor = defaults.Anchor } // default to the source format if c.TargetFormat == 0 { c.TargetFormat = sourceFormat } if c.Quality <= 0 && c.TargetFormat.RequiresDefaultQuality() { // We need a quality setting for all JPEGs and WEBPs. c.Quality = defaults.Cfg.Quality } if c.BgColor == nil && c.TargetFormat != sourceFormat { if sourceFormat.SupportsTransparency() && !c.TargetFormat.SupportsTransparency() { c.BgColor = defaults.BgColor c.BgColorStr = defaults.Cfg.BgColor } } return c, nil } // ImageConfig holds configuration to create a new image from an existing one, resize etc. type ImageConfig struct { // This defines the output format of the output image. It defaults to the source format. TargetFormat Format Action string // If set, this will be used as the key in filenames etc. Key string // Quality ranges from 1 to 100 inclusive, higher is better. // This is only relevant for JPEG and WEBP images. // Default is 75. Quality int qualitySetForImage bool // Whether the above is set for this image. // Rotate rotates an image by the given angle counter-clockwise. // The rotation will be performed first. Rotate int // Used to fill any transparency. // When set in site config, it's used when converting to a format that does // not support transparency. // When set per image operation, it's used even for formats that does support // transparency. BgColor color.Color BgColorStr string // Hint about what type of picture this is. Used to optimize encoding // when target is set to webp. Hint webpoptions.EncodingPreset Width int Height int Filter gift.Resampling FilterStr string Anchor gift.Anchor AnchorStr string } func (i ImageConfig) GetKey(format Format) string { if i.Key != "" { return i.Action + "_" + i.Key } k := strconv.Itoa(i.Width) + "x" + strconv.Itoa(i.Height) if i.Action != "" { k += "_" + i.Action } // This slightly odd construct is here to preserve the old image keys. if i.qualitySetForImage || i.TargetFormat.RequiresDefaultQuality() { k += "_q" + strconv.Itoa(i.Quality) } if i.Rotate != 0 { k += "_r" + strconv.Itoa(i.Rotate) } if i.BgColorStr != "" { k += "_bg" + i.BgColorStr } if i.TargetFormat == WEBP { k += "_h" + strconv.Itoa(int(i.Hint)) } anchor := i.AnchorStr if anchor == smartCropIdentifier { anchor = anchor + strconv.Itoa(smartCropVersionNumber) } k += "_" + i.FilterStr if strings.EqualFold(i.Action, "fill") { k += "_" + anchor } if v, ok := imageFormatsVersions[format]; ok { k += "_" + strconv.Itoa(v) } if mainImageVersionNumber > 0 { k += "_" + strconv.Itoa(mainImageVersionNumber) } return k } type ImagingConfig struct { BgColor color.Color Hint webpoptions.EncodingPreset ResampleFilter gift.Resampling Anchor gift.Anchor // Config as provided by the user. Cfg Imaging // Hash of the config map provided by the user. CfgHash string } // Imaging contains default image processing configuration. This will be fetched // from site (or language) config. type Imaging struct { // Default image quality setting (1-100). Only used for JPEG images. Quality int // Resample filter to use in resize operations. ResampleFilter string // Hint about what type of image this is. // Currently only used when encoding to Webp. // Default is "photo". // Valid values are "picture", "photo", "drawing", "icon", or "text". Hint string // The anchor to use in Fill. Default is "smart", i.e. Smart Crop. Anchor string // Default color used in fill operations (e.g. "fff" for white). BgColor string Exif ExifConfig } func (cfg *Imaging) init() error { if cfg.Quality < 0 || cfg.Quality > 100 { return errors.New("image quality must be a number between 1 and 100") } cfg.BgColor = strings.ToLower(strings.TrimPrefix(cfg.BgColor, "#")) cfg.Anchor = strings.ToLower(cfg.Anchor) cfg.ResampleFilter = strings.ToLower(cfg.ResampleFilter) cfg.Hint = strings.ToLower(cfg.Hint) return nil } type ExifConfig struct { // Regexp matching the Exif fields you want from the (massive) set of Exif info // available. As we cache this info to disk, this is for performance and // disk space reasons more than anything. // If you want it all, put ".*" in this config setting. // Note that if neither this or ExcludeFields is set, Hugo will return a small // default set. IncludeFields string // Regexp matching the Exif fields you want to exclude. This may be easier to use // than IncludeFields above, depending on what you want. ExcludeFields string // Hugo extracts the "photo taken" date/time into .Date by default. // Set this to true to turn it off. DisableDate bool // Hugo extracts the "photo taken where" (GPS latitude and longitude) into // .Long and .Lat. Set this to true to turn it off. DisableLatLong bool }
jmooring
8a005538db5789e25ba2b092104b6cc53c6c1ece
a037be774d567c6a29cc7f10c94c9f746ca6d2aa
OK
bep
134
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
docs/content/en/functions/images/index.md
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Text Using the `Text` filter, you can add text to an image. {{% funcsig %}} images.Text TEXT DICT) {{% /funcsig %}} The following example will add the text `Hugo rocks!` to the image with the specified color, size and position. ``` {{ $img := resources.Get "/images/background.png"}} {{ $img = $img.Filter (images.Text "Hugo rocks!" (dict "color" "#ffffff" "size" 60 "linespacing" 2 "x" 10 "y" 20 ))}} ``` ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
I suggest we release first version without custom font support.
bep
135
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
docs/content/en/functions/images/index.md
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Text Using the `Text` filter, you can add text to an image. {{% funcsig %}} images.Text TEXT DICT) {{% /funcsig %}} The following example will add the text `Hugo rocks!` to the image with the specified color, size and position. ``` {{ $img := resources.Get "/images/background.png"}} {{ $img = $img.Filter (images.Text "Hugo rocks!" (dict "color" "#ffffff" "size" 60 "linespacing" 2 "x" 10 "y" 20 ))}} ``` ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
I may have given conflicting feedback re font -- and we can take that in its own separate feature -- but I now think this would be really useful. But see my comment re. hash key.
bep
136
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
docs/content/en/functions/images/index.md
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Text Using the `Text` filter, you can add text to an image. {{% funcsig %}} images.Text TEXT DICT) {{% /funcsig %}} The following example will add the text `Hugo rocks!` to the image with the specified color, size and position. ``` {{ $img := resources.Get "/images/background.png"}} {{ $img = $img.Filter (images.Text "Hugo rocks!" (dict "color" "#ffffff" "size" 60 "linespacing" 2 "x" 10 "y" 20 ))}} ``` ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
Do you want to include font support for this PR or work that feature out in a separate PR? If we implement fonts, we need to make sure that the pipeline and font is cached between build/restart. Using resources.Get we utilize the existing logic, for local and remote fonts, including the resource cache. I'm not 100% sure about the pipeline cache, during testing, I had to make changes to the pipeline (even after a restart) to see the changes, but I can imagine that the resource pointer is unpredictable. I also thought about passing the resource location instead and call the resources get internally but that would cause an import loop.
vanbroup
137
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
docs/content/en/functions/images/index.md
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Text Using the `Text` filter, you can add text to an image. {{% funcsig %}} images.Text TEXT DICT) {{% /funcsig %}} The following example will add the text `Hugo rocks!` to the image with the specified color, size and position. ``` {{ $img := resources.Get "/images/background.png"}} {{ $img = $img.Filter (images.Text "Hugo rocks!" (dict "color" "#ffffff" "size" 60 "linespacing" 2 "x" 10 "y" 20 ))}} ``` ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
On the hash key, I suppose you refer to [image.go#L237](https://github.com/gohugoio/hugo/blob/master/resources/image.go#L237)? What do you mean with: > Replace the font in options with font.Key (there is an interface) If we want to use resources.Get to support local and remote fonts, I need to pass the resource at some point.
vanbroup
138
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
docs/content/en/functions/images/index.md
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
--- title: Image Functions description: The images namespace provides a list of filters and other image related functions. date: 2017-02-01 categories: [functions] aliases: [/functions/imageconfig/] menu: docs: parent: "functions" keywords: [images] toc: true --- ## Image Filters See [images.Filter](#filter) for how to apply these filters to an image. ### Overlay {{< new-in "0.80.0" >}} {{% funcsig %}} images.Overlay SRC X Y {{% /funcsig %}} Overlay creates a filter that overlays the source image at position x y, e.g: ```go-html-template {{ $logoFilter := (images.Overlay $logo 50 50 ) }} {{ $img := $img | images.Filter $logoFilter }} ``` A shorter version of the above, if you only need to apply the filter once: ```go-html-template {{ $img := $img.Filter (images.Overlay $logo 50 50 )}} ``` The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`). ### Text Using the `Text` filter, you can add text to an image. {{% funcsig %}} images.Text TEXT DICT) {{% /funcsig %}} The following example will add the text `Hugo rocks!` to the image with the specified color, size and position. ``` {{ $img := resources.Get "/images/background.png"}} {{ $img = $img.Filter (images.Text "Hugo rocks!" (dict "color" "#ffffff" "size" 60 "linespacing" 2 "x" 10 "y" 20 ))}} ``` ### Brightness {{% funcsig %}} images.Brightness PERCENTAGE {{% /funcsig %}} Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). ### ColorBalance {{% funcsig %}} images.ColorBalance PERCENTAGERED PERCENTAGEGREEN PERCENTAGEBLUE {{% /funcsig %}} ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). ### Colorize {{% funcsig %}} images.Colorize HUE SATURATION PERCENTAGE {{% /funcsig %}} Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100). ### Contrast {{% funcsig %}} images.Contrast PERCENTAGE {{% /funcsig %}} Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). ### Gamma {{% funcsig %}} images.Gamma GAMMA {{% /funcsig %}} Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 lightens it. ### GaussianBlur {{% funcsig %}} images.GaussianBlur SIGMA {{% /funcsig %}} GaussianBlur creates a filter that applies a gaussian blur to an image. ### Grayscale {{% funcsig %}} images.Grayscale {{% /funcsig %}} Grayscale creates a filter that produces a grayscale version of an image. ### Hue {{% funcsig %}} images.Hue SHIFT {{% /funcsig %}} Hue creates a filter that rotates the hue of an image. The hue angle shift is typically in range -180 to 180. ### Invert {{% funcsig %}} images.Invert {{% /funcsig %}} Invert creates a filter that negates the colors of an image. ### Pixelate {{% funcsig %}} images.Pixelate SIZE {{% /funcsig %}} Pixelate creates a filter that applies a pixelation effect to an image. ### Saturation {{% funcsig %}} images.Saturation PERCENTAGE {{% /funcsig %}} Saturation creates a filter that changes the saturation of an image. ### Sepia {{% funcsig %}} images.Sepia PERCENTAGE {{% /funcsig %}} Sepia creates a filter that produces a sepia-toned version of an image. ### Sigmoid {{% funcsig %}} images.Sigmoid MIDPOINT FACTOR {{% /funcsig %}} Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. ### UnsharpMask {{% funcsig %}} images.UnsharpMask SIGMA AMOUNT THRESHOLD {{% /funcsig %}} UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. ## Other Functions ### Filter {{% funcsig %}} IMAGE | images.Filter FILTERS... {{% /funcsig %}} Can be used to apply a set of filters to an image: ```go-html-template {{ $img := $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} ``` Also see the [Filter Method](/content-management/image-processing/#filter). ### ImageConfig Parses the image and returns the height, width, and color model. {{% funcsig %}} images.ImageConfig PATH {{% /funcsig %}} ```go-html-template {{ with (imageConfig "favicon.ico") }} favicon.ico: {{.Width}} x {{.Height}} {{ end }} ```
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
There is a more complex story to this, but the short story is: * If you do what you did and pass the `Resource` (as in: what you get in `resources.Get` etc.) as an option, the caching is in place. * But, and this is important, you need to make sure that what you create in `HashString` is stable -- which is why I made the comment about: 1. First pull the font from the map. 2. Then replace `font` in the map with `fontResource.Key()` (there is an interface). 3. Then use that map to create the hash. You can do the above in its own PR if you want, or just apply that change to this, if that is most effective.
bep
139
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
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 import ( "fmt" "image" "io/ioutil" "math/big" "math/rand" "os" "path" "path/filepath" "runtime" "strconv" "sync" "testing" "time" "github.com/gohugoio/hugo/resources/images/webp" "github.com/gohugoio/hugo/common/paths" "github.com/spf13/afero" "github.com/disintegration/gift" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/resource" "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 *resourceAdapter) bool { return p1.resourceAdapterInner == p2.resourceAdapterInner }), cmp.Comparer(func(p1, p2 os.FileInfo) bool { 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 *big.Rat) bool { return v1.RatString() == v2.RatString() }, ), 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) fileCache := image.(specProvider).getSpec().FileCaches.ImageCache().Fs assertWidthHeight := func(img resource.Image, 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) } 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) c.Assert(image, qt.Not(eq), resized) assertWidthHeight(resized, 300, 200) assertWidthHeight(image, 900, 562) resized0x, err := image.Resize("x200") c.Assert(err, qt.IsNil) assertWidthHeight(resized0x, 320, 200) assertFileCache(c, fileCache, path.Base(resized0x.RelPermalink()), 320, 200) resizedx0, err := image.Resize("200x") c.Assert(err, qt.IsNil) assertWidthHeight(resizedx0, 200, 125) assertFileCache(c, fileCache, path.Base(resizedx0.RelPermalink()), 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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_300x200_resize_q68_linear.jpg") fitted, err := resized.Fit("50x50") c.Assert(err, qt.IsNil) c.Assert(fitted.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_625708021e2bb281c9f1002f88e4753f.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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_3f65ba24dc2b7fba0f56d7f104519157.jpg") assertWidthHeight(fittedAgain, 10, 7) filled, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x100_fill_q68_linear_bottomleft.jpg") assertWidthHeight(filled, 200, 100) smart, err := image.Fill("200x100 smart") c.Assert(err, qt.IsNil) c.Assert(smart.RelPermalink(), qt.Equals, fmt.Sprintf("/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x100_fill_q68_linear_smart%d.jpg", 1)) assertWidthHeight(smart, 200, 100) // Check cache filledAgain, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled, eq, filledAgain) } func TestImageTransformFormat(t *testing.T) { c := qt.New(t) image := fetchSunset(c) fileCache := image.(specProvider).getSpec().FileCaches.ImageCache().Fs assertExtWidthHeight := func(img resource.Image, 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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_450x0_resize_linear.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") assertFileCache(c, fileCache, path.Base(imagePng.RelPermalink()), 450, 281) imageGif, err := image.Resize("225x gif") c.Assert(err, qt.IsNil) c.Assert(imageGif.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_225x0_resize_linear.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") assertFileCache(c, fileCache, path.Base(imageGif.RelPermalink()), 225, 141) } // 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 resource.Image) { resizedLink := "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_100x50_resize_q75_box.jpg" c.Assert(img.RelPermalink(), qt.Equals, resizedLink) assertImageFile(c, spec.PublishFs, resizedLink, 100, 50) } check2 := func(img resource.Image) { c.Assert(img.RelPermalink(), qt.Equals, "/a/sunset.jpg") assertImageFile(c, spec.PublishFs, "a/sunset.jpg", 900, 562) } orignal := fetchImageForSpec(spec, c, "sunset.jpg") c.Assert(orignal, qt.Not(qt.IsNil)) if checkOriginalFirst { check2(orignal) } resized, err := orignal.Resize("100x50") c.Assert(err, qt.IsNil) check1(resized.(resource.Image)) if !checkOriginalFirst { check2(orignal) } }) } } 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/_hu59e56ffff1bc1d8d122b1403d34e039f_90587_65b757a6e14debeae720fe8831f0a9bc.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/_hu59e56ffff1bc1d8d122b1403d34e039f_90587_c876768085288f41211f768147ba2647.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 := 0; i < 4; i++ { wg.Add(1) go func(id int) { defer wg.Done() for j := 0; j < 5; j++ { img := image for k := 0; k < 2; k++ { 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 TestImageWithMetadata(t *testing.T) { c := qt.New(t) image := fetchSunset(c) meta := []map[string]interface{}{ { "title": "My Sunset", "name": "Sunset #:counter", "src": "*.jpg", }, } c.Assert(AssignMetadata(meta, image), qt.IsNil) c.Assert(image.Name(), qt.Equals, "Sunset #1") resized, err := image.Resize("200x") c.Assert(err, qt.IsNil) c.Assert(resized.Name(), qt.Equals, "Sunset #1") } 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.IsNil) 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_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_800x0_resize_linear_3.png") c.Assert(resized.Width(), qt.Equals, 800) } func TestImageResizeInSubPath(t *testing.T) { c := qt.New(t) image := fetchImage(c, "sub/gohugoio2.png") c.Assert(image.MediaType(), eq, media.PNGType) c.Assert(image.RelPermalink(), qt.Equals, "/a/sub/gohugoio2.png") c.Assert(image.ResourceType(), qt.Equals, "image") c.Assert(image.Exif(), qt.IsNil) resized, err := image.Resize("101x101") c.Assert(err, qt.IsNil) c.Assert(resized.MediaType().Type(), qt.Equals, "image/png") c.Assert(resized.RelPermalink(), qt.Equals, "/a/sub/gohugoio2_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_101x101_resize_linear_3.png") c.Assert(resized.Width(), qt.Equals, 101) c.Assert(resized.Exif(), qt.IsNil) publishedImageFilename := filepath.Clean(resized.RelPermalink()) spec := image.(specProvider).getSpec() assertImageFile(c, spec.BaseFs.PublishFs, publishedImageFilename, 101, 101) c.Assert(spec.BaseFs.PublishFs.Remove(publishedImageFilename), qt.IsNil) // Clear mem cache to simulate reading from the file cache. spec.imageCache.clear() resizedAgain, err := image.Resize("101x101") c.Assert(err, qt.IsNil) c.Assert(resizedAgain.RelPermalink(), qt.Equals, "/a/sub/gohugoio2_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_101x101_resize_linear_3.png") c.Assert(resizedAgain.Width(), qt.Equals, 101) assertImageFile(c, image.(specProvider).getSpec().BaseFs.PublishFs, publishedImageFilename, 101, 101) } 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() 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").(resource.Image) getAndCheckExif := func(c *qt.C, image resource.Image) { 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").(resource.Image) // This will read from file cache. getAndCheckExif(c, image) } func BenchmarkImageExif(b *testing.B) { getImages := func(c *qt.C, b *testing.B, fs afero.Fs) []resource.Image { spec := newTestResourceSpec(specDescriptor{fs: fs, c: c}) images := make([]resource.Image, b.N) for i := 0; i < b.N; i++ { images[i] = fetchResourceForSpec(spec, c, "sunset.jpg", strconv.Itoa(i)).(resource.Image) } return images } getAndCheckExif := func(c *qt.C, image resource.Image) { 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) { b.StopTimer() c := qt.New(b) images := getImages(c, b, afero.NewMemMapFs()) b.StartTimer() for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } }) b.Run("Cold cache, 10", func(b *testing.B) { b.StopTimer() c := qt.New(b) images := getImages(c, b, afero.NewMemMapFs()) b.StartTimer() for i := 0; i < b.N; i++ { for j := 0; j < 10; j++ { getAndCheckExif(c, images[i]) } } }) b.Run("Warm cache", func(b *testing.B) { b.StopTimer() c := qt.New(b) fs := afero.NewMemMapFs() images := getImages(c, b, fs) for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } images = getImages(c, b, fs) b.StartTimer() for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } }) } // usesFMA indicates whether "fused multiply and add" (FMA) instruction is // used. The command "grep FMADD go/test/codegen/floats.go" can help keep // the FMA-using architecture list updated. var usesFMA = runtime.GOARCH == "s390x" || runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" || runtime.GOARCH == "arm64" // goldenEqual compares two NRGBA images. It is used in golden tests only. // A small tolerance is allowed on architectures using "fused multiply and add" // (FMA) instruction to accommodate for floating-point rounding differences // with control golden images that were generated on amd64 architecture. // See https://golang.org/ref/spec#Floating_point_operators // and https://github.com/gohugoio/hugo/issues/6387 for more information. // // Borrowed from https://github.com/disintegration/gift/blob/a999ff8d5226e5ab14b64a94fca07c4ac3f357cf/gift_test.go#L598-L625 // Copyright (c) 2014-2019 Grigory Dryapak // Licensed under the MIT License. func goldenEqual(img1, img2 *image.NRGBA) bool { maxDiff := 0 if usesFMA { maxDiff = 1 } if !img1.Rect.Eq(img2.Rect) { return false } if len(img1.Pix) != len(img2.Pix) { return false } for i := 0; i < len(img1.Pix); i++ { diff := int(img1.Pix[i]) - int(img2.Pix[i]) if diff < 0 { diff = -diff } if diff > maxDiff { return false } } return true } // Issue #8729 func TestImageOperationsGoldenWebp(t *testing.T) { if !webp.Supports() { t.Skip("skip webp test") } c := qt.New(t) c.Parallel() devMode := false testImages := []string{"fuzzy-cirlcle.png"} spec, workDir := newTestResourceOsFs(c) defer func() { if !devMode { os.Remove(workDir) } }() if devMode { fmt.Println(workDir) } for _, imageName := range testImages { image := fetchImageForSpec(spec, c, imageName) imageWebp, err := image.Resize("200x webp") c.Assert(err, qt.IsNil) c.Assert(imageWebp.Width(), qt.Equals, 200) } if devMode { return } dir1 := filepath.Join(workDir, "resources/_gen/images") dir2 := filepath.FromSlash("testdata/golden_webp") assetGoldenDirs(c, dir1, dir2) } func TestImageOperationsGolden(t *testing.T) { c := qt.New(t) c.Parallel() devMode := false testImages := []string{"sunset.jpg", "gohugoio8.png", "gohugoio24.png"} spec, workDir := newTestResourceOsFs(c) defer func() { if !devMode { os.Remove(workDir) } }() if devMode { fmt.Println(workDir) } gopher := fetchImageForSpec(spec, c, "gopher-hero8.png") var err error gopher, err = gopher.Resize("30x") c.Assert(err, qt.IsNil) // Test PNGs with alpha channel. for _, img := range []string{"gopher-hero8.png", "gradient-circle.png"} { orig := fetchImageForSpec(spec, c, img) for _, resizeSpec := range []string{"200x #e3e615", "200x jpg #e3e615"} { resized, err := orig.Resize(resizeSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("resize", rel) c.Assert(rel, qt.Not(qt.Equals), "") } } for _, img := range testImages { orig := fetchImageForSpec(spec, c, img) for _, resizeSpec := range []string{"200x100", "600x", "200x r90 q50 Box"} { resized, err := orig.Resize(resizeSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("resize", rel) c.Assert(rel, qt.Not(qt.Equals), "") } for _, fillSpec := range []string{"300x200 Gaussian Smart", "100x100 Center", "300x100 TopLeft NearestNeighbor", "400x200 BottomLeft"} { resized, err := orig.Fill(fillSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("fill", rel) c.Assert(rel, qt.Not(qt.Equals), "") } for _, fitSpec := range []string{"300x200 Linear"} { resized, err := orig.Fit(fitSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("fit", rel) c.Assert(rel, qt.Not(qt.Equals), "") } f := &images.Filters{} filters := []gift.Filter{ f.Grayscale(), f.GaussianBlur(6), f.Saturation(50), f.Sepia(100), f.Brightness(30), f.ColorBalance(10, -10, -10), f.Colorize(240, 50, 100), f.Gamma(1.5), f.UnsharpMask(1, 1, 0), f.Sigmoid(0.5, 7), f.Pixelate(5), f.Invert(), f.Hue(22), f.Contrast(32.5), f.Overlay(gopher.(images.ImageSource), 20, 30), } resized, err := orig.Fill("400x200 center") c.Assert(err, qt.IsNil) for _, filter := range filters { resized, err := resized.Filter(filter) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Logf("filter: %v %s", filter, rel) c.Assert(rel, qt.Not(qt.Equals), "") } resized, err = resized.Filter(filters[0:4]) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("filter all", rel) c.Assert(rel, qt.Not(qt.Equals), "") } if devMode { return } dir1 := filepath.Join(workDir, "resources/_gen/images") dir2 := filepath.FromSlash("testdata/golden") assetGoldenDirs(c, dir1, dir2) } func assetGoldenDirs(c *qt.C, dir1, dir2 string) { // The two dirs above should now be the same. dirinfos1, err := ioutil.ReadDir(dir1) c.Assert(err, qt.IsNil) dirinfos2, err := ioutil.ReadDir(dir2) c.Assert(err, qt.IsNil) c.Assert(len(dirinfos1), qt.Equals, len(dirinfos2)) for i, fi1 := range dirinfos1 { fi2 := dirinfos2[i] c.Assert(fi1.Name(), qt.Equals, fi2.Name()) f1, err := os.Open(filepath.Join(dir1, fi1.Name())) c.Assert(err, qt.IsNil) f2, err := os.Open(filepath.Join(dir2, fi2.Name())) c.Assert(err, qt.IsNil) img1, _, err := image.Decode(f1) c.Assert(err, qt.IsNil) img2, _, err := image.Decode(f2) c.Assert(err, qt.IsNil) nrgba1 := image.NewNRGBA(img1.Bounds()) gift.New().Draw(nrgba1, img1) nrgba2 := image.NewNRGBA(img2.Bounds()) gift.New().Draw(nrgba2, img2) if !goldenEqual(nrgba1, nrgba2) { switch fi1.Name() { case "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_73c19c5f80881858a85aa23cd0ca400d.png", "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_ae631e5252bb5d7b92bc766ad1a89069.png", "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_d1bbfa2629bffb90118cacce3fcfb924.png": c.Log("expectedly differs from golden due to dithering:", fi1.Name()) default: c.Errorf("resulting image differs from golden: %s", fi1.Name()) } } if !usesFMA { c.Assert(fi1, eq, fi2) _, err = f1.Seek(0, 0) c.Assert(err, qt.IsNil) _, err = f2.Seek(0, 0) c.Assert(err, qt.IsNil) hash1, err := helpers.MD5FromReader(f1) c.Assert(err, qt.IsNil) hash2, err := helpers.MD5FromReader(f2) c.Assert(err, qt.IsNil) c.Assert(hash1, qt.Equals, hash2) } f1.Close() f2.Close() } } 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) } } }) }
// 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" "image" "io/ioutil" "math/big" "math/rand" "os" "path" "path/filepath" "runtime" "strconv" "sync" "testing" "time" "github.com/gohugoio/hugo/resources/images/webp" "github.com/gohugoio/hugo/common/paths" "github.com/spf13/afero" "github.com/disintegration/gift" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/resource" "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 *resourceAdapter) bool { return p1.resourceAdapterInner == p2.resourceAdapterInner }), cmp.Comparer(func(p1, p2 os.FileInfo) bool { 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 *big.Rat) bool { return v1.RatString() == v2.RatString() }, ), 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) fileCache := image.(specProvider).getSpec().FileCaches.ImageCache().Fs assertWidthHeight := func(img resource.Image, 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) } 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) c.Assert(image, qt.Not(eq), resized) assertWidthHeight(resized, 300, 200) assertWidthHeight(image, 900, 562) resized0x, err := image.Resize("x200") c.Assert(err, qt.IsNil) assertWidthHeight(resized0x, 320, 200) assertFileCache(c, fileCache, path.Base(resized0x.RelPermalink()), 320, 200) resizedx0, err := image.Resize("200x") c.Assert(err, qt.IsNil) assertWidthHeight(resizedx0, 200, 125) assertFileCache(c, fileCache, path.Base(resizedx0.RelPermalink()), 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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_300x200_resize_q68_linear.jpg") fitted, err := resized.Fit("50x50") c.Assert(err, qt.IsNil) c.Assert(fitted.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_625708021e2bb281c9f1002f88e4753f.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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_3f65ba24dc2b7fba0f56d7f104519157.jpg") assertWidthHeight(fittedAgain, 10, 7) filled, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x100_fill_q68_linear_bottomleft.jpg") assertWidthHeight(filled, 200, 100) smart, err := image.Fill("200x100 smart") c.Assert(err, qt.IsNil) c.Assert(smart.RelPermalink(), qt.Equals, fmt.Sprintf("/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x100_fill_q68_linear_smart%d.jpg", 1)) assertWidthHeight(smart, 200, 100) // Check cache filledAgain, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled, eq, filledAgain) } func TestImageTransformFormat(t *testing.T) { c := qt.New(t) image := fetchSunset(c) fileCache := image.(specProvider).getSpec().FileCaches.ImageCache().Fs assertExtWidthHeight := func(img resource.Image, 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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_450x0_resize_linear.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") assertFileCache(c, fileCache, path.Base(imagePng.RelPermalink()), 450, 281) imageGif, err := image.Resize("225x gif") c.Assert(err, qt.IsNil) c.Assert(imageGif.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_225x0_resize_linear.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") assertFileCache(c, fileCache, path.Base(imageGif.RelPermalink()), 225, 141) } // 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 resource.Image) { resizedLink := "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_100x50_resize_q75_box.jpg" c.Assert(img.RelPermalink(), qt.Equals, resizedLink) assertImageFile(c, spec.PublishFs, resizedLink, 100, 50) } check2 := func(img resource.Image) { c.Assert(img.RelPermalink(), qt.Equals, "/a/sunset.jpg") assertImageFile(c, spec.PublishFs, "a/sunset.jpg", 900, 562) } orignal := fetchImageForSpec(spec, c, "sunset.jpg") c.Assert(orignal, qt.Not(qt.IsNil)) if checkOriginalFirst { check2(orignal) } resized, err := orignal.Resize("100x50") c.Assert(err, qt.IsNil) check1(resized.(resource.Image)) if !checkOriginalFirst { check2(orignal) } }) } } 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/_hu59e56ffff1bc1d8d122b1403d34e039f_90587_65b757a6e14debeae720fe8831f0a9bc.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/_hu59e56ffff1bc1d8d122b1403d34e039f_90587_c876768085288f41211f768147ba2647.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 := 0; i < 4; i++ { wg.Add(1) go func(id int) { defer wg.Done() for j := 0; j < 5; j++ { img := image for k := 0; k < 2; k++ { 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 TestImageWithMetadata(t *testing.T) { c := qt.New(t) image := fetchSunset(c) meta := []map[string]interface{}{ { "title": "My Sunset", "name": "Sunset #:counter", "src": "*.jpg", }, } c.Assert(AssignMetadata(meta, image), qt.IsNil) c.Assert(image.Name(), qt.Equals, "Sunset #1") resized, err := image.Resize("200x") c.Assert(err, qt.IsNil) c.Assert(resized.Name(), qt.Equals, "Sunset #1") } 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.IsNil) 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_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_800x0_resize_linear_3.png") c.Assert(resized.Width(), qt.Equals, 800) } func TestImageResizeInSubPath(t *testing.T) { c := qt.New(t) image := fetchImage(c, "sub/gohugoio2.png") c.Assert(image.MediaType(), eq, media.PNGType) c.Assert(image.RelPermalink(), qt.Equals, "/a/sub/gohugoio2.png") c.Assert(image.ResourceType(), qt.Equals, "image") c.Assert(image.Exif(), qt.IsNil) resized, err := image.Resize("101x101") c.Assert(err, qt.IsNil) c.Assert(resized.MediaType().Type(), qt.Equals, "image/png") c.Assert(resized.RelPermalink(), qt.Equals, "/a/sub/gohugoio2_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_101x101_resize_linear_3.png") c.Assert(resized.Width(), qt.Equals, 101) c.Assert(resized.Exif(), qt.IsNil) publishedImageFilename := filepath.Clean(resized.RelPermalink()) spec := image.(specProvider).getSpec() assertImageFile(c, spec.BaseFs.PublishFs, publishedImageFilename, 101, 101) c.Assert(spec.BaseFs.PublishFs.Remove(publishedImageFilename), qt.IsNil) // Clear mem cache to simulate reading from the file cache. spec.imageCache.clear() resizedAgain, err := image.Resize("101x101") c.Assert(err, qt.IsNil) c.Assert(resizedAgain.RelPermalink(), qt.Equals, "/a/sub/gohugoio2_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_101x101_resize_linear_3.png") c.Assert(resizedAgain.Width(), qt.Equals, 101) assertImageFile(c, image.(specProvider).getSpec().BaseFs.PublishFs, publishedImageFilename, 101, 101) } 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() 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").(resource.Image) getAndCheckExif := func(c *qt.C, image resource.Image) { 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").(resource.Image) // This will read from file cache. getAndCheckExif(c, image) } func BenchmarkImageExif(b *testing.B) { getImages := func(c *qt.C, b *testing.B, fs afero.Fs) []resource.Image { spec := newTestResourceSpec(specDescriptor{fs: fs, c: c}) images := make([]resource.Image, b.N) for i := 0; i < b.N; i++ { images[i] = fetchResourceForSpec(spec, c, "sunset.jpg", strconv.Itoa(i)).(resource.Image) } return images } getAndCheckExif := func(c *qt.C, image resource.Image) { 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) { b.StopTimer() c := qt.New(b) images := getImages(c, b, afero.NewMemMapFs()) b.StartTimer() for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } }) b.Run("Cold cache, 10", func(b *testing.B) { b.StopTimer() c := qt.New(b) images := getImages(c, b, afero.NewMemMapFs()) b.StartTimer() for i := 0; i < b.N; i++ { for j := 0; j < 10; j++ { getAndCheckExif(c, images[i]) } } }) b.Run("Warm cache", func(b *testing.B) { b.StopTimer() c := qt.New(b) fs := afero.NewMemMapFs() images := getImages(c, b, fs) for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } images = getImages(c, b, fs) b.StartTimer() for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } }) } // usesFMA indicates whether "fused multiply and add" (FMA) instruction is // used. The command "grep FMADD go/test/codegen/floats.go" can help keep // the FMA-using architecture list updated. var usesFMA = runtime.GOARCH == "s390x" || runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" || runtime.GOARCH == "arm64" // goldenEqual compares two NRGBA images. It is used in golden tests only. // A small tolerance is allowed on architectures using "fused multiply and add" // (FMA) instruction to accommodate for floating-point rounding differences // with control golden images that were generated on amd64 architecture. // See https://golang.org/ref/spec#Floating_point_operators // and https://github.com/gohugoio/hugo/issues/6387 for more information. // // Borrowed from https://github.com/disintegration/gift/blob/a999ff8d5226e5ab14b64a94fca07c4ac3f357cf/gift_test.go#L598-L625 // Copyright (c) 2014-2019 Grigory Dryapak // Licensed under the MIT License. func goldenEqual(img1, img2 *image.NRGBA) bool { maxDiff := 0 if usesFMA { maxDiff = 1 } if !img1.Rect.Eq(img2.Rect) { return false } if len(img1.Pix) != len(img2.Pix) { return false } for i := 0; i < len(img1.Pix); i++ { diff := int(img1.Pix[i]) - int(img2.Pix[i]) if diff < 0 { diff = -diff } if diff > maxDiff { return false } } return true } // Issue #8729 func TestImageOperationsGoldenWebp(t *testing.T) { if !webp.Supports() { t.Skip("skip webp test") } c := qt.New(t) c.Parallel() devMode := false testImages := []string{"fuzzy-cirlcle.png"} spec, workDir := newTestResourceOsFs(c) defer func() { if !devMode { os.Remove(workDir) } }() if devMode { fmt.Println(workDir) } for _, imageName := range testImages { image := fetchImageForSpec(spec, c, imageName) imageWebp, err := image.Resize("200x webp") c.Assert(err, qt.IsNil) c.Assert(imageWebp.Width(), qt.Equals, 200) } if devMode { return } dir1 := filepath.Join(workDir, "resources/_gen/images") dir2 := filepath.FromSlash("testdata/golden_webp") assetGoldenDirs(c, dir1, dir2) } func TestImageOperationsGolden(t *testing.T) { c := qt.New(t) c.Parallel() devMode := false testImages := []string{"sunset.jpg", "gohugoio8.png", "gohugoio24.png"} spec, workDir := newTestResourceOsFs(c) defer func() { if !devMode { os.Remove(workDir) } }() if devMode { fmt.Println(workDir) } gopher := fetchImageForSpec(spec, c, "gopher-hero8.png") var err error gopher, err = gopher.Resize("30x") c.Assert(err, qt.IsNil) // Test PNGs with alpha channel. for _, img := range []string{"gopher-hero8.png", "gradient-circle.png"} { orig := fetchImageForSpec(spec, c, img) for _, resizeSpec := range []string{"200x #e3e615", "200x jpg #e3e615"} { resized, err := orig.Resize(resizeSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("resize", rel) c.Assert(rel, qt.Not(qt.Equals), "") } } for _, img := range testImages { orig := fetchImageForSpec(spec, c, img) for _, resizeSpec := range []string{"200x100", "600x", "200x r90 q50 Box"} { resized, err := orig.Resize(resizeSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("resize", rel) c.Assert(rel, qt.Not(qt.Equals), "") } for _, fillSpec := range []string{"300x200 Gaussian Smart", "100x100 Center", "300x100 TopLeft NearestNeighbor", "400x200 BottomLeft"} { resized, err := orig.Fill(fillSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("fill", rel) c.Assert(rel, qt.Not(qt.Equals), "") } for _, fitSpec := range []string{"300x200 Linear"} { resized, err := orig.Fit(fitSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("fit", rel) c.Assert(rel, qt.Not(qt.Equals), "") } f := &images.Filters{} filters := []gift.Filter{ f.Grayscale(), f.GaussianBlur(6), f.Saturation(50), f.Sepia(100), f.Brightness(30), f.ColorBalance(10, -10, -10), f.Colorize(240, 50, 100), f.Gamma(1.5), f.UnsharpMask(1, 1, 0), f.Sigmoid(0.5, 7), f.Pixelate(5), f.Invert(), f.Hue(22), f.Contrast(32.5), f.Overlay(gopher.(images.ImageSource), 20, 30), f.Text("No options"), f.Text("This long text is to test line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."), f.Text("Hugo rocks!", map[string]interface{}{"x": 30, "y": 30, "size": 15, "color": "#ff0000"}), } resized, err := orig.Fill("400x200 center") c.Assert(err, qt.IsNil) for _, filter := range filters { resized, err := resized.Filter(filter) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Logf("filter: %v %s", filter, rel) c.Assert(rel, qt.Not(qt.Equals), "") } resized, err = resized.Filter(filters[0:4]) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("filter all", rel) c.Assert(rel, qt.Not(qt.Equals), "") } if devMode { return } dir1 := filepath.Join(workDir, "resources/_gen/images") dir2 := filepath.FromSlash("testdata/golden") assetGoldenDirs(c, dir1, dir2) } func assetGoldenDirs(c *qt.C, dir1, dir2 string) { // The two dirs above should now be the same. dirinfos1, err := ioutil.ReadDir(dir1) c.Assert(err, qt.IsNil) dirinfos2, err := ioutil.ReadDir(dir2) c.Assert(err, qt.IsNil) c.Assert(len(dirinfos1), qt.Equals, len(dirinfos2)) for i, fi1 := range dirinfos1 { fi2 := dirinfos2[i] c.Assert(fi1.Name(), qt.Equals, fi2.Name()) f1, err := os.Open(filepath.Join(dir1, fi1.Name())) c.Assert(err, qt.IsNil) f2, err := os.Open(filepath.Join(dir2, fi2.Name())) c.Assert(err, qt.IsNil) img1, _, err := image.Decode(f1) c.Assert(err, qt.IsNil) img2, _, err := image.Decode(f2) c.Assert(err, qt.IsNil) nrgba1 := image.NewNRGBA(img1.Bounds()) gift.New().Draw(nrgba1, img1) nrgba2 := image.NewNRGBA(img2.Bounds()) gift.New().Draw(nrgba2, img2) if !goldenEqual(nrgba1, nrgba2) { switch fi1.Name() { case "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_73c19c5f80881858a85aa23cd0ca400d.png", "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_ae631e5252bb5d7b92bc766ad1a89069.png", "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_d1bbfa2629bffb90118cacce3fcfb924.png": c.Log("expectedly differs from golden due to dithering:", fi1.Name()) default: c.Errorf("resulting image differs from golden: %s", fi1.Name()) } } if !usesFMA { c.Assert(fi1, eq, fi2) _, err = f1.Seek(0, 0) c.Assert(err, qt.IsNil) _, err = f2.Seek(0, 0) c.Assert(err, qt.IsNil) hash1, err := helpers.MD5FromReader(f1) c.Assert(err, qt.IsNil) hash2, err := helpers.MD5FromReader(f2) c.Assert(err, qt.IsNil) c.Assert(hash1, qt.Equals, hash2) } f1.Close() f2.Close() } } 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) } } }) }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
Need to flip this for the assertions to trigger.
bep
140
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
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 import ( "fmt" "image" "io/ioutil" "math/big" "math/rand" "os" "path" "path/filepath" "runtime" "strconv" "sync" "testing" "time" "github.com/gohugoio/hugo/resources/images/webp" "github.com/gohugoio/hugo/common/paths" "github.com/spf13/afero" "github.com/disintegration/gift" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/resource" "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 *resourceAdapter) bool { return p1.resourceAdapterInner == p2.resourceAdapterInner }), cmp.Comparer(func(p1, p2 os.FileInfo) bool { 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 *big.Rat) bool { return v1.RatString() == v2.RatString() }, ), 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) fileCache := image.(specProvider).getSpec().FileCaches.ImageCache().Fs assertWidthHeight := func(img resource.Image, 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) } 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) c.Assert(image, qt.Not(eq), resized) assertWidthHeight(resized, 300, 200) assertWidthHeight(image, 900, 562) resized0x, err := image.Resize("x200") c.Assert(err, qt.IsNil) assertWidthHeight(resized0x, 320, 200) assertFileCache(c, fileCache, path.Base(resized0x.RelPermalink()), 320, 200) resizedx0, err := image.Resize("200x") c.Assert(err, qt.IsNil) assertWidthHeight(resizedx0, 200, 125) assertFileCache(c, fileCache, path.Base(resizedx0.RelPermalink()), 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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_300x200_resize_q68_linear.jpg") fitted, err := resized.Fit("50x50") c.Assert(err, qt.IsNil) c.Assert(fitted.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_625708021e2bb281c9f1002f88e4753f.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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_3f65ba24dc2b7fba0f56d7f104519157.jpg") assertWidthHeight(fittedAgain, 10, 7) filled, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x100_fill_q68_linear_bottomleft.jpg") assertWidthHeight(filled, 200, 100) smart, err := image.Fill("200x100 smart") c.Assert(err, qt.IsNil) c.Assert(smart.RelPermalink(), qt.Equals, fmt.Sprintf("/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x100_fill_q68_linear_smart%d.jpg", 1)) assertWidthHeight(smart, 200, 100) // Check cache filledAgain, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled, eq, filledAgain) } func TestImageTransformFormat(t *testing.T) { c := qt.New(t) image := fetchSunset(c) fileCache := image.(specProvider).getSpec().FileCaches.ImageCache().Fs assertExtWidthHeight := func(img resource.Image, 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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_450x0_resize_linear.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") assertFileCache(c, fileCache, path.Base(imagePng.RelPermalink()), 450, 281) imageGif, err := image.Resize("225x gif") c.Assert(err, qt.IsNil) c.Assert(imageGif.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_225x0_resize_linear.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") assertFileCache(c, fileCache, path.Base(imageGif.RelPermalink()), 225, 141) } // 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 resource.Image) { resizedLink := "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_100x50_resize_q75_box.jpg" c.Assert(img.RelPermalink(), qt.Equals, resizedLink) assertImageFile(c, spec.PublishFs, resizedLink, 100, 50) } check2 := func(img resource.Image) { c.Assert(img.RelPermalink(), qt.Equals, "/a/sunset.jpg") assertImageFile(c, spec.PublishFs, "a/sunset.jpg", 900, 562) } orignal := fetchImageForSpec(spec, c, "sunset.jpg") c.Assert(orignal, qt.Not(qt.IsNil)) if checkOriginalFirst { check2(orignal) } resized, err := orignal.Resize("100x50") c.Assert(err, qt.IsNil) check1(resized.(resource.Image)) if !checkOriginalFirst { check2(orignal) } }) } } 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/_hu59e56ffff1bc1d8d122b1403d34e039f_90587_65b757a6e14debeae720fe8831f0a9bc.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/_hu59e56ffff1bc1d8d122b1403d34e039f_90587_c876768085288f41211f768147ba2647.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 := 0; i < 4; i++ { wg.Add(1) go func(id int) { defer wg.Done() for j := 0; j < 5; j++ { img := image for k := 0; k < 2; k++ { 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 TestImageWithMetadata(t *testing.T) { c := qt.New(t) image := fetchSunset(c) meta := []map[string]interface{}{ { "title": "My Sunset", "name": "Sunset #:counter", "src": "*.jpg", }, } c.Assert(AssignMetadata(meta, image), qt.IsNil) c.Assert(image.Name(), qt.Equals, "Sunset #1") resized, err := image.Resize("200x") c.Assert(err, qt.IsNil) c.Assert(resized.Name(), qt.Equals, "Sunset #1") } 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.IsNil) 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_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_800x0_resize_linear_3.png") c.Assert(resized.Width(), qt.Equals, 800) } func TestImageResizeInSubPath(t *testing.T) { c := qt.New(t) image := fetchImage(c, "sub/gohugoio2.png") c.Assert(image.MediaType(), eq, media.PNGType) c.Assert(image.RelPermalink(), qt.Equals, "/a/sub/gohugoio2.png") c.Assert(image.ResourceType(), qt.Equals, "image") c.Assert(image.Exif(), qt.IsNil) resized, err := image.Resize("101x101") c.Assert(err, qt.IsNil) c.Assert(resized.MediaType().Type(), qt.Equals, "image/png") c.Assert(resized.RelPermalink(), qt.Equals, "/a/sub/gohugoio2_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_101x101_resize_linear_3.png") c.Assert(resized.Width(), qt.Equals, 101) c.Assert(resized.Exif(), qt.IsNil) publishedImageFilename := filepath.Clean(resized.RelPermalink()) spec := image.(specProvider).getSpec() assertImageFile(c, spec.BaseFs.PublishFs, publishedImageFilename, 101, 101) c.Assert(spec.BaseFs.PublishFs.Remove(publishedImageFilename), qt.IsNil) // Clear mem cache to simulate reading from the file cache. spec.imageCache.clear() resizedAgain, err := image.Resize("101x101") c.Assert(err, qt.IsNil) c.Assert(resizedAgain.RelPermalink(), qt.Equals, "/a/sub/gohugoio2_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_101x101_resize_linear_3.png") c.Assert(resizedAgain.Width(), qt.Equals, 101) assertImageFile(c, image.(specProvider).getSpec().BaseFs.PublishFs, publishedImageFilename, 101, 101) } 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() 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").(resource.Image) getAndCheckExif := func(c *qt.C, image resource.Image) { 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").(resource.Image) // This will read from file cache. getAndCheckExif(c, image) } func BenchmarkImageExif(b *testing.B) { getImages := func(c *qt.C, b *testing.B, fs afero.Fs) []resource.Image { spec := newTestResourceSpec(specDescriptor{fs: fs, c: c}) images := make([]resource.Image, b.N) for i := 0; i < b.N; i++ { images[i] = fetchResourceForSpec(spec, c, "sunset.jpg", strconv.Itoa(i)).(resource.Image) } return images } getAndCheckExif := func(c *qt.C, image resource.Image) { 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) { b.StopTimer() c := qt.New(b) images := getImages(c, b, afero.NewMemMapFs()) b.StartTimer() for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } }) b.Run("Cold cache, 10", func(b *testing.B) { b.StopTimer() c := qt.New(b) images := getImages(c, b, afero.NewMemMapFs()) b.StartTimer() for i := 0; i < b.N; i++ { for j := 0; j < 10; j++ { getAndCheckExif(c, images[i]) } } }) b.Run("Warm cache", func(b *testing.B) { b.StopTimer() c := qt.New(b) fs := afero.NewMemMapFs() images := getImages(c, b, fs) for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } images = getImages(c, b, fs) b.StartTimer() for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } }) } // usesFMA indicates whether "fused multiply and add" (FMA) instruction is // used. The command "grep FMADD go/test/codegen/floats.go" can help keep // the FMA-using architecture list updated. var usesFMA = runtime.GOARCH == "s390x" || runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" || runtime.GOARCH == "arm64" // goldenEqual compares two NRGBA images. It is used in golden tests only. // A small tolerance is allowed on architectures using "fused multiply and add" // (FMA) instruction to accommodate for floating-point rounding differences // with control golden images that were generated on amd64 architecture. // See https://golang.org/ref/spec#Floating_point_operators // and https://github.com/gohugoio/hugo/issues/6387 for more information. // // Borrowed from https://github.com/disintegration/gift/blob/a999ff8d5226e5ab14b64a94fca07c4ac3f357cf/gift_test.go#L598-L625 // Copyright (c) 2014-2019 Grigory Dryapak // Licensed under the MIT License. func goldenEqual(img1, img2 *image.NRGBA) bool { maxDiff := 0 if usesFMA { maxDiff = 1 } if !img1.Rect.Eq(img2.Rect) { return false } if len(img1.Pix) != len(img2.Pix) { return false } for i := 0; i < len(img1.Pix); i++ { diff := int(img1.Pix[i]) - int(img2.Pix[i]) if diff < 0 { diff = -diff } if diff > maxDiff { return false } } return true } // Issue #8729 func TestImageOperationsGoldenWebp(t *testing.T) { if !webp.Supports() { t.Skip("skip webp test") } c := qt.New(t) c.Parallel() devMode := false testImages := []string{"fuzzy-cirlcle.png"} spec, workDir := newTestResourceOsFs(c) defer func() { if !devMode { os.Remove(workDir) } }() if devMode { fmt.Println(workDir) } for _, imageName := range testImages { image := fetchImageForSpec(spec, c, imageName) imageWebp, err := image.Resize("200x webp") c.Assert(err, qt.IsNil) c.Assert(imageWebp.Width(), qt.Equals, 200) } if devMode { return } dir1 := filepath.Join(workDir, "resources/_gen/images") dir2 := filepath.FromSlash("testdata/golden_webp") assetGoldenDirs(c, dir1, dir2) } func TestImageOperationsGolden(t *testing.T) { c := qt.New(t) c.Parallel() devMode := false testImages := []string{"sunset.jpg", "gohugoio8.png", "gohugoio24.png"} spec, workDir := newTestResourceOsFs(c) defer func() { if !devMode { os.Remove(workDir) } }() if devMode { fmt.Println(workDir) } gopher := fetchImageForSpec(spec, c, "gopher-hero8.png") var err error gopher, err = gopher.Resize("30x") c.Assert(err, qt.IsNil) // Test PNGs with alpha channel. for _, img := range []string{"gopher-hero8.png", "gradient-circle.png"} { orig := fetchImageForSpec(spec, c, img) for _, resizeSpec := range []string{"200x #e3e615", "200x jpg #e3e615"} { resized, err := orig.Resize(resizeSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("resize", rel) c.Assert(rel, qt.Not(qt.Equals), "") } } for _, img := range testImages { orig := fetchImageForSpec(spec, c, img) for _, resizeSpec := range []string{"200x100", "600x", "200x r90 q50 Box"} { resized, err := orig.Resize(resizeSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("resize", rel) c.Assert(rel, qt.Not(qt.Equals), "") } for _, fillSpec := range []string{"300x200 Gaussian Smart", "100x100 Center", "300x100 TopLeft NearestNeighbor", "400x200 BottomLeft"} { resized, err := orig.Fill(fillSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("fill", rel) c.Assert(rel, qt.Not(qt.Equals), "") } for _, fitSpec := range []string{"300x200 Linear"} { resized, err := orig.Fit(fitSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("fit", rel) c.Assert(rel, qt.Not(qt.Equals), "") } f := &images.Filters{} filters := []gift.Filter{ f.Grayscale(), f.GaussianBlur(6), f.Saturation(50), f.Sepia(100), f.Brightness(30), f.ColorBalance(10, -10, -10), f.Colorize(240, 50, 100), f.Gamma(1.5), f.UnsharpMask(1, 1, 0), f.Sigmoid(0.5, 7), f.Pixelate(5), f.Invert(), f.Hue(22), f.Contrast(32.5), f.Overlay(gopher.(images.ImageSource), 20, 30), } resized, err := orig.Fill("400x200 center") c.Assert(err, qt.IsNil) for _, filter := range filters { resized, err := resized.Filter(filter) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Logf("filter: %v %s", filter, rel) c.Assert(rel, qt.Not(qt.Equals), "") } resized, err = resized.Filter(filters[0:4]) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("filter all", rel) c.Assert(rel, qt.Not(qt.Equals), "") } if devMode { return } dir1 := filepath.Join(workDir, "resources/_gen/images") dir2 := filepath.FromSlash("testdata/golden") assetGoldenDirs(c, dir1, dir2) } func assetGoldenDirs(c *qt.C, dir1, dir2 string) { // The two dirs above should now be the same. dirinfos1, err := ioutil.ReadDir(dir1) c.Assert(err, qt.IsNil) dirinfos2, err := ioutil.ReadDir(dir2) c.Assert(err, qt.IsNil) c.Assert(len(dirinfos1), qt.Equals, len(dirinfos2)) for i, fi1 := range dirinfos1 { fi2 := dirinfos2[i] c.Assert(fi1.Name(), qt.Equals, fi2.Name()) f1, err := os.Open(filepath.Join(dir1, fi1.Name())) c.Assert(err, qt.IsNil) f2, err := os.Open(filepath.Join(dir2, fi2.Name())) c.Assert(err, qt.IsNil) img1, _, err := image.Decode(f1) c.Assert(err, qt.IsNil) img2, _, err := image.Decode(f2) c.Assert(err, qt.IsNil) nrgba1 := image.NewNRGBA(img1.Bounds()) gift.New().Draw(nrgba1, img1) nrgba2 := image.NewNRGBA(img2.Bounds()) gift.New().Draw(nrgba2, img2) if !goldenEqual(nrgba1, nrgba2) { switch fi1.Name() { case "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_73c19c5f80881858a85aa23cd0ca400d.png", "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_ae631e5252bb5d7b92bc766ad1a89069.png", "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_d1bbfa2629bffb90118cacce3fcfb924.png": c.Log("expectedly differs from golden due to dithering:", fi1.Name()) default: c.Errorf("resulting image differs from golden: %s", fi1.Name()) } } if !usesFMA { c.Assert(fi1, eq, fi2) _, err = f1.Seek(0, 0) c.Assert(err, qt.IsNil) _, err = f2.Seek(0, 0) c.Assert(err, qt.IsNil) hash1, err := helpers.MD5FromReader(f1) c.Assert(err, qt.IsNil) hash2, err := helpers.MD5FromReader(f2) c.Assert(err, qt.IsNil) c.Assert(hash1, qt.Equals, hash2) } f1.Close() f2.Close() } } 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) } } }) }
// 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" "image" "io/ioutil" "math/big" "math/rand" "os" "path" "path/filepath" "runtime" "strconv" "sync" "testing" "time" "github.com/gohugoio/hugo/resources/images/webp" "github.com/gohugoio/hugo/common/paths" "github.com/spf13/afero" "github.com/disintegration/gift" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/resource" "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 *resourceAdapter) bool { return p1.resourceAdapterInner == p2.resourceAdapterInner }), cmp.Comparer(func(p1, p2 os.FileInfo) bool { 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 *big.Rat) bool { return v1.RatString() == v2.RatString() }, ), 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) fileCache := image.(specProvider).getSpec().FileCaches.ImageCache().Fs assertWidthHeight := func(img resource.Image, 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) } 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) c.Assert(image, qt.Not(eq), resized) assertWidthHeight(resized, 300, 200) assertWidthHeight(image, 900, 562) resized0x, err := image.Resize("x200") c.Assert(err, qt.IsNil) assertWidthHeight(resized0x, 320, 200) assertFileCache(c, fileCache, path.Base(resized0x.RelPermalink()), 320, 200) resizedx0, err := image.Resize("200x") c.Assert(err, qt.IsNil) assertWidthHeight(resizedx0, 200, 125) assertFileCache(c, fileCache, path.Base(resizedx0.RelPermalink()), 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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_300x200_resize_q68_linear.jpg") fitted, err := resized.Fit("50x50") c.Assert(err, qt.IsNil) c.Assert(fitted.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_625708021e2bb281c9f1002f88e4753f.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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_3f65ba24dc2b7fba0f56d7f104519157.jpg") assertWidthHeight(fittedAgain, 10, 7) filled, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x100_fill_q68_linear_bottomleft.jpg") assertWidthHeight(filled, 200, 100) smart, err := image.Fill("200x100 smart") c.Assert(err, qt.IsNil) c.Assert(smart.RelPermalink(), qt.Equals, fmt.Sprintf("/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x100_fill_q68_linear_smart%d.jpg", 1)) assertWidthHeight(smart, 200, 100) // Check cache filledAgain, err := image.Fill("200x100 bottomLeft") c.Assert(err, qt.IsNil) c.Assert(filled, eq, filledAgain) } func TestImageTransformFormat(t *testing.T) { c := qt.New(t) image := fetchSunset(c) fileCache := image.(specProvider).getSpec().FileCaches.ImageCache().Fs assertExtWidthHeight := func(img resource.Image, 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_hu59e56ffff1bc1d8d122b1403d34e039f_90587_450x0_resize_linear.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") assertFileCache(c, fileCache, path.Base(imagePng.RelPermalink()), 450, 281) imageGif, err := image.Resize("225x gif") c.Assert(err, qt.IsNil) c.Assert(imageGif.RelPermalink(), qt.Equals, "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_225x0_resize_linear.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") assertFileCache(c, fileCache, path.Base(imageGif.RelPermalink()), 225, 141) } // 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 resource.Image) { resizedLink := "/a/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_100x50_resize_q75_box.jpg" c.Assert(img.RelPermalink(), qt.Equals, resizedLink) assertImageFile(c, spec.PublishFs, resizedLink, 100, 50) } check2 := func(img resource.Image) { c.Assert(img.RelPermalink(), qt.Equals, "/a/sunset.jpg") assertImageFile(c, spec.PublishFs, "a/sunset.jpg", 900, 562) } orignal := fetchImageForSpec(spec, c, "sunset.jpg") c.Assert(orignal, qt.Not(qt.IsNil)) if checkOriginalFirst { check2(orignal) } resized, err := orignal.Resize("100x50") c.Assert(err, qt.IsNil) check1(resized.(resource.Image)) if !checkOriginalFirst { check2(orignal) } }) } } 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/_hu59e56ffff1bc1d8d122b1403d34e039f_90587_65b757a6e14debeae720fe8831f0a9bc.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/_hu59e56ffff1bc1d8d122b1403d34e039f_90587_c876768085288f41211f768147ba2647.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 := 0; i < 4; i++ { wg.Add(1) go func(id int) { defer wg.Done() for j := 0; j < 5; j++ { img := image for k := 0; k < 2; k++ { 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 TestImageWithMetadata(t *testing.T) { c := qt.New(t) image := fetchSunset(c) meta := []map[string]interface{}{ { "title": "My Sunset", "name": "Sunset #:counter", "src": "*.jpg", }, } c.Assert(AssignMetadata(meta, image), qt.IsNil) c.Assert(image.Name(), qt.Equals, "Sunset #1") resized, err := image.Resize("200x") c.Assert(err, qt.IsNil) c.Assert(resized.Name(), qt.Equals, "Sunset #1") } 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.IsNil) 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_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_800x0_resize_linear_3.png") c.Assert(resized.Width(), qt.Equals, 800) } func TestImageResizeInSubPath(t *testing.T) { c := qt.New(t) image := fetchImage(c, "sub/gohugoio2.png") c.Assert(image.MediaType(), eq, media.PNGType) c.Assert(image.RelPermalink(), qt.Equals, "/a/sub/gohugoio2.png") c.Assert(image.ResourceType(), qt.Equals, "image") c.Assert(image.Exif(), qt.IsNil) resized, err := image.Resize("101x101") c.Assert(err, qt.IsNil) c.Assert(resized.MediaType().Type(), qt.Equals, "image/png") c.Assert(resized.RelPermalink(), qt.Equals, "/a/sub/gohugoio2_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_101x101_resize_linear_3.png") c.Assert(resized.Width(), qt.Equals, 101) c.Assert(resized.Exif(), qt.IsNil) publishedImageFilename := filepath.Clean(resized.RelPermalink()) spec := image.(specProvider).getSpec() assertImageFile(c, spec.BaseFs.PublishFs, publishedImageFilename, 101, 101) c.Assert(spec.BaseFs.PublishFs.Remove(publishedImageFilename), qt.IsNil) // Clear mem cache to simulate reading from the file cache. spec.imageCache.clear() resizedAgain, err := image.Resize("101x101") c.Assert(err, qt.IsNil) c.Assert(resizedAgain.RelPermalink(), qt.Equals, "/a/sub/gohugoio2_hu0e1b9e4a4be4d6f86c7b37b9ccce3fbc_73886_101x101_resize_linear_3.png") c.Assert(resizedAgain.Width(), qt.Equals, 101) assertImageFile(c, image.(specProvider).getSpec().BaseFs.PublishFs, publishedImageFilename, 101, 101) } 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() 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").(resource.Image) getAndCheckExif := func(c *qt.C, image resource.Image) { 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").(resource.Image) // This will read from file cache. getAndCheckExif(c, image) } func BenchmarkImageExif(b *testing.B) { getImages := func(c *qt.C, b *testing.B, fs afero.Fs) []resource.Image { spec := newTestResourceSpec(specDescriptor{fs: fs, c: c}) images := make([]resource.Image, b.N) for i := 0; i < b.N; i++ { images[i] = fetchResourceForSpec(spec, c, "sunset.jpg", strconv.Itoa(i)).(resource.Image) } return images } getAndCheckExif := func(c *qt.C, image resource.Image) { 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) { b.StopTimer() c := qt.New(b) images := getImages(c, b, afero.NewMemMapFs()) b.StartTimer() for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } }) b.Run("Cold cache, 10", func(b *testing.B) { b.StopTimer() c := qt.New(b) images := getImages(c, b, afero.NewMemMapFs()) b.StartTimer() for i := 0; i < b.N; i++ { for j := 0; j < 10; j++ { getAndCheckExif(c, images[i]) } } }) b.Run("Warm cache", func(b *testing.B) { b.StopTimer() c := qt.New(b) fs := afero.NewMemMapFs() images := getImages(c, b, fs) for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } images = getImages(c, b, fs) b.StartTimer() for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } }) } // usesFMA indicates whether "fused multiply and add" (FMA) instruction is // used. The command "grep FMADD go/test/codegen/floats.go" can help keep // the FMA-using architecture list updated. var usesFMA = runtime.GOARCH == "s390x" || runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" || runtime.GOARCH == "arm64" // goldenEqual compares two NRGBA images. It is used in golden tests only. // A small tolerance is allowed on architectures using "fused multiply and add" // (FMA) instruction to accommodate for floating-point rounding differences // with control golden images that were generated on amd64 architecture. // See https://golang.org/ref/spec#Floating_point_operators // and https://github.com/gohugoio/hugo/issues/6387 for more information. // // Borrowed from https://github.com/disintegration/gift/blob/a999ff8d5226e5ab14b64a94fca07c4ac3f357cf/gift_test.go#L598-L625 // Copyright (c) 2014-2019 Grigory Dryapak // Licensed under the MIT License. func goldenEqual(img1, img2 *image.NRGBA) bool { maxDiff := 0 if usesFMA { maxDiff = 1 } if !img1.Rect.Eq(img2.Rect) { return false } if len(img1.Pix) != len(img2.Pix) { return false } for i := 0; i < len(img1.Pix); i++ { diff := int(img1.Pix[i]) - int(img2.Pix[i]) if diff < 0 { diff = -diff } if diff > maxDiff { return false } } return true } // Issue #8729 func TestImageOperationsGoldenWebp(t *testing.T) { if !webp.Supports() { t.Skip("skip webp test") } c := qt.New(t) c.Parallel() devMode := false testImages := []string{"fuzzy-cirlcle.png"} spec, workDir := newTestResourceOsFs(c) defer func() { if !devMode { os.Remove(workDir) } }() if devMode { fmt.Println(workDir) } for _, imageName := range testImages { image := fetchImageForSpec(spec, c, imageName) imageWebp, err := image.Resize("200x webp") c.Assert(err, qt.IsNil) c.Assert(imageWebp.Width(), qt.Equals, 200) } if devMode { return } dir1 := filepath.Join(workDir, "resources/_gen/images") dir2 := filepath.FromSlash("testdata/golden_webp") assetGoldenDirs(c, dir1, dir2) } func TestImageOperationsGolden(t *testing.T) { c := qt.New(t) c.Parallel() devMode := false testImages := []string{"sunset.jpg", "gohugoio8.png", "gohugoio24.png"} spec, workDir := newTestResourceOsFs(c) defer func() { if !devMode { os.Remove(workDir) } }() if devMode { fmt.Println(workDir) } gopher := fetchImageForSpec(spec, c, "gopher-hero8.png") var err error gopher, err = gopher.Resize("30x") c.Assert(err, qt.IsNil) // Test PNGs with alpha channel. for _, img := range []string{"gopher-hero8.png", "gradient-circle.png"} { orig := fetchImageForSpec(spec, c, img) for _, resizeSpec := range []string{"200x #e3e615", "200x jpg #e3e615"} { resized, err := orig.Resize(resizeSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("resize", rel) c.Assert(rel, qt.Not(qt.Equals), "") } } for _, img := range testImages { orig := fetchImageForSpec(spec, c, img) for _, resizeSpec := range []string{"200x100", "600x", "200x r90 q50 Box"} { resized, err := orig.Resize(resizeSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("resize", rel) c.Assert(rel, qt.Not(qt.Equals), "") } for _, fillSpec := range []string{"300x200 Gaussian Smart", "100x100 Center", "300x100 TopLeft NearestNeighbor", "400x200 BottomLeft"} { resized, err := orig.Fill(fillSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("fill", rel) c.Assert(rel, qt.Not(qt.Equals), "") } for _, fitSpec := range []string{"300x200 Linear"} { resized, err := orig.Fit(fitSpec) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("fit", rel) c.Assert(rel, qt.Not(qt.Equals), "") } f := &images.Filters{} filters := []gift.Filter{ f.Grayscale(), f.GaussianBlur(6), f.Saturation(50), f.Sepia(100), f.Brightness(30), f.ColorBalance(10, -10, -10), f.Colorize(240, 50, 100), f.Gamma(1.5), f.UnsharpMask(1, 1, 0), f.Sigmoid(0.5, 7), f.Pixelate(5), f.Invert(), f.Hue(22), f.Contrast(32.5), f.Overlay(gopher.(images.ImageSource), 20, 30), f.Text("No options"), f.Text("This long text is to test line breaks. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."), f.Text("Hugo rocks!", map[string]interface{}{"x": 30, "y": 30, "size": 15, "color": "#ff0000"}), } resized, err := orig.Fill("400x200 center") c.Assert(err, qt.IsNil) for _, filter := range filters { resized, err := resized.Filter(filter) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Logf("filter: %v %s", filter, rel) c.Assert(rel, qt.Not(qt.Equals), "") } resized, err = resized.Filter(filters[0:4]) c.Assert(err, qt.IsNil) rel := resized.RelPermalink() c.Log("filter all", rel) c.Assert(rel, qt.Not(qt.Equals), "") } if devMode { return } dir1 := filepath.Join(workDir, "resources/_gen/images") dir2 := filepath.FromSlash("testdata/golden") assetGoldenDirs(c, dir1, dir2) } func assetGoldenDirs(c *qt.C, dir1, dir2 string) { // The two dirs above should now be the same. dirinfos1, err := ioutil.ReadDir(dir1) c.Assert(err, qt.IsNil) dirinfos2, err := ioutil.ReadDir(dir2) c.Assert(err, qt.IsNil) c.Assert(len(dirinfos1), qt.Equals, len(dirinfos2)) for i, fi1 := range dirinfos1 { fi2 := dirinfos2[i] c.Assert(fi1.Name(), qt.Equals, fi2.Name()) f1, err := os.Open(filepath.Join(dir1, fi1.Name())) c.Assert(err, qt.IsNil) f2, err := os.Open(filepath.Join(dir2, fi2.Name())) c.Assert(err, qt.IsNil) img1, _, err := image.Decode(f1) c.Assert(err, qt.IsNil) img2, _, err := image.Decode(f2) c.Assert(err, qt.IsNil) nrgba1 := image.NewNRGBA(img1.Bounds()) gift.New().Draw(nrgba1, img1) nrgba2 := image.NewNRGBA(img2.Bounds()) gift.New().Draw(nrgba2, img2) if !goldenEqual(nrgba1, nrgba2) { switch fi1.Name() { case "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_73c19c5f80881858a85aa23cd0ca400d.png", "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_ae631e5252bb5d7b92bc766ad1a89069.png", "gohugoio8_hu7f72c00afdf7634587afaa5eff2a25b2_73538_d1bbfa2629bffb90118cacce3fcfb924.png": c.Log("expectedly differs from golden due to dithering:", fi1.Name()) default: c.Errorf("resulting image differs from golden: %s", fi1.Name()) } } if !usesFMA { c.Assert(fi1, eq, fi2) _, err = f1.Seek(0, 0) c.Assert(err, qt.IsNil) _, err = f2.Seek(0, 0) c.Assert(err, qt.IsNil) hash1, err := helpers.MD5FromReader(f1) c.Assert(err, qt.IsNil) hash2, err := helpers.MD5FromReader(f2) c.Assert(err, qt.IsNil) c.Assert(hash1, qt.Equals, hash2) } f1.Close() f2.Close() } } 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) } } }) }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
Options.
bep
141
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
I _think_ that white would make a better default.
bep
142
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
I suspect x:10,y:10 would make a better default.
bep
143
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
OK, I admit, it would be useful to set a custom font, but then this needs some more work. As it is now, I'm pretty sure that `HashString` will return a new value on every build/restart, and that doesn't work. I'm doing some related work in this area, so I suggest that we for this case make it simple: * Fetch the font if set * Replace the `font` in options with `font.Key` (there is an interface) * Create the options hash
bep
144
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
I have removed the font for now, but custom fonts make the Text filter much more useful; this would be a requirement for many users. Not sure if I understand you suggestion above.
vanbroup
145
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
@vanbroup just to be clear re the cache key vs font; the `options` map cannot contain a pointer (unless it implements a Hashable interface, but let's not go down that route her), as that will change on every build/restart. So you need to replace the `font` key with its `.Key` value.
bep
146
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
> So you need to replace the font key with its .Key value. Do you mean the `$resource.Key`? How would that allow me to access the font later on?
vanbroup
147
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
If you do: ``` {{ $font := resource.Get "https://example.org/font.ttf" }} {{ $img = $img | images.Filter (images.Text "foo" (text font: $font ))}} ``` Then 1. `$font` gets cached after first invocation. 2. The images.Text filter will be invoked once for each property combination (which is why we want a stable font Key) and then cached. But note that if the font loading (from the Reader) in itself is an expensive operation, that is not covered by the above.
bep
148
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
In the last commit I updated the font value for `newFilterOpts` to `$font.Key()`, is that what you mean? > `{{ $img = $img | images.Filter (images.Text "foo" (text font: $font ))}}` did you mean: `{{ $img = $img | images.Filter (images.Text "foo" (dict "font" $font ))}}` p.s. Feel free to push directly to this branch, as maintainer you should have the permission to do so, I don't want to keep bothering you while I'm learning the logic of the code.
vanbroup
149
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
I suggest you just use `maps.MustToParamsAndPrepare`; this makes all keys into lowercase, which makes the compare below simpler.
bep
150
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
tf.linespacing.
bep
151
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
I suggest that we complete this PR without the `font` attribute -- I can create suggested PR for that after and see how that works. I'm planning a Hugo release in the next few days, and this would be a great feature to get better OpenGraph images on the Hugo docs site.
bep
152
gohugoio/hugo
9,239
Text filter that draws text with the given options
Closes: #9238
null
2021-12-03 09:59:21+00:00
2021-12-07 10:29:55+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "github.com/gohugoio/hugo/common/maps" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct { } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y interface{}) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...interface{}) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt map[string]interface{} if len(options) > 0 { opt := maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma interface{}) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift interface{}) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size interface{}) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage interface{}) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor interface{}) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold interface{}) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals interface{} } func newFilterOpts(vals ...interface{}) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
vanbroup
5538507e9053a00faa358b92ad0bb004e8d28daf
283394a4fde14476db576a15b7bcc472d693d76f
Removed font attribute as suggested
vanbroup
153
gohugoio/hugo
9,230
Make resources.Get use a file cache for remote resources
Closes: #9228
null
2021-12-02 09:38:37+00:00
2021-12-02 11:56:25+00:00
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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) // This caches to memory and will, in server mode, not be evicted unless the resourceID changes // or the server restarts. // There is ongoing work to improve this. return c.rs.ResourceCache.GetOrCreate(resourceID, func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
// 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 ( "bufio" "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/http/httputil" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client cacheGetResource *filecache.Cache } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, cacheGetResource: rs.FileCaches.GetResourceCache(), } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) _, httpResponse, err := c.cacheGetResource.GetOrCreate(resourceID, func() (io.ReadCloser, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } httpResponse, err := httputil.DumpResponse(res, true) if err != nil { return nil, err } return hugio.ToReadCloser(bytes.NewReader(httpResponse)), nil }) if err != nil { return nil, err } defer httpResponse.Close() res, err := http.ReadResponse(bufio.NewReader(httpResponse), nil) if err != nil { return nil, err } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
133e4bfbeee47bf6843fbcad90f14501f3d3a099
66753416b5ec0f9f1be588a935d5551dfb5eebb9
All of this looks very goo. I one comment; I suspect it would be more (memory) effective to to use `GetOrCreate` (which returns a `io.ReadCloser` -- but then you need to remember to close it when done (or in a defer).
bep
154
gohugoio/hugo
9,221
Check for empty deployment targets and matchers
Fixes #9220
null
2021-11-30 21:53:05+00:00
2021-12-01 09:17:42+00:00
deploy/deployConfig.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. // +build !nodeploy package deploy import ( "fmt" "regexp" "github.com/gobwas/glob" "github.com/gohugoio/hugo/config" hglob "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/media" "github.com/mitchellh/mapstructure" ) const deploymentConfigKey = "deployment" // deployConfig is the complete configuration for deployment. type deployConfig struct { Targets []*target Matchers []*matcher Order []string ordering []*regexp.Regexp // compiled Order mediaTypes media.Types } type target struct { Name string URL string CloudFrontDistributionID string // GoogleCloudCDNOrigin specifies the Google Cloud project and CDN origin to // invalidate when deploying this target. It is specified as <project>/<origin>. GoogleCloudCDNOrigin string // Optional patterns of files to include/exclude for this target. // Parsed using github.com/gobwas/glob. Include string Exclude string // Parsed versions of Include/Exclude. includeGlob glob.Glob excludeGlob glob.Glob } func (tgt *target) parseIncludeExclude() error { var err error if tgt.Include != "" { tgt.includeGlob, err = hglob.GetGlob(tgt.Include) if err != nil { return fmt.Errorf("invalid deployment.target.include %q: %v", tgt.Include, err) } } if tgt.Exclude != "" { tgt.excludeGlob, err = hglob.GetGlob(tgt.Exclude) if err != nil { return fmt.Errorf("invalid deployment.target.exclude %q: %v", tgt.Exclude, err) } } return nil } // matcher represents configuration to be applied to files whose paths match // a specified pattern. type matcher struct { // Pattern is the string pattern to match against paths. // Matching is done against paths converted to use / as the path separator. Pattern string // CacheControl specifies caching attributes to use when serving the blob. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control CacheControl string // ContentEncoding specifies the encoding used for the blob's content, if any. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding ContentEncoding string // ContentType specifies the MIME type of the blob being written. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type ContentType string // Gzip determines whether the file should be gzipped before upload. // If so, the ContentEncoding field will automatically be set to "gzip". Gzip bool // Force indicates that matching files should be re-uploaded. Useful when // other route-determined metadata (e.g., ContentType) has changed. Force bool // re is Pattern compiled. re *regexp.Regexp } func (m *matcher) Matches(path string) bool { return m.re.MatchString(path) } // decode creates a config from a given Hugo configuration. func decodeConfig(cfg config.Provider) (deployConfig, error) { var ( mediaTypesConfig []map[string]interface{} dcfg deployConfig ) if !cfg.IsSet(deploymentConfigKey) { return dcfg, nil } if err := mapstructure.WeakDecode(cfg.GetStringMap(deploymentConfigKey), &dcfg); err != nil { return dcfg, err } for _, tgt := range dcfg.Targets { if err := tgt.parseIncludeExclude(); err != nil { return dcfg, err } } var err error for _, m := range dcfg.Matchers { m.re, err = regexp.Compile(m.Pattern) if err != nil { return dcfg, fmt.Errorf("invalid deployment.matchers.pattern: %v", err) } } for _, o := range dcfg.Order { re, err := regexp.Compile(o) if err != nil { return dcfg, fmt.Errorf("invalid deployment.orderings.pattern: %v", err) } dcfg.ordering = append(dcfg.ordering, re) } if cfg.IsSet("mediaTypes") { mediaTypesConfig = append(mediaTypesConfig, cfg.GetStringMap("mediaTypes")) } dcfg.mediaTypes, err = media.DecodeTypes(mediaTypesConfig...) if err != nil { return dcfg, err } return dcfg, nil }
// 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. //go:build !nodeploy // +build !nodeploy package deploy import ( "fmt" "regexp" "github.com/gobwas/glob" "github.com/gohugoio/hugo/config" hglob "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/media" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" ) const deploymentConfigKey = "deployment" // deployConfig is the complete configuration for deployment. type deployConfig struct { Targets []*target Matchers []*matcher Order []string ordering []*regexp.Regexp // compiled Order mediaTypes media.Types } type target struct { Name string URL string CloudFrontDistributionID string // GoogleCloudCDNOrigin specifies the Google Cloud project and CDN origin to // invalidate when deploying this target. It is specified as <project>/<origin>. GoogleCloudCDNOrigin string // Optional patterns of files to include/exclude for this target. // Parsed using github.com/gobwas/glob. Include string Exclude string // Parsed versions of Include/Exclude. includeGlob glob.Glob excludeGlob glob.Glob } func (tgt *target) parseIncludeExclude() error { var err error if tgt.Include != "" { tgt.includeGlob, err = hglob.GetGlob(tgt.Include) if err != nil { return fmt.Errorf("invalid deployment.target.include %q: %v", tgt.Include, err) } } if tgt.Exclude != "" { tgt.excludeGlob, err = hglob.GetGlob(tgt.Exclude) if err != nil { return fmt.Errorf("invalid deployment.target.exclude %q: %v", tgt.Exclude, err) } } return nil } // matcher represents configuration to be applied to files whose paths match // a specified pattern. type matcher struct { // Pattern is the string pattern to match against paths. // Matching is done against paths converted to use / as the path separator. Pattern string // CacheControl specifies caching attributes to use when serving the blob. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control CacheControl string // ContentEncoding specifies the encoding used for the blob's content, if any. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding ContentEncoding string // ContentType specifies the MIME type of the blob being written. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type ContentType string // Gzip determines whether the file should be gzipped before upload. // If so, the ContentEncoding field will automatically be set to "gzip". Gzip bool // Force indicates that matching files should be re-uploaded. Useful when // other route-determined metadata (e.g., ContentType) has changed. Force bool // re is Pattern compiled. re *regexp.Regexp } func (m *matcher) Matches(path string) bool { return m.re.MatchString(path) } // decode creates a config from a given Hugo configuration. func decodeConfig(cfg config.Provider) (deployConfig, error) { var ( mediaTypesConfig []map[string]interface{} dcfg deployConfig ) if !cfg.IsSet(deploymentConfigKey) { return dcfg, nil } if err := mapstructure.WeakDecode(cfg.GetStringMap(deploymentConfigKey), &dcfg); err != nil { return dcfg, err } for _, tgt := range dcfg.Targets { if tgt == nil { return dcfg, errors.New("empty deployment target") } if err := tgt.parseIncludeExclude(); err != nil { return dcfg, err } } var err error for _, m := range dcfg.Matchers { if m == nil { return dcfg, errors.New("empty deployment matcher") } m.re, err = regexp.Compile(m.Pattern) if err != nil { return dcfg, fmt.Errorf("invalid deployment.matchers.pattern: %v", err) } } for _, o := range dcfg.Order { re, err := regexp.Compile(o) if err != nil { return dcfg, fmt.Errorf("invalid deployment.orderings.pattern: %v", err) } dcfg.ordering = append(dcfg.ordering, re) } if cfg.IsSet("mediaTypes") { mediaTypesConfig = append(mediaTypesConfig, cfg.GetStringMap("mediaTypes")) } dcfg.mediaTypes, err = media.DecodeTypes(mediaTypesConfig...) if err != nil { return dcfg, err } return dcfg, nil }
jmooring
08a863e1e8c7761253939bbafdfdfb9d67df266c
f122771fb1345786f81011181cfd2c452f316278
What's the purpose of this?
bep
155
gohugoio/hugo
9,221
Check for empty deployment targets and matchers
Fixes #9220
null
2021-11-30 21:53:05+00:00
2021-12-01 09:17:42+00:00
deploy/deployConfig.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. // +build !nodeploy package deploy import ( "fmt" "regexp" "github.com/gobwas/glob" "github.com/gohugoio/hugo/config" hglob "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/media" "github.com/mitchellh/mapstructure" ) const deploymentConfigKey = "deployment" // deployConfig is the complete configuration for deployment. type deployConfig struct { Targets []*target Matchers []*matcher Order []string ordering []*regexp.Regexp // compiled Order mediaTypes media.Types } type target struct { Name string URL string CloudFrontDistributionID string // GoogleCloudCDNOrigin specifies the Google Cloud project and CDN origin to // invalidate when deploying this target. It is specified as <project>/<origin>. GoogleCloudCDNOrigin string // Optional patterns of files to include/exclude for this target. // Parsed using github.com/gobwas/glob. Include string Exclude string // Parsed versions of Include/Exclude. includeGlob glob.Glob excludeGlob glob.Glob } func (tgt *target) parseIncludeExclude() error { var err error if tgt.Include != "" { tgt.includeGlob, err = hglob.GetGlob(tgt.Include) if err != nil { return fmt.Errorf("invalid deployment.target.include %q: %v", tgt.Include, err) } } if tgt.Exclude != "" { tgt.excludeGlob, err = hglob.GetGlob(tgt.Exclude) if err != nil { return fmt.Errorf("invalid deployment.target.exclude %q: %v", tgt.Exclude, err) } } return nil } // matcher represents configuration to be applied to files whose paths match // a specified pattern. type matcher struct { // Pattern is the string pattern to match against paths. // Matching is done against paths converted to use / as the path separator. Pattern string // CacheControl specifies caching attributes to use when serving the blob. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control CacheControl string // ContentEncoding specifies the encoding used for the blob's content, if any. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding ContentEncoding string // ContentType specifies the MIME type of the blob being written. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type ContentType string // Gzip determines whether the file should be gzipped before upload. // If so, the ContentEncoding field will automatically be set to "gzip". Gzip bool // Force indicates that matching files should be re-uploaded. Useful when // other route-determined metadata (e.g., ContentType) has changed. Force bool // re is Pattern compiled. re *regexp.Regexp } func (m *matcher) Matches(path string) bool { return m.re.MatchString(path) } // decode creates a config from a given Hugo configuration. func decodeConfig(cfg config.Provider) (deployConfig, error) { var ( mediaTypesConfig []map[string]interface{} dcfg deployConfig ) if !cfg.IsSet(deploymentConfigKey) { return dcfg, nil } if err := mapstructure.WeakDecode(cfg.GetStringMap(deploymentConfigKey), &dcfg); err != nil { return dcfg, err } for _, tgt := range dcfg.Targets { if err := tgt.parseIncludeExclude(); err != nil { return dcfg, err } } var err error for _, m := range dcfg.Matchers { m.re, err = regexp.Compile(m.Pattern) if err != nil { return dcfg, fmt.Errorf("invalid deployment.matchers.pattern: %v", err) } } for _, o := range dcfg.Order { re, err := regexp.Compile(o) if err != nil { return dcfg, fmt.Errorf("invalid deployment.orderings.pattern: %v", err) } dcfg.ordering = append(dcfg.ordering, re) } if cfg.IsSet("mediaTypes") { mediaTypesConfig = append(mediaTypesConfig, cfg.GetStringMap("mediaTypes")) } dcfg.mediaTypes, err = media.DecodeTypes(mediaTypesConfig...) if err != nil { return dcfg, err } return dcfg, nil }
// 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. //go:build !nodeploy // +build !nodeploy package deploy import ( "fmt" "regexp" "github.com/gobwas/glob" "github.com/gohugoio/hugo/config" hglob "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/media" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" ) const deploymentConfigKey = "deployment" // deployConfig is the complete configuration for deployment. type deployConfig struct { Targets []*target Matchers []*matcher Order []string ordering []*regexp.Regexp // compiled Order mediaTypes media.Types } type target struct { Name string URL string CloudFrontDistributionID string // GoogleCloudCDNOrigin specifies the Google Cloud project and CDN origin to // invalidate when deploying this target. It is specified as <project>/<origin>. GoogleCloudCDNOrigin string // Optional patterns of files to include/exclude for this target. // Parsed using github.com/gobwas/glob. Include string Exclude string // Parsed versions of Include/Exclude. includeGlob glob.Glob excludeGlob glob.Glob } func (tgt *target) parseIncludeExclude() error { var err error if tgt.Include != "" { tgt.includeGlob, err = hglob.GetGlob(tgt.Include) if err != nil { return fmt.Errorf("invalid deployment.target.include %q: %v", tgt.Include, err) } } if tgt.Exclude != "" { tgt.excludeGlob, err = hglob.GetGlob(tgt.Exclude) if err != nil { return fmt.Errorf("invalid deployment.target.exclude %q: %v", tgt.Exclude, err) } } return nil } // matcher represents configuration to be applied to files whose paths match // a specified pattern. type matcher struct { // Pattern is the string pattern to match against paths. // Matching is done against paths converted to use / as the path separator. Pattern string // CacheControl specifies caching attributes to use when serving the blob. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control CacheControl string // ContentEncoding specifies the encoding used for the blob's content, if any. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding ContentEncoding string // ContentType specifies the MIME type of the blob being written. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type ContentType string // Gzip determines whether the file should be gzipped before upload. // If so, the ContentEncoding field will automatically be set to "gzip". Gzip bool // Force indicates that matching files should be re-uploaded. Useful when // other route-determined metadata (e.g., ContentType) has changed. Force bool // re is Pattern compiled. re *regexp.Regexp } func (m *matcher) Matches(path string) bool { return m.re.MatchString(path) } // decode creates a config from a given Hugo configuration. func decodeConfig(cfg config.Provider) (deployConfig, error) { var ( mediaTypesConfig []map[string]interface{} dcfg deployConfig ) if !cfg.IsSet(deploymentConfigKey) { return dcfg, nil } if err := mapstructure.WeakDecode(cfg.GetStringMap(deploymentConfigKey), &dcfg); err != nil { return dcfg, err } for _, tgt := range dcfg.Targets { if tgt == nil { return dcfg, errors.New("empty deployment target") } if err := tgt.parseIncludeExclude(); err != nil { return dcfg, err } } var err error for _, m := range dcfg.Matchers { if m == nil { return dcfg, errors.New("empty deployment matcher") } m.re, err = regexp.Compile(m.Pattern) if err != nil { return dcfg, fmt.Errorf("invalid deployment.matchers.pattern: %v", err) } } for _, o := range dcfg.Order { re, err := regexp.Compile(o) if err != nil { return dcfg, fmt.Errorf("invalid deployment.orderings.pattern: %v", err) } dcfg.ordering = append(dcfg.ordering, re) } if cfg.IsSet("mediaTypes") { mediaTypesConfig = append(mediaTypesConfig, cfg.GetStringMap("mediaTypes")) } dcfg.mediaTypes, err = media.DecodeTypes(mediaTypesConfig...) if err != nil { return dcfg, err } return dcfg, nil }
jmooring
08a863e1e8c7761253939bbafdfdfb9d67df266c
f122771fb1345786f81011181cfd2c452f316278
New format for build constraints with 1.17 <https://pkg.go.dev/go/build#hdr-Build_Constraints>
jmooring
156
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
docs/content/en/hugo-pipes/introduction.md
--- title: Hugo Pipes Introduction description: Hugo Pipes is Hugo's asset processing set of functions. date: 2018-07-14 publishdate: 2018-07-14 lastmod: 2018-07-14 categories: [asset management] keywords: [] menu: docs: parent: "pipes" weight: 20 weight: 01 sections_weight: 01 draft: false aliases: [/assets/] --- ### Asset directory Asset files must be stored in the asset directory. This is `/assets` by default, but can be configured via the configuration file's `assetDir` key. ### From file to resource In order to process an asset with Hugo Pipes, it must be retrieved as a resource using `resources.Get`, which takes one argument: the filepath of the file relative to the asset directory. ```go-html-template {{ $style := resources.Get "sass/main.scss" }} ``` ### Asset publishing Assets will only be published (to `/public`) if `.Permalink` or `.RelPermalink` is used. ### Go Pipes For improved readability, the Hugo Pipes examples of this documentation will be written using [Go Pipes](/templates/introduction/#pipes): ```go-html-template {{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify | resources.Fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Method aliases Each Hugo Pipes `resources` transformation method uses a __camelCased__ alias (`toCSS` for `resources.ToCSS`). Non-transformation methods deprived of such aliases are `resources.Get`, `resources.FromString`, `resources.ExecuteAsTemplate` and `resources.Concat`. The example above can therefore also be written as follows: ```go-html-template {{ $style := resources.Get "sass/main.scss" | toCSS | minify | fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Caching Hugo Pipes invocations are cached based on the entire _pipe chain_. An example of a pipe chain is: ```go-html-template {{ $mainJs := resources.Get "js/main.js" | js.Build "main.js" | minify | fingerprint }} ``` The pipe chain is only invoked the first time it is encountered in a site build, and results are otherwise loaded from cache. As such, Hugo Pipes can be used in templates which are executed thousands or millions of times without negatively impacting the build performance.
--- title: Hugo Pipes Introduction description: Hugo Pipes is Hugo's asset processing set of functions. date: 2018-07-14 publishdate: 2018-07-14 lastmod: 2018-07-14 categories: [asset management] keywords: [] menu: docs: parent: "pipes" weight: 20 weight: 01 sections_weight: 01 draft: false aliases: [/assets/] --- ### Asset directory Asset files must be stored in the asset directory. This is `/assets` by default, but can be configured via the configuration file's `assetDir` key. ### From file or URL to resource In order to process an asset with Hugo Pipes, it must be retrieved as a resource using `resources.Get`. The first argument can be the filepath of the file relative to the asset directory or the URL of the file. ```go-html-template {{ $style := resources.Get "sass/main.scss" }} {{ $remoteStyle := resources.Get "https://www.example.com/styles.scss" }} ``` #### Request options When using an URL, the `resources.Get` function takes an optional options map as the last argument, e.g.: ``` {{ $resource := resources.Get "https://example.org/api" (dict "headers" (dict "Authorization" "Bearer abcd")) }} ``` If you need multiple values for the same header key, use a slice: ``` {{ $resource := resources.Get "https://example.org/api" (dict "headers" (dict "X-List" (slice "a" "b" "c"))) }} ``` You can also change the request method and set the request body: ``` {{ $postResponse := resources.Get "https://example.org/api" (dict "method" "post" "body" `{"complete": true}` "headers" (dict "Content-Type" "application/json" ) )}} ``` ### Asset publishing Assets will only be published (to `/public`) if `.Permalink` or `.RelPermalink` is used. ### Go Pipes For improved readability, the Hugo Pipes examples of this documentation will be written using [Go Pipes](/templates/introduction/#pipes): ```go-html-template {{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify | resources.Fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Method aliases Each Hugo Pipes `resources` transformation method uses a __camelCased__ alias (`toCSS` for `resources.ToCSS`). Non-transformation methods deprived of such aliases are `resources.Get`, `resources.FromString`, `resources.ExecuteAsTemplate` and `resources.Concat`. The example above can therefore also be written as follows: ```go-html-template {{ $style := resources.Get "sass/main.scss" | toCSS | minify | fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Caching Hugo Pipes invocations are cached based on the entire _pipe chain_. An example of a pipe chain is: ```go-html-template {{ $mainJs := resources.Get "js/main.js" | js.Build "main.js" | minify | fingerprint }} ``` The pipe chain is only invoked the first time it is encountered in a site build, and results are otherwise loaded from cache. As such, Hugo Pipes can be used in templates which are executed thousands or millions of times without negatively impacting the build performance.
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
I will look at the complete PR (in general, it looks very good), so you don't need to do something about this right away -- but I write it now while remembering it: The original `getJSON` etc. API with variadic arguments was a mistake. If people want to concatenate an URL from different parts, they can do so before passing it to `resources.Get`. So, I suggest that we stick with the 1 argument, with an optional second argument for HTTP headers. Thinking about this, maybe we should make this a `options` so we could add stuff to it in the future (e.g. HTTP config, timeout, whatever), so we do `options.headers` for now?
bep
157
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
docs/content/en/hugo-pipes/introduction.md
--- title: Hugo Pipes Introduction description: Hugo Pipes is Hugo's asset processing set of functions. date: 2018-07-14 publishdate: 2018-07-14 lastmod: 2018-07-14 categories: [asset management] keywords: [] menu: docs: parent: "pipes" weight: 20 weight: 01 sections_weight: 01 draft: false aliases: [/assets/] --- ### Asset directory Asset files must be stored in the asset directory. This is `/assets` by default, but can be configured via the configuration file's `assetDir` key. ### From file to resource In order to process an asset with Hugo Pipes, it must be retrieved as a resource using `resources.Get`, which takes one argument: the filepath of the file relative to the asset directory. ```go-html-template {{ $style := resources.Get "sass/main.scss" }} ``` ### Asset publishing Assets will only be published (to `/public`) if `.Permalink` or `.RelPermalink` is used. ### Go Pipes For improved readability, the Hugo Pipes examples of this documentation will be written using [Go Pipes](/templates/introduction/#pipes): ```go-html-template {{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify | resources.Fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Method aliases Each Hugo Pipes `resources` transformation method uses a __camelCased__ alias (`toCSS` for `resources.ToCSS`). Non-transformation methods deprived of such aliases are `resources.Get`, `resources.FromString`, `resources.ExecuteAsTemplate` and `resources.Concat`. The example above can therefore also be written as follows: ```go-html-template {{ $style := resources.Get "sass/main.scss" | toCSS | minify | fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Caching Hugo Pipes invocations are cached based on the entire _pipe chain_. An example of a pipe chain is: ```go-html-template {{ $mainJs := resources.Get "js/main.js" | js.Build "main.js" | minify | fingerprint }} ``` The pipe chain is only invoked the first time it is encountered in a site build, and results are otherwise loaded from cache. As such, Hugo Pipes can be used in templates which are executed thousands or millions of times without negatively impacting the build performance.
--- title: Hugo Pipes Introduction description: Hugo Pipes is Hugo's asset processing set of functions. date: 2018-07-14 publishdate: 2018-07-14 lastmod: 2018-07-14 categories: [asset management] keywords: [] menu: docs: parent: "pipes" weight: 20 weight: 01 sections_weight: 01 draft: false aliases: [/assets/] --- ### Asset directory Asset files must be stored in the asset directory. This is `/assets` by default, but can be configured via the configuration file's `assetDir` key. ### From file or URL to resource In order to process an asset with Hugo Pipes, it must be retrieved as a resource using `resources.Get`. The first argument can be the filepath of the file relative to the asset directory or the URL of the file. ```go-html-template {{ $style := resources.Get "sass/main.scss" }} {{ $remoteStyle := resources.Get "https://www.example.com/styles.scss" }} ``` #### Request options When using an URL, the `resources.Get` function takes an optional options map as the last argument, e.g.: ``` {{ $resource := resources.Get "https://example.org/api" (dict "headers" (dict "Authorization" "Bearer abcd")) }} ``` If you need multiple values for the same header key, use a slice: ``` {{ $resource := resources.Get "https://example.org/api" (dict "headers" (dict "X-List" (slice "a" "b" "c"))) }} ``` You can also change the request method and set the request body: ``` {{ $postResponse := resources.Get "https://example.org/api" (dict "method" "post" "body" `{"complete": true}` "headers" (dict "Content-Type" "application/json" ) )}} ``` ### Asset publishing Assets will only be published (to `/public`) if `.Permalink` or `.RelPermalink` is used. ### Go Pipes For improved readability, the Hugo Pipes examples of this documentation will be written using [Go Pipes](/templates/introduction/#pipes): ```go-html-template {{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify | resources.Fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Method aliases Each Hugo Pipes `resources` transformation method uses a __camelCased__ alias (`toCSS` for `resources.ToCSS`). Non-transformation methods deprived of such aliases are `resources.Get`, `resources.FromString`, `resources.ExecuteAsTemplate` and `resources.Concat`. The example above can therefore also be written as follows: ```go-html-template {{ $style := resources.Get "sass/main.scss" | toCSS | minify | fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Caching Hugo Pipes invocations are cached based on the entire _pipe chain_. An example of a pipe chain is: ```go-html-template {{ $mainJs := resources.Get "js/main.js" | js.Build "main.js" | minify | fingerprint }} ``` The pipe chain is only invoked the first time it is encountered in a site build, and results are otherwise loaded from cache. As such, Hugo Pipes can be used in templates which are executed thousands or millions of times without negatively impacting the build performance.
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Agree, this would be a better approach, I wanted to stick with what is used elsewhere but as this will deprecate the other functions it's a good moment to break that logic. I have seen some issues asking to support other HTTP methods (e.g., POST), we might be able to include support for that (including the corresponding payload) as well.
vanbroup
158
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
docs/content/en/hugo-pipes/introduction.md
--- title: Hugo Pipes Introduction description: Hugo Pipes is Hugo's asset processing set of functions. date: 2018-07-14 publishdate: 2018-07-14 lastmod: 2018-07-14 categories: [asset management] keywords: [] menu: docs: parent: "pipes" weight: 20 weight: 01 sections_weight: 01 draft: false aliases: [/assets/] --- ### Asset directory Asset files must be stored in the asset directory. This is `/assets` by default, but can be configured via the configuration file's `assetDir` key. ### From file to resource In order to process an asset with Hugo Pipes, it must be retrieved as a resource using `resources.Get`, which takes one argument: the filepath of the file relative to the asset directory. ```go-html-template {{ $style := resources.Get "sass/main.scss" }} ``` ### Asset publishing Assets will only be published (to `/public`) if `.Permalink` or `.RelPermalink` is used. ### Go Pipes For improved readability, the Hugo Pipes examples of this documentation will be written using [Go Pipes](/templates/introduction/#pipes): ```go-html-template {{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify | resources.Fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Method aliases Each Hugo Pipes `resources` transformation method uses a __camelCased__ alias (`toCSS` for `resources.ToCSS`). Non-transformation methods deprived of such aliases are `resources.Get`, `resources.FromString`, `resources.ExecuteAsTemplate` and `resources.Concat`. The example above can therefore also be written as follows: ```go-html-template {{ $style := resources.Get "sass/main.scss" | toCSS | minify | fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Caching Hugo Pipes invocations are cached based on the entire _pipe chain_. An example of a pipe chain is: ```go-html-template {{ $mainJs := resources.Get "js/main.js" | js.Build "main.js" | minify | fingerprint }} ``` The pipe chain is only invoked the first time it is encountered in a site build, and results are otherwise loaded from cache. As such, Hugo Pipes can be used in templates which are executed thousands or millions of times without negatively impacting the build performance.
--- title: Hugo Pipes Introduction description: Hugo Pipes is Hugo's asset processing set of functions. date: 2018-07-14 publishdate: 2018-07-14 lastmod: 2018-07-14 categories: [asset management] keywords: [] menu: docs: parent: "pipes" weight: 20 weight: 01 sections_weight: 01 draft: false aliases: [/assets/] --- ### Asset directory Asset files must be stored in the asset directory. This is `/assets` by default, but can be configured via the configuration file's `assetDir` key. ### From file or URL to resource In order to process an asset with Hugo Pipes, it must be retrieved as a resource using `resources.Get`. The first argument can be the filepath of the file relative to the asset directory or the URL of the file. ```go-html-template {{ $style := resources.Get "sass/main.scss" }} {{ $remoteStyle := resources.Get "https://www.example.com/styles.scss" }} ``` #### Request options When using an URL, the `resources.Get` function takes an optional options map as the last argument, e.g.: ``` {{ $resource := resources.Get "https://example.org/api" (dict "headers" (dict "Authorization" "Bearer abcd")) }} ``` If you need multiple values for the same header key, use a slice: ``` {{ $resource := resources.Get "https://example.org/api" (dict "headers" (dict "X-List" (slice "a" "b" "c"))) }} ``` You can also change the request method and set the request body: ``` {{ $postResponse := resources.Get "https://example.org/api" (dict "method" "post" "body" `{"complete": true}` "headers" (dict "Content-Type" "application/json" ) )}} ``` ### Asset publishing Assets will only be published (to `/public`) if `.Permalink` or `.RelPermalink` is used. ### Go Pipes For improved readability, the Hugo Pipes examples of this documentation will be written using [Go Pipes](/templates/introduction/#pipes): ```go-html-template {{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify | resources.Fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Method aliases Each Hugo Pipes `resources` transformation method uses a __camelCased__ alias (`toCSS` for `resources.ToCSS`). Non-transformation methods deprived of such aliases are `resources.Get`, `resources.FromString`, `resources.ExecuteAsTemplate` and `resources.Concat`. The example above can therefore also be written as follows: ```go-html-template {{ $style := resources.Get "sass/main.scss" | toCSS | minify | fingerprint }} <link rel="stylesheet" href="{{ $style.Permalink }}"> ``` ### Caching Hugo Pipes invocations are cached based on the entire _pipe chain_. An example of a pipe chain is: ```go-html-template {{ $mainJs := resources.Get "js/main.js" | js.Build "main.js" | minify | fingerprint }} ``` The pipe chain is only invoked the first time it is encountered in a site build, and results are otherwise loaded from cache. As such, Hugo Pipes can be used in templates which are executed thousands or millions of times without negatively impacting the build performance.
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
OK, I have looked at this one more time -- and if you do the one change as we discussed above, I will merge it (we/I will improve the cache situation in an upcoming commit). So, we make it into 1 URL argument with an optional second `options` argument. ``` {{ $resource := resources.Get "https://example.org/api" (dict "headers" (dict "Authorization" "Bearer abcd" )) }} ```
bep
159
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
hugolib/resource_chain_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 hugolib import ( "bytes" "fmt" "io" "math/rand" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", ` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} `) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= `) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", ` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
// 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 hugolib import ( "bytes" "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.Get "%[1]s/sunset.jpg" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.Get "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.Get "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.Get "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.Get "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.Get "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.Get "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.Get "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.Get "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.Get "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.Get "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
@bep The size in the permalink turns 0, any idea why this could happen? The size is not 0. I tested fit and resizing and the following works: ``` {{- $image := resources.FromRemote "https://d33wubrfki0l68.cloudfront.net/291588ca4ec28632c45707669f113eced92ea64d/f1a39/images/homepage-screenshot-hugo-themes.jpg" -}} {{ $fit := $image.Fit "200x200"}} {{$image.Permalink}} {{$fit.Permalink}} <img src="{{ $image.Permalink }}" alt="{{ $image.Permalink }}" /> <img src="{{ $fit.Permalink }}" alt="{{ $fit.Permalink }}" /> ```
vanbroup
160
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
hugolib/resource_chain_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 hugolib import ( "bytes" "fmt" "io" "math/rand" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", ` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} `) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= `) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", ` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
// 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 hugolib import ( "bytes" "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.Get "%[1]s/sunset.jpg" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.Get "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.Get "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.Get "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.Get "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.Get "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.Get "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.Get "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.Get "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.Get "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.Get "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
The test server should be closed, but I think the sitebuilder runs in a routine and the server will be stopped before finished. Any suggestions? Can we start a test server as a shared resource?
vanbroup
161
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
hugolib/resource_chain_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 hugolib import ( "bytes" "fmt" "io" "math/rand" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", ` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} `) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= `) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", ` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
// 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 hugolib import ( "bytes" "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.Get "%[1]s/sunset.jpg" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.Get "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.Get "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.Get "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.Get "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.Get "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.Get "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.Get "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.Get "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.Get "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.Get "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Fixed using c8b07b4
vanbroup
162
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
hugolib/resource_chain_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 hugolib import ( "bytes" "fmt" "io" "math/rand" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", ` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} `) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= `) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", ` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
// 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 hugolib import ( "bytes" "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.Get "%[1]s/sunset.jpg" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.Get "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.Get "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.Get "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.Get "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.Get "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.Get "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.Get "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.Get "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.Get "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.Get "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
@bep `hugio.NewReadSeekerNoOpCloser` is not storing any files, causing the unavailability of `hugofs.FileMetaInfo` in https://github.com/gohugoio/hugo/blob/master/resources/resource.go#L644, resulting in the 0 source-file size indicator in the publication filename. I'm not sure why the original file size is included in the filename and if we really care about its or the `hugofs.FileMetaInfo` absence. The `resources.FromString` function has the same limitation (but does not support the image type).
vanbroup
163
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
hugolib/resource_chain_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 hugolib import ( "bytes" "fmt" "io" "math/rand" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", ` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} `) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= `) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", ` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
// 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 hugolib import ( "bytes" "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.Get "%[1]s/sunset.jpg" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.Get "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.Get "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.Get "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.Get "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.Get "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.Get "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.Get "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.Get "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.Get "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.Get "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
The size is 0 because it's not a file (we read that from the FileInfo object we get when doing `os.Stat`). It's probably fixable (we could probably read the size when we generate the hash), but not important.
bep
164
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
hugolib/resource_chain_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 hugolib import ( "bytes" "fmt" "io" "math/rand" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", ` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} `) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= `) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", ` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
// 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 hugolib import ( "bytes" "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/http/httptest" "os" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "path/filepath" "strings" "testing" "time" "github.com/gohugoio/hugo/common/hexec" jww "github.com/spf13/jwalterweatherman" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/htesting" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestSCSSWithIncludePaths(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) }) } } func TestSCSSWithRegularCSSImport(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-regular-%s", test.name)) c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workDir) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) scssDir := filepath.Join(workDir, "assets", "scss") c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "regular.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "another.css"), ``) b.WithSourceFile(filepath.Join(scssDir, "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" %q) }} T1: {{ $r.Content | safeHTML }} `, test.name)) b.Build(BuildCfg{}) if test.name == "libsass" { // 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(filepath.Join(workDir, "public/index.html"), ` T1: moo { color: #fff; } @import "regular.css"; moo { color: #fff; } @import "another.css"; /* foo */ `) } else { // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } }) } } func TestSCSSWithThemeOverrides(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, fmt.Sprintf("hugo-scss-include-theme-overrides-%s", test.name)) c.Assert(err, qt.IsNil) defer clean1() theme := "mytheme" themesDir := filepath.Join(workDir, "themes") themeDirs := filepath.Join(themesDir, theme) v := config.New() v.Set("workingDir", workDir) v.Set("theme", theme) b := newTestSitesBuilder(c).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) fooDir := filepath.Join(workDir, "node_modules", "foo") scssDir := filepath.Join(workDir, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss") c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` @import "moo"; @import "_boo"; @import "_zoo"; `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_moo.scss"), ` $moolor: #fff; moo { color: $moolor; } `) // Only in theme. b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_zoo.scss"), ` $zoolor: pink; zoo { color: $zoolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_boo.scss"), ` $boolor: orange; boo { color: $boolor; } `) b.WithSourceFile(filepath.Join(scssThemeDir, "main.scss"), ` @import "components/imports"; `) b.WithSourceFile(filepath.Join(scssDir, "components", "_moo.scss"), ` $moolor: #ccc; moo { color: $moolor; } `) b.WithSourceFile(filepath.Join(scssDir, "components", "_boo.scss"), ` $boolor: green; boo { color: $boolor; } `) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" %q ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} `, test.name)) b.Build(BuildCfg{}) b.AssertFileContent( filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`, ) }) } } // https://github.com/gohugoio/hugo/issues/6274 func TestSCSSWithIncludePathsSass(t *testing.T) { c := qt.New(t) for _, test := range []struct { name string supports func() bool }{ {"libsass", func() bool { return scss.Supports() }}, {"dartsass", func() bool { return dartsass.Supports() }}, } { c.Run(test.name, func(c *qt.C) { if !test.supports() { c.Skip(fmt.Sprintf("Skip %s", test.name)) } }) } if !scss.Supports() { t.Skip("Skip SCSS") } workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-includepaths") c.Assert(err, qt.IsNil) defer clean1() v := config.New() v.Set("workingDir", workDir) v.Set("theme", "mytheme") b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) hulmaDir := filepath.Join(workDir, "node_modules", "hulma") scssDir := filepath.Join(workDir, "themes/mytheme/assets", "scss") c.Assert(os.MkdirAll(hulmaDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(scssDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(scssDir, "main.scss"), ` @import "hulma/hulma"; `) b.WithSourceFile(filepath.Join(hulmaDir, "hulma.sass"), ` $hulma: #ccc; foo color: $hulma; `) b.WithTemplatesAdded("index.html", ` {{ $scssOptions := (dict "targetPath" "css/styles.css" "enableSourceMap" false "includePaths" (slice "node_modules")) }} {{ $r := resources.Get "scss/main.scss" | toCSS $scssOptions | minify }} T1: {{ $r.Content }} `) b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) } func TestResourceChainBasic(t *testing.T) { t.Parallel() ts := httptest.NewServer(http.FileServer(http.Dir("testdata/"))) t.Cleanup(func() { ts.Close() }) b := newTestSitesBuilder(t) b.WithTemplatesAdded("index.html", fmt.Sprintf(` {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $rimg := resources.Get "%[1]s/sunset.jpg" }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} `, ts.URL)) fs := b.Fs.Source imageDir := filepath.Join("assets", "images") b.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil) src, err := os.Open("testdata/sunset.jpg") b.Assert(err, qt.IsNil) out, err := fs.Create(filepath.Join(imageDir, "sunset.jpg")) b.Assert(err, qt.IsNil) _, err = io.Copy(out, src) b.Assert(err, qt.IsNil) out.Close() b.Running() for i := 0; i < 2; i++ { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", fmt.Sprintf(` SUNSET: images/sunset.jpg|/images/sunset.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT: images/sunset.jpg|/images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_200x200_fit_q75_box.jpg|200 CSS integrity Data first: sha256-od9YaHw8nMOL8mUy97Sy8sKwMV3N4hI3aVmZXATxH&#43;8= /styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css CSS integrity Data last: /styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css sha256-HPxSmGg2QF03&#43;ZmKY/1t2GCOjEEOXj2x2qow94vCc7o= SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0bc8fa97390c4242a86c3e5c0737e71.jpg|900|90587 FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200 `, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{}))) b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") b.EditFiles("page1.md", ` --- title: "Page 1 edit" summary: "Edited summary" --- Edited content. `) b.Assert(b.Fs.Destination.Remove("public"), qt.IsNil) b.H.ResourceSpec.ClearCaches() } } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() rnd := rand.New(rand.NewSource(time.Now().UnixNano())) b := newTestSitesBuilder(t) b.WithConfigFile("toml", `[minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false`) b.WithContent("page1.md", "---\ntitle: Page1\n---") b.WithContent("page2.md", "---\ntitle: Page2\n---") b.WithTemplates( "_default/single.html", `{{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} `, "index.html", `Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> `+strings.Repeat("a b", rnd.Intn(10)+1)+` End.`) b.Running() b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: hello.html|Content: <h1>Hello World!</h1>|Title: hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) } func BenchmarkResourceChainPostProcess(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() s := newTestSitesBuilder(b) for i := 0; i < 300; i++ { s.WithContent(fmt.Sprintf("page%d.md", i+1), "---\ntitle: Page\n---") } s.WithTemplates("_default/single.html", `Start. Some text. {{ $hello1 := "<h1> Hello World 2! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} {{ $hello2 := "<h1> Hello World 2! </h1>" | resources.FromString (printf "%s.html" .Path) | minify | fingerprint "md5" | resources.PostProcess }} Some more text. HELLO: {{ $hello1.RelPermalink }}|Integrity: {{ $hello1.Data.Integrity }}|MediaType: {{ $hello1.MediaType.Type }} Some more text. HELLO2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} Some more text. HELLO2_2: Name: {{ $hello2.Name }}|Content: {{ $hello2.Content }}|Title: {{ $hello2.Title }}|ResourceType: {{ $hello2.ResourceType }} End. `) b.StartTimer() s.Build(BuildCfg{}) } } func TestResourceChains(t *testing.T) { t.Parallel() c := qt.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) return })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool prepare func(b *sitesBuilder) verify func(b *sitesBuilder) }{ {"tocss", func() bool { return scss.Supports() }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, func(b *sitesBuilder) { b.WithConfigFile("toml", `[minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false `) b.WithTemplates("home.html", fmt.Sprintf(` Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.Get "%[1]s/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.Get "%[1]s/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.Get "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.Get "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.Get "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.Get "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x;x=5,document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", fmt.Sprintf(` {{$js := resources.Get "%[1]s/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.Get "%[1]s/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.Get "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.Get "%[1]s/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, ts.URL)) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, {"concat and fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }}, {"fromstring", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, func(b *sitesBuilder) { b.WithSimpleConfigFileAndBaseURL("https://example.com/hugo/") b.WithTemplates("home.html", ` {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.Assert(b.CheckExists("public/external2.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external1.css"), qt.Equals, false) b.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true) b.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false) }}, {"unmarshal", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", ` {{ $toml := "slogan = \"Hugo Rocks!\"" | resources.FromString "slogan.toml" | transform.Unmarshal }} {{ $csv1 := "\"Hugo Rocks\",\"Hugo is Fast!\"" | resources.FromString "slogans.csv" | transform.Unmarshal }} {{ $csv2 := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} Slogan: {{ $toml.slogan }} CSV1: {{ $csv1 }} {{ len (index $csv1 0) }} CSV2: {{ $csv2 }} `) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", `Slogan: Hugo Rocks!`, `[[Hugo Rocks Hugo is Fast!]] 2`, `CSV2: [[a b c]]`, ) }}, {"resources.Get", func() bool { return true }, func(b *sitesBuilder) { b.WithTemplates("home.html", `NOT FOUND: {{ if (resources.Get "this-does-not-exist") }}FAILED{{ else }}OK{{ end }}`) }, func(b *sitesBuilder) { b.AssertFileContent("public/index.html", "NOT FOUND: OK") }}, {"template", func() bool { return true }, func(b *sitesBuilder) {}, func(b *sitesBuilder) { }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { if !test.shouldRun() { t.Skip() } t.Parallel() b := newTestSitesBuilder(t).WithLogger(loggers.NewErrorLogger()) b.WithContent("_index.md", ` --- title: Home --- Home. `, "page1.md", ` --- title: Hello1 --- Hello1 `, "page2.md", ` --- title: Hello2 --- Hello2 `, "t1.txt", "t1t|", "t2.txt", "t2t|", ) b.WithSourceFile(filepath.Join("assets", "css", "styles1.css"), ` h1 { font-style: bold; } `) b.WithSourceFile(filepath.Join("assets", "js", "script1.js"), ` var x; x = 5; document.getElementById("demo").innerHTML = x * 10; `) b.WithSourceFile(filepath.Join("assets", "mydata", "json1.json"), ` { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } `) b.WithSourceFile(filepath.Join("assets", "mydata", "svg1.svg"), ` <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> `) b.WithSourceFile(filepath.Join("assets", "mydata", "xml1.xml"), ` <hello> <world>Hugo Rocks!</<world> </hello> `) b.WithSourceFile(filepath.Join("assets", "mydata", "html1.html"), ` <html> <a href="#"> Cool </a > </html> `) b.WithSourceFile(filepath.Join("assets", "scss", "styles2.scss"), ` $color: #333; body { color: $color; } `) b.WithSourceFile(filepath.Join("assets", "sass", "styles3.sass"), ` $color: #333; .content-navigation border-color: $color `) test.prepare(b) b.Build(BuildCfg{}) test.verify(b) }) } } func TestMultiSiteResource(t *testing.T) { t.Parallel() c := qt.New(t) b := newMultiSiteTestDefaultBuilder(t) b.CreateSites().Build(BuildCfg{}) // This build is multilingual, but not multihost. There should be only one pipes.txt b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false) b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") } func TestResourcesMatch(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("page.md", "") b.WithSourceFile( "assets/jsons/data1.json", "json1 content", "assets/jsons/data2.json", "json2 content", "assets/jsons/data3.xml", "xml content", ) b.WithTemplates("index.html", ` {{ $jsons := (resources.Match "jsons/*.json") }} {{ $json := (resources.GetMatch "jsons/*.json") }} {{ printf "JSONS: %d" (len $jsons) }} JSON: {{ $json.RelPermalink }}: {{ $json.Content }} {{ range $jsons }} {{- .RelPermalink }}: {{ .Content }} {{ end }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "JSON: /jsons/data1.json: json1 content", "JSONS: 2", "/jsons/data1.json: json1 content") } func TestExecuteAsTemplateWithLanguage(t *testing.T) { b := newMultiSiteTestDefaultBuilder(t) indexContent := ` 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.WithTemplatesAdded("index.html", indexContent) b.WithTemplatesAdded("index.fr.html", indexContent) b.Build(BuildCfg{}) b.AssertFileContent("public/en/index.html", ` Hello1: Hello Hello2: Hello `) b.AssertFileContent("public/fr/index.html", ` Hello1: Bonjour Hello2: Bonjour `) } func TestResourceChainPostCSS(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) packageJSON := `{ "scripts": {}, "devDependencies": { "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" } } ` postcssConfig := ` console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT ); // 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') ] } ` tailwindCss := ` @tailwind base; @tailwind components; @tailwind utilities; @import "components/all.css"; h1 { @apply text-2xl font-bold; } ` workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-postcss") c.Assert(err, qt.IsNil) defer clean() var logBuf bytes.Buffer newTestBuilder := func(v config.Provider) *sitesBuilder { v.Set("workingDir", workDir) v.Set("disableKinds", []string{"taxonomy", "term", "page"}) logger := loggers.NewBasicLoggerForWriter(jww.LevelInfo, &logBuf) b := newTestSitesBuilder(t).WithLogger(logger) // Need to use OS fs for this. b.Fs = hugofs.NewDefault(v) b.WithWorkingDir(workDir) b.WithViper(v) b.WithContent("p1.md", "") b.WithTemplates("index.html", ` {{ $options := dict "inlineImports" true }} {{ $styles := resources.Get "css/styles.css" | resources.PostCSS $options }} Styles RelPermalink: {{ $styles.RelPermalink }} {{ $cssContent := $styles.Content }} Styles Content: Len: {{ len $styles.Content }}| `) return b } b := newTestBuilder(config.New()) cssDir := filepath.Join(workDir, "assets", "css", "components") b.Assert(os.MkdirAll(cssDir, 0777), qt.IsNil) b.WithSourceFile("assets/css/styles.css", tailwindCss) b.WithSourceFile("assets/css/components/all.css", ` @import "a.css"; @import "b.css"; `, "assets/css/components/a.css", ` class-in-a { color: blue; } `, "assets/css/components/b.css", ` @import "a.css"; class-in-b { color: blue; } `) b.WithSourceFile("package.json", packageJSON) b.WithSourceFile("postcss.config.js", postcssConfig) b.Assert(os.Chdir(workDir), qt.IsNil) cmd, err := hexec.SafeCommand("npm", "install") _, err = cmd.CombinedOutput() b.Assert(err, qt.IsNil) b.Build(BuildCfg{}) // Make sure Node sees this. b.Assert(logBuf.String(), qt.Contains, "Hugo Environment: production") b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("PostCSS Config File: %s/postcss.config.js", workDir))) b.Assert(logBuf.String(), qt.Contains, filepath.FromSlash(fmt.Sprintf("package.json: %s/package.json", workDir))) b.AssertFileContent("public/index.html", ` Styles RelPermalink: /css/styles.css Styles Content: Len: 770878| `) assertCss := func(b *sitesBuilder) { content := b.FileContent("public/css/styles.css") b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) } assertCss(b) build := func(s string, shouldFail bool) error { b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) v := config.New() v.Set("build", map[string]interface{}{ "useResourceCacheWhen": s, }) b = newTestBuilder(v) b.Assert(os.RemoveAll(filepath.Join(workDir, "public")), qt.IsNil) err := b.BuildE(BuildCfg{}) if shouldFail { b.Assert(err, qt.Not(qt.IsNil)) } else { b.Assert(err, qt.IsNil) assertCss(b) } return err } build("always", false) build("fallback", false) // Introduce a syntax error in an import b.WithSourceFile("assets/css/components/b.css", `@import "a.css"; class-in-b { @apply asdf; } `) err = build("never", true) err = herrors.UnwrapErrorWithFileContext(err) _, ok := err.(*herrors.ErrorWithFileContext) b.Assert(ok, qt.Equals, true) // TODO(bep) for some reason, we have starting to get // execute of template failed: template: index.html:5:25 // on CI (GitHub action). //b.Assert(fe.Position().LineNumber, qt.Equals, 5) //b.Assert(fe.Error(), qt.Contains, filepath.Join(workDir, "assets/css/components/b.css:4:1")) // Remove PostCSS b.Assert(os.RemoveAll(filepath.Join(workDir, "node_modules")), qt.IsNil) build("always", false) build("fallback", false) build("never", true) // Remove cache b.Assert(os.RemoveAll(filepath.Join(workDir, "resources")), qt.IsNil) build("always", true) build("fallback", true) build("never", true) } func TestResourceMinifyDisabled(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL = "https://example.org" [minify] disableXML=true `) b.WithContent("page.md", "") b.WithSourceFile( "assets/xml/data.xml", "<root> <foo> asdfasdf </foo> </root>", ) b.WithTemplates("index.html", ` {{ $xml := resources.Get "xml/data.xml" | minify | fingerprint }} XML: {{ $xml.Content | safeHTML }}|{{ $xml.RelPermalink }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` XML: <root> <foo> asdfasdf </foo> </root>|/xml/data.min.3be4fddd19aaebb18c48dd6645215b822df74701957d6d36e59f203f9c30fd9f.xml `) } // Issue 8954 func TestMinifyWithError(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithSourceFile( "assets/js/test.js", ` new Date(2002, 04, 11) `, ) b.WithTemplates("index.html", ` {{ $js := resources.Get "js/test.js" | minify | fingerprint }} <script> {{ $js.Content }} </script> `) b.WithContent("page.md", "") err := b.BuildE(BuildCfg{}) if err == nil || !strings.Contains(err.Error(), "04") { t.Fatalf("expected a message about a legacy octal number, but got: %v", err) } }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Thanks for your feedback, I will mark this as resolved.
vanbroup
165
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Start with lower case ("failed to...") for errors (unless you are logging them). I know we're not 100% consistent on this, but ...
bep
166
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
I think you could (and should) drop the `SourceFilename`(as there is none).
bep
167
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
This should be `path.Ext`.
bep
168
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
There is a long story, but I'm currently on a branch that will improve this "dependency tracking vs cache" situation (also, but not now (we should mention it in the documentation), this only caches to memory, which may not be optimal for lots of remote resources). But, using `resources.CACHE_OTHER` will effectively trigger a re-download of all remote resources on every rebuild, which is probably not what you would want. I suggest you use `resources.ResourceCacheKey`).
bep
169
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Error message have been updated to start with a lowercase in ba23cbb
vanbroup
170
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Remove `SourceFilename` in 871bbd4
vanbroup
171
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Changed `filepath.Ext` to `path.Ext` in 871bbd4
vanbroup
172
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
871bbd4 changes this to `resources.ResourceCacheKey`, does this mean a cache of the remote resource is stored to disk and retained between builds? As it only returns a string, I doubt it, but I haven't researched the cache system.
vanbroup
173
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
No, but the `resources.ResourceCacheKey` prevents it from being re-downloaded on every rebuild in server mode. There is a long story here; I'm doing some major cleanups in this area in another branch, and we will improve this situation before we release Hugo 0.90, so just let it be for now.
bep
174
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
We need to somehow include the header info in this cache key. It's probably simpler to use `helpers.HashString(args...)`.
bep
175
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
I take that back, just use the `resourceID` as is for the key for now (I will fix this cache situation in a bit).
bep
176
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
We may get lots of different string types in here (not likely in this case, but...), so I suggest: * Make `body` a string and use `cast.ToString` to do the type casting. * Use strings.NewReader to make it into a reader.
bep
177
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
If we make the body a string you can't use a binary resource, for example an image or sound resource, like this: ``` {{ $image := resources.Get "https://d33wubrfki0l68.cloudfront.net/291588ca4ec28632c45707669f113eced92ea64d/f1a39/images/homepage-screenshot-hugo-themes.jpg" }} {{ resources.Get "https://example.com/imagefilter" (dict "method" "post" "body" $image.Content "headers" (dict "Content-Type" "image/jpeg" ) )}} ```
vanbroup
178
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
You mean going back to: ``` resourceID := helpers.MD5String(uri) ``` I do think it's good/a must to have optional headers, request method, etc. included in the cache key. Any reason you think it's better to go back to just the URL?
vanbroup
179
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
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 ( "path" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "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 } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) }
// 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 ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "net/url" "path" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/pkg/errors" ) // Client contains methods to create Resource objects. // tasks to Resource objects. type Client struct { rs *resources.Spec httpClient *http.Client } // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{ rs: rs, httpClient: &http.Client{ Timeout: 10 * time.Second, }, } } // Get creates a new Resource by opening the given filename in the assets filesystem. func (c *Client) Get(filename string) (resource.Resource, error) { filename = filepath.Clean(filename) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(filename), func() (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, SourceFilename: filename, }) }) } // Match gets the resources matching the given pattern from the assets filesystem. func (c *Client) Match(pattern string) (resource.Resources, error) { return c.match(pattern, false) } // 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(pattern, true) if err != nil || len(res) == 0 { return nil, err } return res[0], err } func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) { var name string if firstOnly { name = "__get-match" } else { name = "__match" } pattern = glob.NormalizePath(pattern) partitions := glob.FilterGlobParts(strings.Split(pattern, "/")) if len(partitions) == 0 { partitions = []string{resources.CACHE_OTHER} } 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) { meta := info.Meta() r, err := c.rs.New(resources.ResourceSourceDescriptor{ LazyPublish: true, FileInfo: info, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, RelTargetFilename: meta.Path, }) if err != nil { return true, err } 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 }) } // 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.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) { return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath), }) }) } // 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, options map[string]interface{}) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) } resourceID := helpers.HashString(uri, options) return c.rs.ResourceCache.GetOrCreate(resources.ResourceCacheKey(resourceID), func() (resource.Resource, error) { method, reqBody, err := getMethodAndBody(options) if err != nil { return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri) } req, err := http.NewRequest(method, uri, reqBody) if err != nil { return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) } addDefaultHeaders(req) if _, ok := options["headers"]; ok { headers, err := maps.ToStringMapE(options["headers"]) if err != nil { return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri) } addUserProvidedHeaders(headers, req) } res, err := c.httpClient.Do(req) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode)) } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read remote resource %s", uri) } filename := path.Base(rURL.Path) if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { if _, ok := params["filename"]; ok { filename = params["filename"] } } var contentType string if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 { contentType = arr[0] } // If content type was not determined by header, look for a file extention if contentType == "" { if ext := path.Ext(filename); ext != "" { contentType = ext } } // If content type was not determined by header or file extention, try using content itself if contentType == "" { if ct := http.DetectContentType(body); ct != "application/octet-stream" { if arr, _ := mime.ExtensionsByType(ct); arr != nil { contentType = arr[0] } } } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + contentType return c.rs.New( resources.ResourceSourceDescriptor{ Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil }, RelTargetFilename: filepath.Clean(resourceID), }) }) } func addDefaultHeaders(req *http.Request, accepts ...string) { for _, accept := range accepts { if !hasHeaderValue(req.Header, "Accept", accept) { req.Header.Add("Accept", accept) } } if !hasHeaderKey(req.Header, "User-Agent") { req.Header.Add("User-Agent", "Hugo Static Site Generator") } } func addUserProvidedHeaders(headers map[string]interface{}, 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 hasHeaderValue(m http.Header, key, value string) bool { var s []string var ok bool if s, ok = m[key]; !ok { return false } for _, v := range s { if v == value { return true } } return false } func hasHeaderKey(m http.Header, key string) bool { _, ok := m[key] return ok } func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) { if options == nil { return "GET", nil, nil } if method, ok := options["method"].(string); ok { method = strings.ToUpper(method) switch method { case "GET", "DELETE", "HEAD", "OPTIONS": return method, nil, nil case "POST", "PUT", "PATCH": var body []byte if _, ok := options["body"]; ok { switch b := options["body"].(type) { case string: body = []byte(b) case []byte: body = b } } return method, bytes.NewBuffer(body), nil } return "", nil, fmt.Errorf("invalid HTTP method %q", method) } return "GET", nil, nil }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Ah, ok, never mind.
bep
180
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
tpl/resources/resources.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 provides template functions for working with resources. package resources import ( "fmt" "path/filepath" "sync" "github.com/gohugoio/hugo/common/maps" "github.com/pkg/errors" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/bundler" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/resources/resource_transformers/babel" "github.com/gohugoio/hugo/resources/resource_transformers/integrity" "github.com/gohugoio/hugo/resources/resource_transformers/minifier" "github.com/gohugoio/hugo/resources/resource_transformers/postcss" "github.com/gohugoio/hugo/resources/resource_transformers/templates" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" "github.com/spf13/cast" ) // New returns a new instance of the resources-namespaced template functions. func New(deps *deps.Deps) (*Namespace, error) { if deps.ResourceSpec == nil { return &Namespace{}, nil } scssClient, err := scss.New(deps.BaseFs.Assets, deps.ResourceSpec) if err != nil { return nil, err } minifyClient, err := minifier.New(deps.ResourceSpec) if err != nil { return nil, err } return &Namespace{ deps: deps, scssClientLibSass: scssClient, createClient: create.New(deps.ResourceSpec), bundlerClient: bundler.New(deps.ResourceSpec), integrityClient: integrity.New(deps.ResourceSpec), minifyClient: minifyClient, postcssClient: postcss.New(deps.ResourceSpec), templatesClient: templates.New(deps.ResourceSpec, deps), babelClient: babel.New(deps.ResourceSpec), }, nil } // Namespace provides template functions for the "resources" namespace. type Namespace struct { deps *deps.Deps createClient *create.Client bundlerClient *bundler.Client scssClientLibSass *scss.Client integrityClient *integrity.Client minifyClient *minifier.Client postcssClient *postcss.Client babelClient *babel.Client templatesClient *templates.Client // The Dart Client requires a os/exec process, so only // create it if we really need it. // This is mostly to avoid creating one per site build test. scssClientDartSassInit sync.Once scssClientDartSass *dartsass.Client } func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) { var err error ns.scssClientDartSassInit.Do(func() { ns.scssClientDartSass, err = dartsass.New(ns.deps.BaseFs.Assets, ns.deps.ResourceSpec) if err != nil { return } ns.deps.BuildClosers.Add(ns.scssClientDartSass) }) return ns.scssClientDartSass, err } // Get locates the filename given in Hugo's assets filesystem // and creates a Resource object that can be used for further transformations. func (ns *Namespace) Get(filename interface{}) (resource.Resource, error) { filenamestr, err := cast.ToStringE(filename) if err != nil { return nil, err } filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) } // GetMatch finds the first Resource matching the given pattern, or nil if none found. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.GetMatch(patternStr) } // 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 the files name with path relative to the file system 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. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) Match(pattern interface{}) (resource.Resources, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.Match(patternStr) } // Concat concatenates a slice of Resource objects. These resources must // (currently) be of the same Media Type. func (ns *Namespace) Concat(targetPathIn interface{}, r interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } var rr resource.Resources switch v := r.(type) { case resource.Resources: rr = v case resource.ResourcesConverter: rr = v.ToResources() default: return nil, fmt.Errorf("slice %T not supported in concat", r) } if len(rr) == 0 { return nil, errors.New("must provide one or more Resource objects to concat") } return ns.bundlerClient.Concat(targetPath, rr) } // FromString creates a Resource from a string published to the relative target path. func (ns *Namespace) FromString(targetPathIn, contentIn interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } content, err := cast.ToStringE(contentIn) if err != nil { return nil, err } return ns.createClient.FromString(targetPath, content) } // ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with // the given data, and published to the relative target path. func (ns *Namespace) ExecuteAsTemplate(args ...interface{}) (resource.Resource, error) { if len(args) != 3 { return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object") } targetPath, err := cast.ToStringE(args[0]) if err != nil { return nil, err } data := args[1] r, ok := args[2].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2]) } return ns.templatesClient.ExecuteAsTemplate(r, targetPath, data) } // Fingerprint transforms the given Resource with a MD5 hash of the content in // the RelPermalink and Permalink. func (ns *Namespace) Fingerprint(args ...interface{}) (resource.Resource, error) { if len(args) < 1 || len(args) > 2 { return nil, errors.New("must provide a Resource and (optional) crypto algo") } var algo string resIdx := 0 if len(args) == 2 { resIdx = 1 var err error algo, err = cast.ToStringE(args[0]) if err != nil { return nil, err } } r, ok := args[resIdx].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("%T can not be transformed", args[resIdx]) } return ns.integrityClient.Fingerprint(r, algo) } // Minify minifies the given Resource using the MediaType to pick the correct // minifier. func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) { return ns.minifyClient.Minify(r) } // ToCSS converts the given Resource to CSS. You can optional provide an Options // object or a target path (string) as first argument. func (ns *Namespace) ToCSS(args ...interface{}) (resource.Resource, error) { const ( // 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" ) var ( r resources.ResourceTransformer m map[string]interface{} targetPath string err error ok bool transpiler = transpilerLibSass ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if m != nil { maps.PrepareParams(m) if t, found := m["transpiler"]; found { switch t { case transpilerDart, transpilerLibSass: transpiler = cast.ToString(t) default: return nil, errors.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) } } } if transpiler == transpilerLibSass { var options scss.Options if targetPath != "" { options.TargetPath = helpers.ToSlashTrimLeading(targetPath) } else if m != nil { options, err = scss.DecodeOptions(m) if err != nil { return nil, err } } return ns.scssClientLibSass.ToCSS(r, options) } if m == nil { m = make(map[string]interface{}) } if targetPath != "" { m["targetPath"] = targetPath } client, err := ns.getscssClientDartSass() if err != nil { return nil, err } return client.ToCSS(r, m) } // PostCSS processes the given Resource with PostCSS func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options postcss.Options if m != nil { options, err = postcss.DecodeOptions(m) if err != nil { return nil, err } } return ns.postcssClient.Process(r, options) } func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) } // Babel processes the given Resource with Babel. func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options babel.Options if m != nil { options, err = babel.DecodeOptions(m) if err != nil { return nil, err } } return ns.babelClient.Process(r, options) }
// 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 provides template functions for working with resources. package resources import ( "fmt" "net/url" "path/filepath" "sync" "github.com/gohugoio/hugo/common/maps" "github.com/pkg/errors" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/bundler" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/resources/resource_transformers/babel" "github.com/gohugoio/hugo/resources/resource_transformers/integrity" "github.com/gohugoio/hugo/resources/resource_transformers/minifier" "github.com/gohugoio/hugo/resources/resource_transformers/postcss" "github.com/gohugoio/hugo/resources/resource_transformers/templates" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" "github.com/spf13/cast" ) // New returns a new instance of the resources-namespaced template functions. func New(deps *deps.Deps) (*Namespace, error) { if deps.ResourceSpec == nil { return &Namespace{}, nil } scssClient, err := scss.New(deps.BaseFs.Assets, deps.ResourceSpec) if err != nil { return nil, err } minifyClient, err := minifier.New(deps.ResourceSpec) if err != nil { return nil, err } return &Namespace{ deps: deps, scssClientLibSass: scssClient, createClient: create.New(deps.ResourceSpec), bundlerClient: bundler.New(deps.ResourceSpec), integrityClient: integrity.New(deps.ResourceSpec), minifyClient: minifyClient, postcssClient: postcss.New(deps.ResourceSpec), templatesClient: templates.New(deps.ResourceSpec, deps), babelClient: babel.New(deps.ResourceSpec), }, nil } // Namespace provides template functions for the "resources" namespace. type Namespace struct { deps *deps.Deps createClient *create.Client bundlerClient *bundler.Client scssClientLibSass *scss.Client integrityClient *integrity.Client minifyClient *minifier.Client postcssClient *postcss.Client babelClient *babel.Client templatesClient *templates.Client // The Dart Client requires a os/exec process, so only // create it if we really need it. // This is mostly to avoid creating one per site build test. scssClientDartSassInit sync.Once scssClientDartSass *dartsass.Client } func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) { var err error ns.scssClientDartSassInit.Do(func() { ns.scssClientDartSass, err = dartsass.New(ns.deps.BaseFs.Assets, ns.deps.ResourceSpec) if err != nil { return } ns.deps.BuildClosers.Add(ns.scssClientDartSass) }) return ns.scssClientDartSass, err } // Get locates the filename given in Hugo's assets filesystem or downloads // a file from an URL and creates a Resource object that can be used for // further transformations. // // For URLs an additional argument with options can be provided. func (ns *Namespace) Get(args ...interface{}) (resource.Resource, error) { if len(args) != 1 && len(args) != 2 { return nil, errors.New("must provide a filename or URL") } filenamestr, err := cast.ToStringE(args[0]) if err != nil { return nil, err } if u, err := url.Parse(filenamestr); err == nil && u.Scheme != "" { if len(args) == 2 { options, err := maps.ToStringMapE(args[1]) if err != nil { return nil, err } return ns.createClient.FromRemote(filenamestr, options) } return ns.createClient.FromRemote(filenamestr, nil) } filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) } // GetMatch finds the first Resource matching the given pattern, or nil if none found. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.GetMatch(patternStr) } // 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 the files name with path relative to the file system 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. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) Match(pattern interface{}) (resource.Resources, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.Match(patternStr) } // Concat concatenates a slice of Resource objects. These resources must // (currently) be of the same Media Type. func (ns *Namespace) Concat(targetPathIn interface{}, r interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } var rr resource.Resources switch v := r.(type) { case resource.Resources: rr = v case resource.ResourcesConverter: rr = v.ToResources() default: return nil, fmt.Errorf("slice %T not supported in concat", r) } if len(rr) == 0 { return nil, errors.New("must provide one or more Resource objects to concat") } return ns.bundlerClient.Concat(targetPath, rr) } // FromString creates a Resource from a string published to the relative target path. func (ns *Namespace) FromString(targetPathIn, contentIn interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } content, err := cast.ToStringE(contentIn) if err != nil { return nil, err } return ns.createClient.FromString(targetPath, content) } // ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with // the given data, and published to the relative target path. func (ns *Namespace) ExecuteAsTemplate(args ...interface{}) (resource.Resource, error) { if len(args) != 3 { return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object") } targetPath, err := cast.ToStringE(args[0]) if err != nil { return nil, err } data := args[1] r, ok := args[2].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2]) } return ns.templatesClient.ExecuteAsTemplate(r, targetPath, data) } // Fingerprint transforms the given Resource with a MD5 hash of the content in // the RelPermalink and Permalink. func (ns *Namespace) Fingerprint(args ...interface{}) (resource.Resource, error) { if len(args) < 1 || len(args) > 2 { return nil, errors.New("must provide a Resource and (optional) crypto algo") } var algo string resIdx := 0 if len(args) == 2 { resIdx = 1 var err error algo, err = cast.ToStringE(args[0]) if err != nil { return nil, err } } r, ok := args[resIdx].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("%T can not be transformed", args[resIdx]) } return ns.integrityClient.Fingerprint(r, algo) } // Minify minifies the given Resource using the MediaType to pick the correct // minifier. func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) { return ns.minifyClient.Minify(r) } // ToCSS converts the given Resource to CSS. You can optional provide an Options // object or a target path (string) as first argument. func (ns *Namespace) ToCSS(args ...interface{}) (resource.Resource, error) { const ( // 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" ) var ( r resources.ResourceTransformer m map[string]interface{} targetPath string err error ok bool transpiler = transpilerLibSass ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if m != nil { maps.PrepareParams(m) if t, found := m["transpiler"]; found { switch t { case transpilerDart, transpilerLibSass: transpiler = cast.ToString(t) default: return nil, errors.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) } } } if transpiler == transpilerLibSass { var options scss.Options if targetPath != "" { options.TargetPath = helpers.ToSlashTrimLeading(targetPath) } else if m != nil { options, err = scss.DecodeOptions(m) if err != nil { return nil, err } } return ns.scssClientLibSass.ToCSS(r, options) } if m == nil { m = make(map[string]interface{}) } if targetPath != "" { m["targetPath"] = targetPath } client, err := ns.getscssClientDartSass() if err != nil { return nil, err } return client.ToCSS(r, m) } // PostCSS processes the given Resource with PostCSS func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options postcss.Options if m != nil { options, err = postcss.DecodeOptions(m) if err != nil { return nil, err } } return ns.postcssClient.Process(r, options) } func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) } // Babel processes the given Resource with Babel. func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options babel.Options if m != nil { options, err = babel.DecodeOptions(m) if err != nil { return nil, err } } return ns.babelClient.Process(r, options) }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
We have discussed this before, and I have certainly thought well and hard about it. The thing is, the user does not care about _where_ the resource lives. So, I suggest that we try to have the `resources.Get` work for both local and remote resources. The implementations certainly needs to be separate, but we need to check for the presence of a protocol, e.g. ``` {{ $remote := resources.Get "https://myapi.json" }} {{ $remote := resources.Get "/foo/bar.json" }} ```
bep
181
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
tpl/resources/resources.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 provides template functions for working with resources. package resources import ( "fmt" "path/filepath" "sync" "github.com/gohugoio/hugo/common/maps" "github.com/pkg/errors" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/bundler" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/resources/resource_transformers/babel" "github.com/gohugoio/hugo/resources/resource_transformers/integrity" "github.com/gohugoio/hugo/resources/resource_transformers/minifier" "github.com/gohugoio/hugo/resources/resource_transformers/postcss" "github.com/gohugoio/hugo/resources/resource_transformers/templates" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" "github.com/spf13/cast" ) // New returns a new instance of the resources-namespaced template functions. func New(deps *deps.Deps) (*Namespace, error) { if deps.ResourceSpec == nil { return &Namespace{}, nil } scssClient, err := scss.New(deps.BaseFs.Assets, deps.ResourceSpec) if err != nil { return nil, err } minifyClient, err := minifier.New(deps.ResourceSpec) if err != nil { return nil, err } return &Namespace{ deps: deps, scssClientLibSass: scssClient, createClient: create.New(deps.ResourceSpec), bundlerClient: bundler.New(deps.ResourceSpec), integrityClient: integrity.New(deps.ResourceSpec), minifyClient: minifyClient, postcssClient: postcss.New(deps.ResourceSpec), templatesClient: templates.New(deps.ResourceSpec, deps), babelClient: babel.New(deps.ResourceSpec), }, nil } // Namespace provides template functions for the "resources" namespace. type Namespace struct { deps *deps.Deps createClient *create.Client bundlerClient *bundler.Client scssClientLibSass *scss.Client integrityClient *integrity.Client minifyClient *minifier.Client postcssClient *postcss.Client babelClient *babel.Client templatesClient *templates.Client // The Dart Client requires a os/exec process, so only // create it if we really need it. // This is mostly to avoid creating one per site build test. scssClientDartSassInit sync.Once scssClientDartSass *dartsass.Client } func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) { var err error ns.scssClientDartSassInit.Do(func() { ns.scssClientDartSass, err = dartsass.New(ns.deps.BaseFs.Assets, ns.deps.ResourceSpec) if err != nil { return } ns.deps.BuildClosers.Add(ns.scssClientDartSass) }) return ns.scssClientDartSass, err } // Get locates the filename given in Hugo's assets filesystem // and creates a Resource object that can be used for further transformations. func (ns *Namespace) Get(filename interface{}) (resource.Resource, error) { filenamestr, err := cast.ToStringE(filename) if err != nil { return nil, err } filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) } // GetMatch finds the first Resource matching the given pattern, or nil if none found. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.GetMatch(patternStr) } // 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 the files name with path relative to the file system 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. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) Match(pattern interface{}) (resource.Resources, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.Match(patternStr) } // Concat concatenates a slice of Resource objects. These resources must // (currently) be of the same Media Type. func (ns *Namespace) Concat(targetPathIn interface{}, r interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } var rr resource.Resources switch v := r.(type) { case resource.Resources: rr = v case resource.ResourcesConverter: rr = v.ToResources() default: return nil, fmt.Errorf("slice %T not supported in concat", r) } if len(rr) == 0 { return nil, errors.New("must provide one or more Resource objects to concat") } return ns.bundlerClient.Concat(targetPath, rr) } // FromString creates a Resource from a string published to the relative target path. func (ns *Namespace) FromString(targetPathIn, contentIn interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } content, err := cast.ToStringE(contentIn) if err != nil { return nil, err } return ns.createClient.FromString(targetPath, content) } // ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with // the given data, and published to the relative target path. func (ns *Namespace) ExecuteAsTemplate(args ...interface{}) (resource.Resource, error) { if len(args) != 3 { return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object") } targetPath, err := cast.ToStringE(args[0]) if err != nil { return nil, err } data := args[1] r, ok := args[2].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2]) } return ns.templatesClient.ExecuteAsTemplate(r, targetPath, data) } // Fingerprint transforms the given Resource with a MD5 hash of the content in // the RelPermalink and Permalink. func (ns *Namespace) Fingerprint(args ...interface{}) (resource.Resource, error) { if len(args) < 1 || len(args) > 2 { return nil, errors.New("must provide a Resource and (optional) crypto algo") } var algo string resIdx := 0 if len(args) == 2 { resIdx = 1 var err error algo, err = cast.ToStringE(args[0]) if err != nil { return nil, err } } r, ok := args[resIdx].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("%T can not be transformed", args[resIdx]) } return ns.integrityClient.Fingerprint(r, algo) } // Minify minifies the given Resource using the MediaType to pick the correct // minifier. func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) { return ns.minifyClient.Minify(r) } // ToCSS converts the given Resource to CSS. You can optional provide an Options // object or a target path (string) as first argument. func (ns *Namespace) ToCSS(args ...interface{}) (resource.Resource, error) { const ( // 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" ) var ( r resources.ResourceTransformer m map[string]interface{} targetPath string err error ok bool transpiler = transpilerLibSass ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if m != nil { maps.PrepareParams(m) if t, found := m["transpiler"]; found { switch t { case transpilerDart, transpilerLibSass: transpiler = cast.ToString(t) default: return nil, errors.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) } } } if transpiler == transpilerLibSass { var options scss.Options if targetPath != "" { options.TargetPath = helpers.ToSlashTrimLeading(targetPath) } else if m != nil { options, err = scss.DecodeOptions(m) if err != nil { return nil, err } } return ns.scssClientLibSass.ToCSS(r, options) } if m == nil { m = make(map[string]interface{}) } if targetPath != "" { m["targetPath"] = targetPath } client, err := ns.getscssClientDartSass() if err != nil { return nil, err } return client.ToCSS(r, m) } // PostCSS processes the given Resource with PostCSS func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options postcss.Options if m != nil { options, err = postcss.DecodeOptions(m) if err != nil { return nil, err } } return ns.postcssClient.Process(r, options) } func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) } // Babel processes the given Resource with Babel. func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options babel.Options if m != nil { options, err = babel.DecodeOptions(m) if err != nil { return nil, err } } return ns.babelClient.Process(r, options) }
// 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 provides template functions for working with resources. package resources import ( "fmt" "net/url" "path/filepath" "sync" "github.com/gohugoio/hugo/common/maps" "github.com/pkg/errors" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/bundler" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/resources/resource_transformers/babel" "github.com/gohugoio/hugo/resources/resource_transformers/integrity" "github.com/gohugoio/hugo/resources/resource_transformers/minifier" "github.com/gohugoio/hugo/resources/resource_transformers/postcss" "github.com/gohugoio/hugo/resources/resource_transformers/templates" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" "github.com/spf13/cast" ) // New returns a new instance of the resources-namespaced template functions. func New(deps *deps.Deps) (*Namespace, error) { if deps.ResourceSpec == nil { return &Namespace{}, nil } scssClient, err := scss.New(deps.BaseFs.Assets, deps.ResourceSpec) if err != nil { return nil, err } minifyClient, err := minifier.New(deps.ResourceSpec) if err != nil { return nil, err } return &Namespace{ deps: deps, scssClientLibSass: scssClient, createClient: create.New(deps.ResourceSpec), bundlerClient: bundler.New(deps.ResourceSpec), integrityClient: integrity.New(deps.ResourceSpec), minifyClient: minifyClient, postcssClient: postcss.New(deps.ResourceSpec), templatesClient: templates.New(deps.ResourceSpec, deps), babelClient: babel.New(deps.ResourceSpec), }, nil } // Namespace provides template functions for the "resources" namespace. type Namespace struct { deps *deps.Deps createClient *create.Client bundlerClient *bundler.Client scssClientLibSass *scss.Client integrityClient *integrity.Client minifyClient *minifier.Client postcssClient *postcss.Client babelClient *babel.Client templatesClient *templates.Client // The Dart Client requires a os/exec process, so only // create it if we really need it. // This is mostly to avoid creating one per site build test. scssClientDartSassInit sync.Once scssClientDartSass *dartsass.Client } func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) { var err error ns.scssClientDartSassInit.Do(func() { ns.scssClientDartSass, err = dartsass.New(ns.deps.BaseFs.Assets, ns.deps.ResourceSpec) if err != nil { return } ns.deps.BuildClosers.Add(ns.scssClientDartSass) }) return ns.scssClientDartSass, err } // Get locates the filename given in Hugo's assets filesystem or downloads // a file from an URL and creates a Resource object that can be used for // further transformations. // // For URLs an additional argument with options can be provided. func (ns *Namespace) Get(args ...interface{}) (resource.Resource, error) { if len(args) != 1 && len(args) != 2 { return nil, errors.New("must provide a filename or URL") } filenamestr, err := cast.ToStringE(args[0]) if err != nil { return nil, err } if u, err := url.Parse(filenamestr); err == nil && u.Scheme != "" { if len(args) == 2 { options, err := maps.ToStringMapE(args[1]) if err != nil { return nil, err } return ns.createClient.FromRemote(filenamestr, options) } return ns.createClient.FromRemote(filenamestr, nil) } filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) } // GetMatch finds the first Resource matching the given pattern, or nil if none found. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.GetMatch(patternStr) } // 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 the files name with path relative to the file system 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. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) Match(pattern interface{}) (resource.Resources, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.Match(patternStr) } // Concat concatenates a slice of Resource objects. These resources must // (currently) be of the same Media Type. func (ns *Namespace) Concat(targetPathIn interface{}, r interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } var rr resource.Resources switch v := r.(type) { case resource.Resources: rr = v case resource.ResourcesConverter: rr = v.ToResources() default: return nil, fmt.Errorf("slice %T not supported in concat", r) } if len(rr) == 0 { return nil, errors.New("must provide one or more Resource objects to concat") } return ns.bundlerClient.Concat(targetPath, rr) } // FromString creates a Resource from a string published to the relative target path. func (ns *Namespace) FromString(targetPathIn, contentIn interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } content, err := cast.ToStringE(contentIn) if err != nil { return nil, err } return ns.createClient.FromString(targetPath, content) } // ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with // the given data, and published to the relative target path. func (ns *Namespace) ExecuteAsTemplate(args ...interface{}) (resource.Resource, error) { if len(args) != 3 { return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object") } targetPath, err := cast.ToStringE(args[0]) if err != nil { return nil, err } data := args[1] r, ok := args[2].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2]) } return ns.templatesClient.ExecuteAsTemplate(r, targetPath, data) } // Fingerprint transforms the given Resource with a MD5 hash of the content in // the RelPermalink and Permalink. func (ns *Namespace) Fingerprint(args ...interface{}) (resource.Resource, error) { if len(args) < 1 || len(args) > 2 { return nil, errors.New("must provide a Resource and (optional) crypto algo") } var algo string resIdx := 0 if len(args) == 2 { resIdx = 1 var err error algo, err = cast.ToStringE(args[0]) if err != nil { return nil, err } } r, ok := args[resIdx].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("%T can not be transformed", args[resIdx]) } return ns.integrityClient.Fingerprint(r, algo) } // Minify minifies the given Resource using the MediaType to pick the correct // minifier. func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) { return ns.minifyClient.Minify(r) } // ToCSS converts the given Resource to CSS. You can optional provide an Options // object or a target path (string) as first argument. func (ns *Namespace) ToCSS(args ...interface{}) (resource.Resource, error) { const ( // 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" ) var ( r resources.ResourceTransformer m map[string]interface{} targetPath string err error ok bool transpiler = transpilerLibSass ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if m != nil { maps.PrepareParams(m) if t, found := m["transpiler"]; found { switch t { case transpilerDart, transpilerLibSass: transpiler = cast.ToString(t) default: return nil, errors.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) } } } if transpiler == transpilerLibSass { var options scss.Options if targetPath != "" { options.TargetPath = helpers.ToSlashTrimLeading(targetPath) } else if m != nil { options, err = scss.DecodeOptions(m) if err != nil { return nil, err } } return ns.scssClientLibSass.ToCSS(r, options) } if m == nil { m = make(map[string]interface{}) } if targetPath != "" { m["targetPath"] = targetPath } client, err := ns.getscssClientDartSass() if err != nil { return nil, err } return client.ToCSS(r, m) } // PostCSS processes the given Resource with PostCSS func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options postcss.Options if m != nil { options, err = postcss.DecodeOptions(m) if err != nil { return nil, err } } return ns.postcssClient.Process(r, options) } func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) } // Babel processes the given Resource with Babel. func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options babel.Options if m != nil { options, err = babel.DecodeOptions(m) if err != nil { return nil, err } } return ns.babelClient.Process(r, options) }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
ad6e83f updates `resources.Get` to check for remote resources, this is also covered by testing
vanbroup
182
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
tpl/resources/resources.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 provides template functions for working with resources. package resources import ( "fmt" "path/filepath" "sync" "github.com/gohugoio/hugo/common/maps" "github.com/pkg/errors" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/bundler" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/resources/resource_transformers/babel" "github.com/gohugoio/hugo/resources/resource_transformers/integrity" "github.com/gohugoio/hugo/resources/resource_transformers/minifier" "github.com/gohugoio/hugo/resources/resource_transformers/postcss" "github.com/gohugoio/hugo/resources/resource_transformers/templates" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" "github.com/spf13/cast" ) // New returns a new instance of the resources-namespaced template functions. func New(deps *deps.Deps) (*Namespace, error) { if deps.ResourceSpec == nil { return &Namespace{}, nil } scssClient, err := scss.New(deps.BaseFs.Assets, deps.ResourceSpec) if err != nil { return nil, err } minifyClient, err := minifier.New(deps.ResourceSpec) if err != nil { return nil, err } return &Namespace{ deps: deps, scssClientLibSass: scssClient, createClient: create.New(deps.ResourceSpec), bundlerClient: bundler.New(deps.ResourceSpec), integrityClient: integrity.New(deps.ResourceSpec), minifyClient: minifyClient, postcssClient: postcss.New(deps.ResourceSpec), templatesClient: templates.New(deps.ResourceSpec, deps), babelClient: babel.New(deps.ResourceSpec), }, nil } // Namespace provides template functions for the "resources" namespace. type Namespace struct { deps *deps.Deps createClient *create.Client bundlerClient *bundler.Client scssClientLibSass *scss.Client integrityClient *integrity.Client minifyClient *minifier.Client postcssClient *postcss.Client babelClient *babel.Client templatesClient *templates.Client // The Dart Client requires a os/exec process, so only // create it if we really need it. // This is mostly to avoid creating one per site build test. scssClientDartSassInit sync.Once scssClientDartSass *dartsass.Client } func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) { var err error ns.scssClientDartSassInit.Do(func() { ns.scssClientDartSass, err = dartsass.New(ns.deps.BaseFs.Assets, ns.deps.ResourceSpec) if err != nil { return } ns.deps.BuildClosers.Add(ns.scssClientDartSass) }) return ns.scssClientDartSass, err } // Get locates the filename given in Hugo's assets filesystem // and creates a Resource object that can be used for further transformations. func (ns *Namespace) Get(filename interface{}) (resource.Resource, error) { filenamestr, err := cast.ToStringE(filename) if err != nil { return nil, err } filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) } // GetMatch finds the first Resource matching the given pattern, or nil if none found. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.GetMatch(patternStr) } // 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 the files name with path relative to the file system 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. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) Match(pattern interface{}) (resource.Resources, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.Match(patternStr) } // Concat concatenates a slice of Resource objects. These resources must // (currently) be of the same Media Type. func (ns *Namespace) Concat(targetPathIn interface{}, r interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } var rr resource.Resources switch v := r.(type) { case resource.Resources: rr = v case resource.ResourcesConverter: rr = v.ToResources() default: return nil, fmt.Errorf("slice %T not supported in concat", r) } if len(rr) == 0 { return nil, errors.New("must provide one or more Resource objects to concat") } return ns.bundlerClient.Concat(targetPath, rr) } // FromString creates a Resource from a string published to the relative target path. func (ns *Namespace) FromString(targetPathIn, contentIn interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } content, err := cast.ToStringE(contentIn) if err != nil { return nil, err } return ns.createClient.FromString(targetPath, content) } // ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with // the given data, and published to the relative target path. func (ns *Namespace) ExecuteAsTemplate(args ...interface{}) (resource.Resource, error) { if len(args) != 3 { return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object") } targetPath, err := cast.ToStringE(args[0]) if err != nil { return nil, err } data := args[1] r, ok := args[2].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2]) } return ns.templatesClient.ExecuteAsTemplate(r, targetPath, data) } // Fingerprint transforms the given Resource with a MD5 hash of the content in // the RelPermalink and Permalink. func (ns *Namespace) Fingerprint(args ...interface{}) (resource.Resource, error) { if len(args) < 1 || len(args) > 2 { return nil, errors.New("must provide a Resource and (optional) crypto algo") } var algo string resIdx := 0 if len(args) == 2 { resIdx = 1 var err error algo, err = cast.ToStringE(args[0]) if err != nil { return nil, err } } r, ok := args[resIdx].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("%T can not be transformed", args[resIdx]) } return ns.integrityClient.Fingerprint(r, algo) } // Minify minifies the given Resource using the MediaType to pick the correct // minifier. func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) { return ns.minifyClient.Minify(r) } // ToCSS converts the given Resource to CSS. You can optional provide an Options // object or a target path (string) as first argument. func (ns *Namespace) ToCSS(args ...interface{}) (resource.Resource, error) { const ( // 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" ) var ( r resources.ResourceTransformer m map[string]interface{} targetPath string err error ok bool transpiler = transpilerLibSass ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if m != nil { maps.PrepareParams(m) if t, found := m["transpiler"]; found { switch t { case transpilerDart, transpilerLibSass: transpiler = cast.ToString(t) default: return nil, errors.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) } } } if transpiler == transpilerLibSass { var options scss.Options if targetPath != "" { options.TargetPath = helpers.ToSlashTrimLeading(targetPath) } else if m != nil { options, err = scss.DecodeOptions(m) if err != nil { return nil, err } } return ns.scssClientLibSass.ToCSS(r, options) } if m == nil { m = make(map[string]interface{}) } if targetPath != "" { m["targetPath"] = targetPath } client, err := ns.getscssClientDartSass() if err != nil { return nil, err } return client.ToCSS(r, m) } // PostCSS processes the given Resource with PostCSS func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options postcss.Options if m != nil { options, err = postcss.DecodeOptions(m) if err != nil { return nil, err } } return ns.postcssClient.Process(r, options) } func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) } // Babel processes the given Resource with Babel. func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options babel.Options if m != nil { options, err = babel.DecodeOptions(m) if err != nil { return nil, err } } return ns.babelClient.Process(r, options) }
// 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 provides template functions for working with resources. package resources import ( "fmt" "net/url" "path/filepath" "sync" "github.com/gohugoio/hugo/common/maps" "github.com/pkg/errors" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/bundler" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/resources/resource_transformers/babel" "github.com/gohugoio/hugo/resources/resource_transformers/integrity" "github.com/gohugoio/hugo/resources/resource_transformers/minifier" "github.com/gohugoio/hugo/resources/resource_transformers/postcss" "github.com/gohugoio/hugo/resources/resource_transformers/templates" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" "github.com/spf13/cast" ) // New returns a new instance of the resources-namespaced template functions. func New(deps *deps.Deps) (*Namespace, error) { if deps.ResourceSpec == nil { return &Namespace{}, nil } scssClient, err := scss.New(deps.BaseFs.Assets, deps.ResourceSpec) if err != nil { return nil, err } minifyClient, err := minifier.New(deps.ResourceSpec) if err != nil { return nil, err } return &Namespace{ deps: deps, scssClientLibSass: scssClient, createClient: create.New(deps.ResourceSpec), bundlerClient: bundler.New(deps.ResourceSpec), integrityClient: integrity.New(deps.ResourceSpec), minifyClient: minifyClient, postcssClient: postcss.New(deps.ResourceSpec), templatesClient: templates.New(deps.ResourceSpec, deps), babelClient: babel.New(deps.ResourceSpec), }, nil } // Namespace provides template functions for the "resources" namespace. type Namespace struct { deps *deps.Deps createClient *create.Client bundlerClient *bundler.Client scssClientLibSass *scss.Client integrityClient *integrity.Client minifyClient *minifier.Client postcssClient *postcss.Client babelClient *babel.Client templatesClient *templates.Client // The Dart Client requires a os/exec process, so only // create it if we really need it. // This is mostly to avoid creating one per site build test. scssClientDartSassInit sync.Once scssClientDartSass *dartsass.Client } func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) { var err error ns.scssClientDartSassInit.Do(func() { ns.scssClientDartSass, err = dartsass.New(ns.deps.BaseFs.Assets, ns.deps.ResourceSpec) if err != nil { return } ns.deps.BuildClosers.Add(ns.scssClientDartSass) }) return ns.scssClientDartSass, err } // Get locates the filename given in Hugo's assets filesystem or downloads // a file from an URL and creates a Resource object that can be used for // further transformations. // // For URLs an additional argument with options can be provided. func (ns *Namespace) Get(args ...interface{}) (resource.Resource, error) { if len(args) != 1 && len(args) != 2 { return nil, errors.New("must provide a filename or URL") } filenamestr, err := cast.ToStringE(args[0]) if err != nil { return nil, err } if u, err := url.Parse(filenamestr); err == nil && u.Scheme != "" { if len(args) == 2 { options, err := maps.ToStringMapE(args[1]) if err != nil { return nil, err } return ns.createClient.FromRemote(filenamestr, options) } return ns.createClient.FromRemote(filenamestr, nil) } filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) } // GetMatch finds the first Resource matching the given pattern, or nil if none found. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.GetMatch(patternStr) } // 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 the files name with path relative to the file system 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. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) Match(pattern interface{}) (resource.Resources, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.Match(patternStr) } // Concat concatenates a slice of Resource objects. These resources must // (currently) be of the same Media Type. func (ns *Namespace) Concat(targetPathIn interface{}, r interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } var rr resource.Resources switch v := r.(type) { case resource.Resources: rr = v case resource.ResourcesConverter: rr = v.ToResources() default: return nil, fmt.Errorf("slice %T not supported in concat", r) } if len(rr) == 0 { return nil, errors.New("must provide one or more Resource objects to concat") } return ns.bundlerClient.Concat(targetPath, rr) } // FromString creates a Resource from a string published to the relative target path. func (ns *Namespace) FromString(targetPathIn, contentIn interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } content, err := cast.ToStringE(contentIn) if err != nil { return nil, err } return ns.createClient.FromString(targetPath, content) } // ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with // the given data, and published to the relative target path. func (ns *Namespace) ExecuteAsTemplate(args ...interface{}) (resource.Resource, error) { if len(args) != 3 { return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object") } targetPath, err := cast.ToStringE(args[0]) if err != nil { return nil, err } data := args[1] r, ok := args[2].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2]) } return ns.templatesClient.ExecuteAsTemplate(r, targetPath, data) } // Fingerprint transforms the given Resource with a MD5 hash of the content in // the RelPermalink and Permalink. func (ns *Namespace) Fingerprint(args ...interface{}) (resource.Resource, error) { if len(args) < 1 || len(args) > 2 { return nil, errors.New("must provide a Resource and (optional) crypto algo") } var algo string resIdx := 0 if len(args) == 2 { resIdx = 1 var err error algo, err = cast.ToStringE(args[0]) if err != nil { return nil, err } } r, ok := args[resIdx].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("%T can not be transformed", args[resIdx]) } return ns.integrityClient.Fingerprint(r, algo) } // Minify minifies the given Resource using the MediaType to pick the correct // minifier. func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) { return ns.minifyClient.Minify(r) } // ToCSS converts the given Resource to CSS. You can optional provide an Options // object or a target path (string) as first argument. func (ns *Namespace) ToCSS(args ...interface{}) (resource.Resource, error) { const ( // 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" ) var ( r resources.ResourceTransformer m map[string]interface{} targetPath string err error ok bool transpiler = transpilerLibSass ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if m != nil { maps.PrepareParams(m) if t, found := m["transpiler"]; found { switch t { case transpilerDart, transpilerLibSass: transpiler = cast.ToString(t) default: return nil, errors.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) } } } if transpiler == transpilerLibSass { var options scss.Options if targetPath != "" { options.TargetPath = helpers.ToSlashTrimLeading(targetPath) } else if m != nil { options, err = scss.DecodeOptions(m) if err != nil { return nil, err } } return ns.scssClientLibSass.ToCSS(r, options) } if m == nil { m = make(map[string]interface{}) } if targetPath != "" { m["targetPath"] = targetPath } client, err := ns.getscssClientDartSass() if err != nil { return nil, err } return client.ToCSS(r, m) } // PostCSS processes the given Resource with PostCSS func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options postcss.Options if m != nil { options, err = postcss.DecodeOptions(m) if err != nil { return nil, err } } return ns.postcssClient.Process(r, options) } func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) } // Babel processes the given Resource with Babel. func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options babel.Options if m != nil { options, err = babel.DecodeOptions(m) if err != nil { return nil, err } } return ns.babelClient.Process(r, options) }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Remove `ns.FromRemove` and call the client directly (we do not want two template methods doing just about the same thing).
bep
183
gohugoio/hugo
9,185
Add remote support to resources.Get
Implement resources.FromRemote, inspired by #5686 Closes #5255 Supports #9044
null
2021-11-18 17:15:44+00:00
2021-11-30 10:49:52+00:00
tpl/resources/resources.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 provides template functions for working with resources. package resources import ( "fmt" "path/filepath" "sync" "github.com/gohugoio/hugo/common/maps" "github.com/pkg/errors" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/bundler" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/resources/resource_transformers/babel" "github.com/gohugoio/hugo/resources/resource_transformers/integrity" "github.com/gohugoio/hugo/resources/resource_transformers/minifier" "github.com/gohugoio/hugo/resources/resource_transformers/postcss" "github.com/gohugoio/hugo/resources/resource_transformers/templates" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" "github.com/spf13/cast" ) // New returns a new instance of the resources-namespaced template functions. func New(deps *deps.Deps) (*Namespace, error) { if deps.ResourceSpec == nil { return &Namespace{}, nil } scssClient, err := scss.New(deps.BaseFs.Assets, deps.ResourceSpec) if err != nil { return nil, err } minifyClient, err := minifier.New(deps.ResourceSpec) if err != nil { return nil, err } return &Namespace{ deps: deps, scssClientLibSass: scssClient, createClient: create.New(deps.ResourceSpec), bundlerClient: bundler.New(deps.ResourceSpec), integrityClient: integrity.New(deps.ResourceSpec), minifyClient: minifyClient, postcssClient: postcss.New(deps.ResourceSpec), templatesClient: templates.New(deps.ResourceSpec, deps), babelClient: babel.New(deps.ResourceSpec), }, nil } // Namespace provides template functions for the "resources" namespace. type Namespace struct { deps *deps.Deps createClient *create.Client bundlerClient *bundler.Client scssClientLibSass *scss.Client integrityClient *integrity.Client minifyClient *minifier.Client postcssClient *postcss.Client babelClient *babel.Client templatesClient *templates.Client // The Dart Client requires a os/exec process, so only // create it if we really need it. // This is mostly to avoid creating one per site build test. scssClientDartSassInit sync.Once scssClientDartSass *dartsass.Client } func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) { var err error ns.scssClientDartSassInit.Do(func() { ns.scssClientDartSass, err = dartsass.New(ns.deps.BaseFs.Assets, ns.deps.ResourceSpec) if err != nil { return } ns.deps.BuildClosers.Add(ns.scssClientDartSass) }) return ns.scssClientDartSass, err } // Get locates the filename given in Hugo's assets filesystem // and creates a Resource object that can be used for further transformations. func (ns *Namespace) Get(filename interface{}) (resource.Resource, error) { filenamestr, err := cast.ToStringE(filename) if err != nil { return nil, err } filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) } // GetMatch finds the first Resource matching the given pattern, or nil if none found. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.GetMatch(patternStr) } // 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 the files name with path relative to the file system 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. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) Match(pattern interface{}) (resource.Resources, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.Match(patternStr) } // Concat concatenates a slice of Resource objects. These resources must // (currently) be of the same Media Type. func (ns *Namespace) Concat(targetPathIn interface{}, r interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } var rr resource.Resources switch v := r.(type) { case resource.Resources: rr = v case resource.ResourcesConverter: rr = v.ToResources() default: return nil, fmt.Errorf("slice %T not supported in concat", r) } if len(rr) == 0 { return nil, errors.New("must provide one or more Resource objects to concat") } return ns.bundlerClient.Concat(targetPath, rr) } // FromString creates a Resource from a string published to the relative target path. func (ns *Namespace) FromString(targetPathIn, contentIn interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } content, err := cast.ToStringE(contentIn) if err != nil { return nil, err } return ns.createClient.FromString(targetPath, content) } // ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with // the given data, and published to the relative target path. func (ns *Namespace) ExecuteAsTemplate(args ...interface{}) (resource.Resource, error) { if len(args) != 3 { return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object") } targetPath, err := cast.ToStringE(args[0]) if err != nil { return nil, err } data := args[1] r, ok := args[2].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2]) } return ns.templatesClient.ExecuteAsTemplate(r, targetPath, data) } // Fingerprint transforms the given Resource with a MD5 hash of the content in // the RelPermalink and Permalink. func (ns *Namespace) Fingerprint(args ...interface{}) (resource.Resource, error) { if len(args) < 1 || len(args) > 2 { return nil, errors.New("must provide a Resource and (optional) crypto algo") } var algo string resIdx := 0 if len(args) == 2 { resIdx = 1 var err error algo, err = cast.ToStringE(args[0]) if err != nil { return nil, err } } r, ok := args[resIdx].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("%T can not be transformed", args[resIdx]) } return ns.integrityClient.Fingerprint(r, algo) } // Minify minifies the given Resource using the MediaType to pick the correct // minifier. func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) { return ns.minifyClient.Minify(r) } // ToCSS converts the given Resource to CSS. You can optional provide an Options // object or a target path (string) as first argument. func (ns *Namespace) ToCSS(args ...interface{}) (resource.Resource, error) { const ( // 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" ) var ( r resources.ResourceTransformer m map[string]interface{} targetPath string err error ok bool transpiler = transpilerLibSass ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if m != nil { maps.PrepareParams(m) if t, found := m["transpiler"]; found { switch t { case transpilerDart, transpilerLibSass: transpiler = cast.ToString(t) default: return nil, errors.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) } } } if transpiler == transpilerLibSass { var options scss.Options if targetPath != "" { options.TargetPath = helpers.ToSlashTrimLeading(targetPath) } else if m != nil { options, err = scss.DecodeOptions(m) if err != nil { return nil, err } } return ns.scssClientLibSass.ToCSS(r, options) } if m == nil { m = make(map[string]interface{}) } if targetPath != "" { m["targetPath"] = targetPath } client, err := ns.getscssClientDartSass() if err != nil { return nil, err } return client.ToCSS(r, m) } // PostCSS processes the given Resource with PostCSS func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options postcss.Options if m != nil { options, err = postcss.DecodeOptions(m) if err != nil { return nil, err } } return ns.postcssClient.Process(r, options) } func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) } // Babel processes the given Resource with Babel. func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options babel.Options if m != nil { options, err = babel.DecodeOptions(m) if err != nil { return nil, err } } return ns.babelClient.Process(r, options) }
// 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 provides template functions for working with resources. package resources import ( "fmt" "net/url" "path/filepath" "sync" "github.com/gohugoio/hugo/common/maps" "github.com/pkg/errors" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/postpub" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource_factories/bundler" "github.com/gohugoio/hugo/resources/resource_factories/create" "github.com/gohugoio/hugo/resources/resource_transformers/babel" "github.com/gohugoio/hugo/resources/resource_transformers/integrity" "github.com/gohugoio/hugo/resources/resource_transformers/minifier" "github.com/gohugoio/hugo/resources/resource_transformers/postcss" "github.com/gohugoio/hugo/resources/resource_transformers/templates" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" "github.com/spf13/cast" ) // New returns a new instance of the resources-namespaced template functions. func New(deps *deps.Deps) (*Namespace, error) { if deps.ResourceSpec == nil { return &Namespace{}, nil } scssClient, err := scss.New(deps.BaseFs.Assets, deps.ResourceSpec) if err != nil { return nil, err } minifyClient, err := minifier.New(deps.ResourceSpec) if err != nil { return nil, err } return &Namespace{ deps: deps, scssClientLibSass: scssClient, createClient: create.New(deps.ResourceSpec), bundlerClient: bundler.New(deps.ResourceSpec), integrityClient: integrity.New(deps.ResourceSpec), minifyClient: minifyClient, postcssClient: postcss.New(deps.ResourceSpec), templatesClient: templates.New(deps.ResourceSpec, deps), babelClient: babel.New(deps.ResourceSpec), }, nil } // Namespace provides template functions for the "resources" namespace. type Namespace struct { deps *deps.Deps createClient *create.Client bundlerClient *bundler.Client scssClientLibSass *scss.Client integrityClient *integrity.Client minifyClient *minifier.Client postcssClient *postcss.Client babelClient *babel.Client templatesClient *templates.Client // The Dart Client requires a os/exec process, so only // create it if we really need it. // This is mostly to avoid creating one per site build test. scssClientDartSassInit sync.Once scssClientDartSass *dartsass.Client } func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) { var err error ns.scssClientDartSassInit.Do(func() { ns.scssClientDartSass, err = dartsass.New(ns.deps.BaseFs.Assets, ns.deps.ResourceSpec) if err != nil { return } ns.deps.BuildClosers.Add(ns.scssClientDartSass) }) return ns.scssClientDartSass, err } // Get locates the filename given in Hugo's assets filesystem or downloads // a file from an URL and creates a Resource object that can be used for // further transformations. // // For URLs an additional argument with options can be provided. func (ns *Namespace) Get(args ...interface{}) (resource.Resource, error) { if len(args) != 1 && len(args) != 2 { return nil, errors.New("must provide a filename or URL") } filenamestr, err := cast.ToStringE(args[0]) if err != nil { return nil, err } if u, err := url.Parse(filenamestr); err == nil && u.Scheme != "" { if len(args) == 2 { options, err := maps.ToStringMapE(args[1]) if err != nil { return nil, err } return ns.createClient.FromRemote(filenamestr, options) } return ns.createClient.FromRemote(filenamestr, nil) } filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) } // GetMatch finds the first Resource matching the given pattern, or nil if none found. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.GetMatch(patternStr) } // 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 the files name with path relative to the file system 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. // // It looks for files in the assets file system. // // See Match for a more complete explanation about the rules used. func (ns *Namespace) Match(pattern interface{}) (resource.Resources, error) { patternStr, err := cast.ToStringE(pattern) if err != nil { return nil, err } return ns.createClient.Match(patternStr) } // Concat concatenates a slice of Resource objects. These resources must // (currently) be of the same Media Type. func (ns *Namespace) Concat(targetPathIn interface{}, r interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } var rr resource.Resources switch v := r.(type) { case resource.Resources: rr = v case resource.ResourcesConverter: rr = v.ToResources() default: return nil, fmt.Errorf("slice %T not supported in concat", r) } if len(rr) == 0 { return nil, errors.New("must provide one or more Resource objects to concat") } return ns.bundlerClient.Concat(targetPath, rr) } // FromString creates a Resource from a string published to the relative target path. func (ns *Namespace) FromString(targetPathIn, contentIn interface{}) (resource.Resource, error) { targetPath, err := cast.ToStringE(targetPathIn) if err != nil { return nil, err } content, err := cast.ToStringE(contentIn) if err != nil { return nil, err } return ns.createClient.FromString(targetPath, content) } // ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with // the given data, and published to the relative target path. func (ns *Namespace) ExecuteAsTemplate(args ...interface{}) (resource.Resource, error) { if len(args) != 3 { return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object") } targetPath, err := cast.ToStringE(args[0]) if err != nil { return nil, err } data := args[1] r, ok := args[2].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2]) } return ns.templatesClient.ExecuteAsTemplate(r, targetPath, data) } // Fingerprint transforms the given Resource with a MD5 hash of the content in // the RelPermalink and Permalink. func (ns *Namespace) Fingerprint(args ...interface{}) (resource.Resource, error) { if len(args) < 1 || len(args) > 2 { return nil, errors.New("must provide a Resource and (optional) crypto algo") } var algo string resIdx := 0 if len(args) == 2 { resIdx = 1 var err error algo, err = cast.ToStringE(args[0]) if err != nil { return nil, err } } r, ok := args[resIdx].(resources.ResourceTransformer) if !ok { return nil, fmt.Errorf("%T can not be transformed", args[resIdx]) } return ns.integrityClient.Fingerprint(r, algo) } // Minify minifies the given Resource using the MediaType to pick the correct // minifier. func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) { return ns.minifyClient.Minify(r) } // ToCSS converts the given Resource to CSS. You can optional provide an Options // object or a target path (string) as first argument. func (ns *Namespace) ToCSS(args ...interface{}) (resource.Resource, error) { const ( // 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" ) var ( r resources.ResourceTransformer m map[string]interface{} targetPath string err error ok bool transpiler = transpilerLibSass ) r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args) if !ok { r, m, err = resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } } if m != nil { maps.PrepareParams(m) if t, found := m["transpiler"]; found { switch t { case transpilerDart, transpilerLibSass: transpiler = cast.ToString(t) default: return nil, errors.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) } } } if transpiler == transpilerLibSass { var options scss.Options if targetPath != "" { options.TargetPath = helpers.ToSlashTrimLeading(targetPath) } else if m != nil { options, err = scss.DecodeOptions(m) if err != nil { return nil, err } } return ns.scssClientLibSass.ToCSS(r, options) } if m == nil { m = make(map[string]interface{}) } if targetPath != "" { m["targetPath"] = targetPath } client, err := ns.getscssClientDartSass() if err != nil { return nil, err } return client.ToCSS(r, m) } // PostCSS processes the given Resource with PostCSS func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options postcss.Options if m != nil { options, err = postcss.DecodeOptions(m) if err != nil { return nil, err } } return ns.postcssClient.Process(r, options) } func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) } // Babel processes the given Resource with Babel. func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { r, m, err := resourcehelpers.ResolveArgs(args) if err != nil { return nil, err } var options babel.Options if m != nil { options, err = babel.DecodeOptions(m) if err != nil { return nil, err } } return ns.babelClient.Process(r, options) }
vanbroup
75a823a36a75781c0c5d89fe9f328e3b9322d95f
8aa7257f652ebea70dfbb819c301800f5c25b567
Removed the `resources.FromRemote` call, extended test coverage and updated documentation.
vanbroup
184
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
I'm not totally sure I follow this logic. Given the example below, do I not get an ordered slice of items? ```xml <channel> <title>Example feed</title> <item> <title>Item 1</title> </item> <item> <title>Item 2</title> </item> </channel> ```
bep
185
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
I added this note following the comment by @jmooring https://github.com/gohugoio/hugo/pull/9044#issuecomment-947645742 and my reply below that. > @vanbroup > > > That limitation doesn't seem to be relevant to the usage in Hugo, does it? > > For ~the majority of~ some use cases I don't think it is relevant. But technically, a XML node has a name, value, and position. When you convert to a map you lose the position. > > data/foo.xml > > ``` > <?xml version="1.0" encoding="UTF-8"?> > <item> > <b>This is the first node</b> > <a>This is the second node</a> > <c>This is the third node</c> > </item> > ``` > > template > > ``` > <pre>{{ jsonify (dict "indent" " ") site.Data.foo }}</pre> > ``` > > output > > ``` > { > "item": { > "a": "This is the second node", > "b": "This is the first node", > "c": "This is the third node" > } > } > ```
vanbroup
186
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
Sure, I understand this re what I consider to be _map values_, but what about this example: ```xml <channel> <title>Example feed</title> <item> <title>Item 1</title> </item> <item> <title>Item 2</title> </item> </channel> ```
bep
187
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
Correct, I tested to be sure, but the order of a slice is preserved: ```json { "channel": { "item": [ { "title": "Item 1" }, { "title": "Item 2" } ], "title": "Example feed" } } ``` But the order of the values in an item not: ```xml <channel> <title>Example feed</title> <item> <title>Item 1</title> <description>Description 1</description> </item> <item> <title>Item 2</title> <description>Description 2</description> </item> </channel> ``` Results in a swapped order of the title and description: ```json { "channel": { "item": [ { "description": "Description 1", "title": "Item 1" }, { "description": "Description 2", "title": "Item 2" } ], "title": "Example feed" } } ``` I suggest we remove the warning as the order of a map is not relevant to how the values are used in Hugo.
vanbroup
188
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
I suggest we remove the warning as the order of a map is not relevant to how the values are used in Hugo. ```suggestion ```
vanbroup
189
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
We should remove the warning (as it confuses more than it helps), but the order is not irellevant: * When you iterate a map in a Go template, the keys are sorted (I assume ascending order) * When you marshal a Go map to JSON, the keys are sorted What I then would expect for XML is, most importantly, that it is consistent. We have a `Remarshal` func that has a roundtrip test that it would be good if you could add XML to to verify that these formats can be converted to/from.
bep
190
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
The XML specification requires a root element, parsing without a root element works but not for lists (such a resources in this example). ```xml <root> <resources> <params> <byline>picasso</byline> </params> <src>**image-4.png</src> <title>The Fourth Image!</title> </resources> <resources> <name>my-cool-image-:counter</name> <params> <byline>bep</byline> </params> <src>**.png</src> <title>TOML: The Image #:counter</title> </resources> <title>Test Metadata</title> </root> ``` `TestRemarshal` fails because it will encode with the unexpected root element: ``` --- FAIL: TestRemarshal (0.01s) remarshal_test.go:128: [XML => yaml] Expected resources: - params: byline: picasso src: '**image-4.png' title: The Fourth Image! - name: my-cool-image-:counter params: byline: bep src: '**.png' title: 'TOML: The Image #:counter' title: Test Metadata got root: resources: - params: byline: picasso src: '**image-4.png' title: The Fourth Image! - name: my-cool-image-:counter params: byline: bep src: '**.png' title: 'TOML: The Image #:counter' title: Test Metadata diff: [root:] remarshal_test.go:128: [XML => json] Expected { "resources": [ { "params": { "byline": "picasso" }, "src": "**image-4.png", "title": "The Fourth Image!" }, { "name": "my-cool-image-:counter", "params": { "byline": "bep" }, "src": "**.png", "title": "TOML: The Image #:counter" } ], "title": "Test Metadata" } got { "root": { "resources": [ { "params": { "byline": "picasso" }, "src": "**image-4.png", "title": "The Fourth Image!" }, { "name": "my-cool-image-:counter", "params": { "byline": "bep" }, "src": "**.png", "title": "TOML: The Image #:counter" } ], "title": "Test Metadata" } } diff: ["root":] remarshal_test.go:128: [XML => toml] Expected title = 'Test Metadata' [[resources]] src = '**image-4.png' title = 'The Fourth Image!' [resources.params] byline = 'picasso' [[resources]] name = 'my-cool-image-:counter' src = '**.png' title = 'TOML: The Image #:counter' [resources.params] byline = 'bep' got [root] title = 'Test Metadata' [[root.resources]] src = '**image-4.png' title = 'The Fourth Image!' [root.resources.params] byline = 'picasso' [[root.resources]] name = 'my-cool-image-:counter' src = '**.png' title = 'TOML: The Image #:counter' [root.resources.params] byline = 'bep' diff: [[root] [[resources]] [resources.params]] remarshal_test.go:128: [XML => TOML] Expected title = 'Test Metadata' [[resources]] src = '**image-4.png' title = 'The Fourth Image!' [resources.params] byline = 'picasso' [[resources]] name = 'my-cool-image-:counter' src = '**.png' title = 'TOML: The Image #:counter' [resources.params] byline = 'bep' got [root] title = 'Test Metadata' [[root.resources]] src = '**image-4.png' title = 'The Fourth Image!' [root.resources.params] byline = 'picasso' [[root.resources]] name = 'my-cool-image-:counter' src = '**.png' title = 'TOML: The Image #:counter' [root.resources.params] byline = 'bep' diff: [[[resources]] [root] [resources.params]] remarshal_test.go:128: [XML => Toml] Expected title = 'Test Metadata' [[resources]] src = '**image-4.png' title = 'The Fourth Image!' [resources.params] byline = 'picasso' [[resources]] name = 'my-cool-image-:counter' src = '**.png' title = 'TOML: The Image #:counter' [resources.params] byline = 'bep' got [root] title = 'Test Metadata' [[root.resources]] src = '**image-4.png' title = 'The Fourth Image!' [root.resources.params] byline = 'picasso' [[root.resources]] name = 'my-cool-image-:counter' src = '**.png' title = 'TOML: The Image #:counter' [root.resources.params] byline = 'bep' diff: [[resources.params] [root] [[resources]]] remarshal_test.go:128: [XML => TOML ] Expected title = 'Test Metadata' [[resources]] src = '**image-4.png' title = 'The Fourth Image!' [resources.params] byline = 'picasso' [[resources]] name = 'my-cool-image-:counter' src = '**.png' title = 'TOML: The Image #:counter' [resources.params] byline = 'bep' got [root] title = 'Test Metadata' [[root.resources]] src = '**image-4.png' title = 'The Fourth Image!' [root.resources.params] byline = 'picasso' [[root.resources]] name = 'my-cool-image-:counter' src = '**.png' title = 'TOML: The Image #:counter' [root.resources.params] byline = 'bep' diff: [[[resources]] [resources.params] [root]] ``` I can 'fix' this by automatically removing any root element in the `metadecorders` which might give some unexpected results or expect these exceptions in the test. What do you think @bep?
vanbroup
191
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
Just drop the remarshal thing for now. One question: * What parts of Hugo do XML work with with this PR? * I assume `reosurces.Get` and /data; for /data; what is the root key for `mydata.xml` with root `<root>`? `mydata.root.*`?
bep
192
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
The root key is defined by the xml, so for RSS the key is `rss` as the document starts with `<rss>` and ends with `</rss>`. In this example the root key would be `note` and you would use `note.body`: ```xml <?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> ``` The current code works for `resources.Get` and the `/data` directory. It doesn't work for configs as Hugo is not expecting a root element. Dropping the root element would work as follows: ```go case XML: var xmlRoot xml.Map xmlRoot, err = xml.NewMapXml(data) var xmlValue map[string]interface{} if err == nil { xmlRootName, err := xmlRoot.Root() if err != nil { return toFileError(f, errors.Wrap(err, "failed to unmarshal XML")) } xmlValue = xmlRoot[xmlRootName].(map[string]interface{}) } ``` After which you would skip the root element so just `body` in the example above or this for an RSS feed (`{{ range .channel.item }}` instead of `{{ range .rss.channel.item }}`: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
193
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
I'll bring @jmooring into this discussion. I think we need to get this right, as these kind of things are extremely hard to take back/change. ``` data └── notes β”œβ”€β”€ note1.xml └── note2.xml ``` So, given the above, we currently get `site.Data.notes.note1.note.title` (or something). Which seems a little stuttery to me ... Also, it would be nice to get the different types (JSON, XML, YAML, TOML) as similar as possible in the structure.
bep
194
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
It would indeed be `site.Data.notes.note1.note.title` I also have a version ready that would strip the root element which would make it `site.Data.notes.note1.title`. But the root element would still be in the source file which could be confusing. For frontmatter and configs we could wrap the information in a `<hugo>` root element and only strip the root element if it's called `hugo`, which makes the `TestRemarshal` happy.
vanbroup
195
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
>For frontmatter and configs I need to sleep on this, but for frontmatter and config (if we want to got down that route) I would imagine that we would repeat the _topic_ so it would be `<frontmatter></frontmatter>` and `<config></config>` (the latter in a file named `config.xml`).
bep
196
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
XML for frontmatter and config? Please, no, no, no. I don't like the idea of swallowing the root node, because it might provide context. This is contrived, but worth thinking about. ```text data └── messages/ β”œβ”€β”€ message-1.xml β”œβ”€β”€ message-2.xml └── message-3.xml ```` data/messages/message-1.xml ```xml <info> <body>The engine is warm.</body> </info> ``` data/messages/message-2.xml ```xml <warning> <body>The engine is hot.</body> </warning> ``` data/messages/message-3.xml ```xml <error> <body>The engine is on fire.</body> </error> ```
jmooring
197
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
Yeah, well, those aren't messages. If they were messages, they'd be wrapped in a message (root) node. I think it's reasonable to tell a site author, "Hey, if you drop an XML file in the data/books/ directory, it's a book." So swallow the root node. Sorry for the noise.
jmooring
198
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
> XML for frontmatter and config? Please, no, no, no. The reason to swallow the root node would be to support XML for frontmatter and config as these have a defined format and do not expect the root node. If we don't care about XML for frontmatter and config, which I can't imagine anyone would want to use, we should keep the root node. The good thing is, if we would want to support XML for frontmatter or config later, we can just swallow these specific root nodes (or in that context somehow). I would suggest to leave it as it's now, just for `resources.Get` and `/data` without frontmatter and config support, and without modifying the XML (inclusive the root node).
vanbroup
199
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
> The reason to swallow the root node would be to support XML for frontmatter and config And to make XML consumption like JSON/YAML/TOML consumption... bep's point about stuttery syntax is dead on. A site author says, "So let me get this straight. If I want to access the title, I can do `site.Data.books.mybook.title` if it's a JSON/YAML/TOML file, but I have to do `site.Data.books.mybook.book.title` if it's an XML file. Why did they decide to do it that way?" I don't want to have answer that question.
jmooring
200
gohugoio/hugo
9,044
Implement XML data support
Implement XML data support Sample usage: ``` {{ with resources.Get "https://www.w3schools.com/xml/note.xml" | transform.Unmarshal }} {{ .note.body }} {{ end }} ``` A common usage: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .rss.channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ``` Closes #4470
null
2021-10-15 14:25:45+00:00
2021-12-02 16:30:36+00:00
docs/content/en/functions/transform.Unmarshal.md
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ```
--- title: "transform.Unmarshal" description: "`transform.Unmarshal` (alias `unmarshal`) parses the input and converts it into a map or an array. Supported formats are JSON, TOML, YAML, XML and CSV." date: 2018-12-23 categories: [functions] menu: docs: parent: "functions" keywords: [] signature: ["RESOURCE or STRING | transform.Unmarshal [OPTIONS]"] hugoversion: "0.53" aliases: [] --- The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map: ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | transform.Unmarshal }}` ``` ```go-html-template {{ $greetings := "hello = \"Hello Hugo\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }} ``` In both the above examples, you get a map you can work with: ```go-html-template {{ $greetings.hello }} ``` The above prints `Hello Hugo`. ## CSV Options Unmarshal with CSV as input has some options you can set: delimiter : The delimiter used, default is `,`. comment : The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.: Example: ```go-html-template {{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }} ``` ## XML data As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data. To get the contents of `<title>` in the document below, you use `{{ .message.title }}`: ``` <root> <message> <title>Hugo rocks!</title> <description>Thanks for using Hugo</description> </message> </root> ``` The following example lists the items of an RSS feed: ``` {{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }} {{ range .channel.item }} <strong>{{ .title | plainify | htmlUnescape }}</strong><br /> <p>{{ .description | plainify | htmlUnescape }}</p> {{ $link := .link | plainify | htmlUnescape }} <a href="{{ $link }}">{{ $link }}</a><br /> <hr> {{ end }} {{ end }} ```
vanbroup
58adbeef88ea5c8769d12ba27eef2d89bdf575eb
0eaaa8fee37068bfc8ecfb760f770ecc9a7af22a
Is that not exactly the question to expect when you modify the XML? XML comes with the root element to my knowledge you always need to specify the root element when querying the contents. It's simple to remove, but I would be concerned that this would raise questions instead of removing them.
vanbroup
201