diff options
author | Bjørn Erik Pedersen <[email protected]> | 2020-12-02 13:23:25 +0100 |
---|---|---|
committer | Bjørn Erik Pedersen <[email protected]> | 2020-12-03 13:12:58 +0100 |
commit | d90e37e0c6e812f9913bf256c9c81aa05b7a08aa (patch) | |
tree | 7b1b14464eefec1188ca2eed53c64e4823453cc9 | |
parent | 32471b57bde51c55a15dbf1db75d6e5f7232c347 (diff) | |
download | hugo-d90e37e0c6e812f9913bf256c9c81aa05b7a08aa.tar.gz hugo-d90e37e0c6e812f9913bf256c9c81aa05b7a08aa.zip |
all: Format code with gofumpt
See https://github.com/mvdan/gofumpt
442 files changed, 1423 insertions, 2251 deletions
diff --git a/cache/filecache/filecache.go b/cache/filecache/filecache.go index 37870dd5f..c586f9a51 100644 --- a/cache/filecache/filecache.go +++ b/cache/filecache/filecache.go @@ -158,7 +158,6 @@ func (c *Cache) ReadOrCreate(id string, err = create(info, f) return - } // GetOrCreate tries to get the file with the given id from cache. If not found or expired, create will @@ -220,7 +219,6 @@ func (c *Cache) GetOrCreateBytes(id string, create func() ([]byte, error)) (Item return info, nil, err } return info, b, nil - } // GetBytes gets the file content with the given id from the cahce, nil if none found. @@ -276,7 +274,6 @@ func (c *Cache) getOrRemove(id string) hugio.ReadSeekCloser { } f, err := c.Fs.Open(id) - if err != nil { return nil } @@ -299,7 +296,6 @@ func (c *Cache) getString(id string) string { defer c.nlocker.Unlock(id) f, err := c.Fs.Open(id) - if err != nil { return "" } @@ -307,7 +303,6 @@ func (c *Cache) getString(id string) string { b, _ := ioutil.ReadAll(f) return string(b) - } // Caches is a named set of caches. diff --git a/cache/filecache/filecache_config_test.go b/cache/filecache/filecache_config_test.go index 9f80a4f90..cd1d2c82a 100644 --- a/cache/filecache/filecache_config_test.go +++ b/cache/filecache/filecache_config_test.go @@ -69,7 +69,6 @@ dir = "/path/to/c3" c3 := decoded["images"] c.Assert(c3.MaxAge, qt.Equals, time.Duration(-1)) c.Assert(c3.Dir, qt.Equals, filepath.FromSlash("/path/to/c3/filecache/images")) - } func TestDecodeConfigIgnoreCache(t *testing.T) { @@ -110,7 +109,6 @@ dir = "/path/to/c3" for _, v := range decoded { c.Assert(v.MaxAge, qt.Equals, time.Duration(0)) } - } func TestDecodeConfigDefault(t *testing.T) { @@ -178,7 +176,6 @@ dir = "/" _, err = DecodeConfig(fs, cfg) c.Assert(err, qt.Not(qt.IsNil)) - } func newTestConfig() *viper.Viper { diff --git a/cache/filecache/filecache_pruner.go b/cache/filecache/filecache_pruner.go index b77f5331b..db1875701 100644 --- a/cache/filecache/filecache_pruner.go +++ b/cache/filecache/filecache_pruner.go @@ -110,7 +110,6 @@ func (c *Cache) Prune(force bool) (int, error) { } func (c *Cache) pruneRootDir(force bool) (int, error) { - info, err := c.Fs.Stat(c.pruneAllRootDir) if err != nil { if os.IsNotExist(err) { @@ -124,5 +123,4 @@ func (c *Cache) pruneRootDir(force bool) (int, error) { } return hugofs.MakeReadableAndRemoveAllModulePkgDir(c.Fs, c.pruneAllRootDir) - } diff --git a/cache/filecache/filecache_pruner_test.go b/cache/filecache/filecache_pruner_test.go index 48bce723e..46e1317ce 100644 --- a/cache/filecache/filecache_pruner_test.go +++ b/cache/filecache/filecache_pruner_test.go @@ -107,5 +107,4 @@ dir = ":resourceDir/_gen" } } - } diff --git a/cache/filecache/filecache_test.go b/cache/filecache/filecache_test.go index 00b4e5573..6a051a264 100644 --- a/cache/filecache/filecache_test.go +++ b/cache/filecache/filecache_test.go @@ -183,7 +183,6 @@ dir = ":cacheDir/c" c.Assert(string(b), qt.Equals, "Hugo is great!") } - } func TestFileCacheConcurrent(t *testing.T) { @@ -253,7 +252,6 @@ func TestFileCacheReadOrCreateErrorInRead(t *testing.T) { var result string rf := func(failLevel int) func(info ItemInfo, r io.ReadSeeker) error { - return func(info ItemInfo, r io.ReadSeeker) error { if failLevel > 0 { if failLevel > 1 { @@ -347,5 +345,4 @@ func newPathsSpec(t *testing.T, fs afero.Fs, configStr string) *helpers.PathSpec p, err := helpers.NewPathSpec(hugofs.NewFrom(fs, cfg), cfg, nil) c.Assert(err, qt.IsNil) return p - } diff --git a/cache/namedmemcache/named_cache.go b/cache/namedmemcache/named_cache.go index d8c229a01..d67bcc28a 100644 --- a/cache/namedmemcache/named_cache.go +++ b/cache/namedmemcache/named_cache.go @@ -49,7 +49,6 @@ func (c *Cache) Clear() { c.cache = make(map[string]cacheEntry) c.nlocker = locker.NewLocker() - } // GetOrCreate tries to get the value with the given cache key, if not found diff --git a/codegen/methods.go b/codegen/methods.go index ed8dba923..38477e333 100644 --- a/codegen/methods.go +++ b/codegen/methods.go @@ -58,7 +58,7 @@ func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.T var methods Methods - var excludes = make(map[string]bool) + excludes := make(map[string]bool) if len(exclude) > 0 { for _, m := range c.MethodsFromTypes(exclude, nil) { @@ -99,11 +99,9 @@ func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.T name = pkgPrefix + name return name, pkg - } for _, t := range include { - for i := 0; i < t.NumMethod(); i++ { m := t.Method(i) @@ -153,7 +151,6 @@ func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.T methods = append(methods, method) } - } sort.SliceStable(methods, func(i, j int) bool { @@ -167,16 +164,13 @@ func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.T } return wi < wj - }) return methods - } func (c *Inspector) parseSource() { c.init.Do(func() { - if !strings.Contains(c.ProjectRootDir, "hugo") { panic("dir must be set to the Hugo root") } @@ -200,7 +194,6 @@ func (c *Inspector) parseSource() { filenames = append(filenames, path) return nil - }) for _, filename := range filenames { @@ -230,7 +223,6 @@ func (c *Inspector) parseSource() { c.methodWeight[iface] = weights } } - } return true }) @@ -247,7 +239,6 @@ func (c *Inspector) parseSource() { } } } - }) } @@ -385,7 +376,7 @@ func (m Methods) ToMarshalJSON(receiver, pkgPath string, excludes ...string) (st fmt.Fprintf(&sb, "func Marshal%sToJSON(%s %s) ([]byte, error) {\n", what, r, receiver) var methods Methods - var excludeRes = make([]*regexp.Regexp, len(excludes)) + excludeRes := make([]*regexp.Regexp, len(excludes)) for i, exclude := range excludes { excludeRes[i] = regexp.MustCompile(exclude) @@ -450,7 +441,6 @@ func (m Methods) ToMarshalJSON(receiver, pkgPath string, excludes ...string) (st } return sb.String(), pkgImports - } func collectMethodsRecursive(pkg string, f []*ast.Field) []string { @@ -481,7 +471,6 @@ func collectMethodsRecursive(pkg string, f []*ast.Field) []string { } return methodNames - } func firstToLower(name string) string { @@ -544,5 +533,4 @@ func varName(name string) string { } return name - } diff --git a/codegen/methods_test.go b/codegen/methods_test.go index 77399f4e4..66000f4e9 100644 --- a/codegen/methods_test.go +++ b/codegen/methods_test.go @@ -25,7 +25,6 @@ import ( ) func TestMethods(t *testing.T) { - var ( zeroIE = reflect.TypeOf((*IEmbed)(nil)).Elem() zeroIEOnly = reflect.TypeOf((*IEOnly)(nil)).Elem() @@ -58,7 +57,6 @@ func TestMethods(t *testing.T) { methodsStr := fmt.Sprint(methods) c.Assert(methodsStr, qt.Contains, "MethodEmbed3(arg0 string) string") - }) t.Run("ToMarshalJSON", func(t *testing.T) { @@ -76,9 +74,7 @@ func TestMethods(t *testing.T) { c.Assert(pkg, qt.Contains, "encoding/json") fmt.Println(pkg) - }) - } type I interface { diff --git a/commands/check.go b/commands/check.go index f36f23969..f9be84852 100644 --- a/commands/check.go +++ b/commands/check.go @@ -26,9 +26,10 @@ type checkCmd struct { } func newCheckCmd() *checkCmd { - return &checkCmd{baseCmd: &baseCmd{cmd: &cobra.Command{ - Use: "check", - Short: "Contains some verification checks", - }, + return &checkCmd{baseCmd: &baseCmd{ + cmd: &cobra.Command{ + Use: "check", + Short: "Contains some verification checks", + }, }} } diff --git a/commands/check_darwin.go b/commands/check_darwin.go index 9291be84c..ac542916d 100644 --- a/commands/check_darwin.go +++ b/commands/check_darwin.go @@ -24,10 +24,11 @@ type checkCmd struct { } func newCheckCmd() *checkCmd { - cc := &checkCmd{baseCmd: &baseCmd{cmd: &cobra.Command{ - Use: "check", - Short: "Contains some verification checks", - }, + cc := &checkCmd{baseCmd: &baseCmd{ + cmd: &cobra.Command{ + Use: "check", + Short: "Contains some verification checks", + }, }} cc.cmd.AddCommand(newLimitCmd().getCommand()) diff --git a/commands/commandeer.go b/commands/commandeer.go index e0eae4a66..024651aad 100644 --- a/commands/commandeer.go +++ b/commands/commandeer.go @@ -16,24 +16,22 @@ package commands import ( "bytes" "errors" + "io/ioutil" + "os" + "path/filepath" + "regexp" "sync" + "time" hconfig "github.com/gohugoio/hugo/config" "golang.org/x/sync/semaphore" - "io/ioutil" - "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugo" jww "github.com/spf13/jwalterweatherman" - "os" - "path/filepath" - "regexp" - "time" - "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config" @@ -156,7 +154,6 @@ func (c *commandeer) initFs(fs *hugofs.Fs) error { } func newCommandeer(mustHaveConfigFile, running bool, h *hugoBuilderCommon, f flagsToConfigHandler, cfgInit func(c *commandeer) error, subCmdVs ...*cobra.Command) (*commandeer, error) { - var rebuildDebouncer func(f func()) if running { // The time value used is tested with mass content replacements in a fairly big Hugo site. @@ -248,7 +245,6 @@ func (f *fileChangeDetector) PrepareNew() { } func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { - if c.DepsCfg == nil { c.DepsCfg = &deps.DepsCfg{} } @@ -277,7 +273,6 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { environment := c.h.getEnvironment(running) doWithConfig := func(cfg config.Provider) error { - if c.ftch != nil { c.ftch.flagsToConfig(cfg) } @@ -309,7 +304,8 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { Filename: c.h.cfgFile, AbsConfigDir: c.h.getConfigDir(dir), Environ: os.Environ(), - Environment: environment}, + Environment: environment, + }, cfgSetAndInit, doWithConfig) @@ -389,7 +385,7 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { } // To debug hard-to-find path issues. - //fs.Destination = hugofs.NewStacktracerFs(fs.Destination, `fr/fr`) + // fs.Destination = hugofs.NewStacktracerFs(fs.Destination, `fr/fr`) err = c.initFs(fs) if err != nil { @@ -402,7 +398,6 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { h, err = hugolib.NewHugoSites(*c.DepsCfg) c.hugoSites = h close(c.created) - }) if err != nil { @@ -418,5 +413,4 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { cfg.Logger.Infoln("Using config file:", config.ConfigFileUsed()) return nil - } diff --git a/commands/commands.go b/commands/commands.go index ce5f0ff7d..1135dc01a 100644 --- a/commands/commands.go +++ b/commands/commands.go @@ -88,6 +88,7 @@ var _ commandsBuilderGetter = (*baseBuilderCmd)(nil) type commandsBuilderGetter interface { getCommandsBuilder() *commandsBuilder } + type baseBuilderCmd struct { *baseCmd *commandsBuilder @@ -138,7 +139,6 @@ func (c *nilCommand) getCommand() *cobra.Command { } func (c *nilCommand) flagsToConfig(cfg config.Provider) { - } func (b *commandsBuilder) newHugoCmd() *hugoCmd { diff --git a/commands/commands_test.go b/commands/commands_test.go index 22e996853..0b1543169 100644 --- a/commands/commands_test.go +++ b/commands/commands_test.go @@ -35,7 +35,6 @@ import ( ) func TestExecute(t *testing.T) { - c := qt.New(t) createSite := func(c *qt.C) (string, func()) { @@ -124,7 +123,6 @@ func TestExecute(t *testing.T) { c.Assert(config, qt.Contains, "baseURL = \"http://example.org/\"") checkNewSiteInited(c, siteDir) }) - } func checkNewSiteInited(c *qt.C, basepath string) { @@ -185,7 +183,8 @@ func TestFlags(t *testing.T) { }, { name: "Persistent flags", - args: []string{"server", + args: []string{ + "server", "--config=myconfig.toml", "--configDir=myconfigdir", "--contentDir=mycontent", @@ -235,12 +234,12 @@ func TestFlags(t *testing.T) { // The flag is named i18n-warnings c.Assert(cfg.GetBool("logI18nWarnings"), qt.Equals, true) - - }}} + }, + }, + } for _, test := range tests { c.Run(test.name, func(c *qt.C) { - b := newCommandsBuilder() root := b.addAll().build() @@ -257,11 +256,9 @@ func TestFlags(t *testing.T) { test.check(c, b.commands[0].(*serverCmd)) }) } - } func TestCommandsExecute(t *testing.T) { - c := qt.New(t) dir, clean, err := createSimpleTestSite(t, testSiteConfig{}) @@ -330,7 +327,6 @@ func TestCommandsExecute(t *testing.T) { } } - } type testSiteConfig struct { @@ -399,7 +395,6 @@ Environment: {{ hugo.Environment }} `) return d, clean, nil - } func writeFile(t *testing.T, filename, content string) { diff --git a/commands/convert.go b/commands/convert.go index d8976f7ea..3047add0b 100644 --- a/commands/convert.go +++ b/commands/convert.go @@ -16,6 +16,7 @@ package commands import ( "bytes" "fmt" + "path/filepath" "strings" "time" @@ -34,14 +35,10 @@ import ( "github.com/gohugoio/hugo/hugolib" - "path/filepath" - "github.com/spf13/cobra" ) -var ( - _ cmder = (*convertCmd)(nil) -) +var _ cmder = (*convertCmd)(nil) type convertCmd struct { outputDir string diff --git a/commands/env.go b/commands/env.go index 76c16b93b..975c3bd0a 100644 --- a/commands/env.go +++ b/commands/env.go @@ -27,18 +27,19 @@ type envCmd struct { } func newEnvCmd() *envCmd { - return &envCmd{baseCmd: newBaseCmd(&cobra.Command{ - Use: "env", - Short: "Print Hugo version and environment info", - Long: `Print Hugo version and environment info. This is useful in Hugo bug reports.`, - RunE: func(cmd *cobra.Command, args []string) error { - printHugoVersion() - jww.FEEDBACK.Printf("GOOS=%q\n", runtime.GOOS) - jww.FEEDBACK.Printf("GOARCH=%q\n", runtime.GOARCH) - jww.FEEDBACK.Printf("GOVERSION=%q\n", runtime.Version()) + return &envCmd{ + baseCmd: newBaseCmd(&cobra.Command{ + Use: "env", + Short: "Print Hugo version and environment info", + Long: `Print Hugo version and environment info. This is useful in Hugo bug reports.`, + RunE: func(cmd *cobra.Command, args []string) error { + printHugoVersion() + jww.FEEDBACK.Printf("GOOS=%q\n", runtime.GOOS) + jww.FEEDBACK.Printf("GOARCH=%q\n", runtime.GOARCH) + jww.FEEDBACK.Printf("GOVERSION=%q\n", runtime.Version()) - return nil - }, - }), + return nil + }, + }), } } diff --git a/commands/genautocomplete.go b/commands/genautocomplete.go index b0b98abb4..e8d9890cf 100644 --- a/commands/genautocomplete.go +++ b/commands/genautocomplete.go @@ -59,7 +59,6 @@ or just source them in directly: } err := cmd.Root().GenBashCompletionFile(cc.autocompleteTarget) - if err != nil { return err } diff --git a/commands/genchromastyles.go b/commands/genchromastyles.go index 6d54b6ab4..53fb2be6a 100644 --- a/commands/genchromastyles.go +++ b/commands/genchromastyles.go @@ -22,9 +22,7 @@ import ( "github.com/spf13/cobra" ) -var ( - _ cmder = (*genChromaStyles)(nil) -) +var _ cmder = (*genChromaStyles)(nil) type genChromaStyles struct { style string diff --git a/commands/gendocshelper.go b/commands/gendocshelper.go index 68ac035ee..34d45154f 100644 --- a/commands/gendocshelper.go +++ b/commands/gendocshelper.go @@ -23,9 +23,7 @@ import ( "github.com/spf13/cobra" ) -var ( - _ cmder = (*genDocsHelper)(nil) -) +var _ cmder = (*genDocsHelper)(nil) type genDocsHelper struct { target string @@ -70,5 +68,4 @@ func (g *genDocsHelper) generate() error { fmt.Println("Done!") return nil - } diff --git a/commands/hugo.go b/commands/hugo.go index 58f33b775..b850f7e65 100644 --- a/commands/hugo.go +++ b/commands/hugo.go @@ -19,10 +19,16 @@ 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" @@ -34,18 +40,10 @@ import ( "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/terminal" - "syscall" - "github.com/gohugoio/hugo/hugolib/filesystems" "golang.org/x/sync/errgroup" - "os" - "path/filepath" - "runtime" - "strings" - "time" - "github.com/gohugoio/hugo/config" flag "github.com/spf13/pflag" @@ -82,7 +80,6 @@ func (r Response) IsUserError() bool { // 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) @@ -120,14 +117,12 @@ func initializeConfig(mustHaveConfigFile, running bool, h *hugoBuilderCommon, f flagsToConfigHandler, cfgInit func(c *commandeer) error) (*commandeer, error) { - c, err := newCommandeer(mustHaveConfigFile, running, h, f, cfgInit) if err != nil { return nil, err } return c, nil - } func (c *commandeer) createLogger(cfg config.Provider, running bool) (loggers.Logger, error) { @@ -246,7 +241,6 @@ func initializeFlags(cmd *cobra.Command, cfg config.Provider) { setValueFromFlag(cmd.Flags(), "destination", cfg, "publishDir", false) setValueFromFlag(cmd.Flags(), "i18n-warnings", cfg, "logI18nWarnings", false) setValueFromFlag(cmd.Flags(), "path-warnings", cfg, "logPathWarnings", false) - } func setValueFromFlag(flags *flag.FlagSet, key string, cfg config.Provider, targetKey string, force bool) { @@ -282,7 +276,6 @@ func isTerminal() bool { } func (c *commandeer) fullBuild() error { - var ( g errgroup.Group langCount map[string]uint64 @@ -298,7 +291,6 @@ func (c *commandeer) fullBuild() error { } copyStaticFunc := func() error { - cnt, err := c.copyStatic() if err != nil { return errors.Wrap(err, "Error copying static files") @@ -346,7 +338,6 @@ func (c *commandeer) fullBuild() error { } return nil - } func (c *commandeer) initCPUProfile() (func(), error) { @@ -419,7 +410,6 @@ func (c *commandeer) initMutexProfile() (func(), error) { pprof.Lookup("mutex").WriteTo(f, 0) f.Close() }, nil - } func (c *commandeer) initMemTicker() func() { @@ -429,7 +419,6 @@ func (c *commandeer) initMemTicker() 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() { @@ -442,7 +431,6 @@ func (c *commandeer) initMemTicker() func() { printMem() return } - } }() @@ -452,7 +440,6 @@ func (c *commandeer) initMemTicker() func() { } func (c *commandeer) initProfiling() (func(), error) { - stopCPUProf, err := c.initCPUProfile() if err != nil { return nil, err @@ -538,7 +525,7 @@ func (c *commandeer) build() error { checkErr(c.Logger, err) defer watcher.Close() - var sigs = make(chan os.Signal, 1) + sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) <-sigs @@ -584,7 +571,6 @@ func (c *commandeer) copyStatic() (map[string]uint64, error) { } 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 @@ -712,7 +698,6 @@ func (c *commandeer) getDirList() ([]string, error) { } return nil - } watchFiles := c.hugo().PathSpec.BaseFs.WatchDirs() @@ -753,7 +738,6 @@ func (c *commandeer) rebuildSites(events []fsnotify.Event) error { 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) @@ -763,7 +747,6 @@ func (c *commandeer) rebuildSites(events []fsnotify.Event) error { home := c.hugo().PathSpec.PrependBasePath("/"+langPath, false) visited[home] = true } - } return c.hugo().Build(hugolib.BuildCfg{RecentlyVisited: visited, ErrRecovery: c.wasError}, events...) } @@ -793,13 +776,11 @@ func (c *commandeer) fullRebuild(changeType string) { 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. @@ -848,7 +829,6 @@ func (c *commandeer) newWatcher(dirList ...string) (*watcher.Batcher, error) { } watcher, err := watcher.New(1 * time.Second) - if err != nil { return nil, err } @@ -909,7 +889,6 @@ func (c *commandeer) handleEvents(watcher *watcher.Batcher, staticSyncer *staticSyncer, evs []fsnotify.Event, configSet map[string]bool) { - defer func() { c.wasError = false }() @@ -950,7 +929,6 @@ func (c *commandeer) handleEvents(watcher *watcher.Batcher, time.Sleep(100 * time.Millisecond) } } - } // Config file(s) changed. Need full rebuild. @@ -1194,7 +1172,6 @@ func partitionDynamicEvents(sourceFs *filesystems.SourceFilesystems, events []fs } } return - } func pickOneWriteOrCreatePath(events []fsnotify.Event) string { diff --git a/commands/hugo_test.go b/commands/hugo_test.go index 65a0416c7..4bead09f0 100644 --- a/commands/hugo_test.go +++ b/commands/hugo_test.go @@ -44,5 +44,4 @@ contentDir = "thisdoesnotexist" _, err = cmd.ExecuteC() c.Assert(err, qt.IsNil) - } diff --git a/commands/import_jekyll.go b/commands/import_jekyll.go index 2dd0fc051..b9ea56d4b 100644 --- a/commands/import_jekyll.go +++ b/commands/import_jekyll.go @@ -74,11 +74,9 @@ Import from Jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root cc.cmd.AddCommand(importJekyllCmd) return cc - } func (i *importCmd) importFromJekyll(cmd *cobra.Command, args []string) error { - if len(args) < 2 { return newUserError(`import from jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.") } @@ -255,13 +253,11 @@ func (i *importCmd) loadJekyllConfig(fs afero.Fs, jekyllRoot string) map[string] defer f.Close() b, err := ioutil.ReadAll(f) - if err != nil { return nil } c, err := metadecoders.Default.UnmarshalToMap(b, metadecoders.YAML) - if err != nil { return nil } @@ -338,8 +334,10 @@ func (i *importCmd) copyJekyllFilesAndFolders(jekyllRoot, dest string, jekyllPos } } else { lowerEntryName := strings.ToLower(entry.Name()) - exceptSuffix := []string{".md", ".markdown", ".html", ".htm", - ".xml", ".textile", "rakefile", "gemfile", ".lock"} + exceptSuffix := []string{ + ".md", ".markdown", ".html", ".htm", + ".xml", ".textile", "rakefile", "gemfile", ".lock", + } isExcept := false for _, suffix := range exceptSuffix { if strings.HasSuffix(lowerEntryName, suffix) { @@ -602,8 +600,8 @@ func replaceImageTag(match string) string { } result.WriteString(">}}") return result.String() - } + func replaceOptionalPart(buffer *bytes.Buffer, partName string, part string) { if len(part) > 0 { buffer.WriteString(partName + "=\"" + part + "\" ") diff --git a/commands/import_jekyll_test.go b/commands/import_jekyll_test.go index c87c224b2..3819d03a5 100644 --- a/commands/import_jekyll_test.go +++ b/commands/import_jekyll_test.go @@ -53,25 +53,41 @@ func TestConvertJekyllMetadata(t *testing.T) { draft bool expect string }{ - {map[interface{}]interface{}{}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z"}`}, - {map[interface{}]interface{}{}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), true, - `{"date":"2015-10-01T00:00:00Z","draft":true}`}, - {map[interface{}]interface{}{"Permalink": "/permalink.html", "layout": "post"}, + { + map[interface{}]interface{}{}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z","url":"/permalink.html"}`}, - {map[interface{}]interface{}{"permalink": "/permalink.html"}, + `{"date":"2015-10-01T00:00:00Z"}`, + }, + { + map[interface{}]interface{}{}, + "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), true, + `{"date":"2015-10-01T00:00:00Z","draft":true}`, + }, + { + map[interface{}]interface{}{"Permalink": "/permalink.html", "layout": "post"}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z","url":"/permalink.html"}`}, - {map[interface{}]interface{}{"category": nil, "permalink": 123}, + `{"date":"2015-10-01T00:00:00Z","url":"/permalink.html"}`, + }, + { + map[interface{}]interface{}{"permalink": "/permalink.html"}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z"}`}, - {map[interface{}]interface{}{"Excerpt_Separator": "sep"}, + `{"date":"2015-10-01T00:00:00Z","url":"/permalink.html"}`, + }, + { + map[interface{}]interface{}{"category": nil, "permalink": 123}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z","excerpt_separator":"sep"}`}, - {map[interface{}]interface{}{"category": "book", "layout": "post", "Others": "Goods", "Date": "2015-10-01 12:13:11"}, + `{"date":"2015-10-01T00:00:00Z"}`, + }, + { + map[interface{}]interface{}{"Excerpt_Separator": "sep"}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"Others":"Goods","categories":["book"],"date":"2015-10-01T12:13:11Z"}`}, + `{"date":"2015-10-01T00:00:00Z","excerpt_separator":"sep"}`, + }, + { + map[interface{}]interface{}{"category": "book", "layout": "post", "Others": "Goods", "Date": "2015-10-01 12:13:11"}, + "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, + `{"Others":"Goods","categories":["book"],"date":"2015-10-01T12:13:11Z"}`, + }, } for _, data := range testDataList { @@ -90,44 +106,68 @@ func TestConvertJekyllContent(t *testing.T) { content string expect string }{ - {map[interface{}]interface{}{}, - "Test content\r\n<!-- more -->\npart2 content", "Test content\n<!--more-->\npart2 content"}, - {map[interface{}]interface{}{}, - "Test content\n<!-- More -->\npart2 content", "Test content\n<!--more-->\npart2 content"}, - {map[interface{}]interface{}{"excerpt_separator": "<!--sep-->"}, + { + map[interface{}]interface{}{}, + "Test content\r\n<!-- more -->\npart2 content", "Test content\n<!--more-->\npart2 content", + }, + { + map[interface{}]interface{}{}, + "Test content\n<!-- More -->\npart2 content", "Test content\n<!--more-->\npart2 content", + }, + { + map[interface{}]interface{}{"excerpt_separator": "<!--sep-->"}, "Test content\n<!--sep-->\npart2 content", - "---\nexcerpt_separator: <!--sep-->\n---\nTest content\n<!--more-->\npart2 content"}, + "---\nexcerpt_separator: <!--sep-->\n---\nTest content\n<!--more-->\npart2 content", + }, {map[interface{}]interface{}{}, "{% raw %}text{% endraw %}", "text"}, {map[interface{}]interface{}{}, "{%raw%} text2 {%endraw %}", "text2"}, - {map[interface{}]interface{}{}, + { + map[interface{}]interface{}{}, "{% highlight go %}\nvar s int\n{% endhighlight %}", - "{{< highlight go >}}\nvar s int\n{{< / highlight >}}"}, - {map[interface{}]interface{}{}, + "{{< highlight go >}}\nvar s int\n{{< / highlight >}}", + }, + { + map[interface{}]interface{}{}, "{% highlight go linenos hl_lines=\"1 2\" %}\nvar s string\nvar i int\n{% endhighlight %}", - "{{< highlight go \"linenos=table,hl_lines=1 2\" >}}\nvar s string\nvar i int\n{{< / highlight >}}"}, + "{{< highlight go \"linenos=table,hl_lines=1 2\" >}}\nvar s string\nvar i int\n{{< / highlight >}}", + }, // Octopress image tag - {map[interface{}]interface{}{}, + { + map[interface{}]interface{}{}, "{% img http://placekitten.com/890/280 %}", - "{{< figure src=\"http://placekitten.com/890/280\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure src=\"http://placekitten.com/890/280\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img left http://placekitten.com/320/250 Place Kitten #2 %}", - "{{< figure class=\"left\" src=\"http://placekitten.com/320/250\" title=\"Place Kitten #2\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure class=\"left\" src=\"http://placekitten.com/320/250\" title=\"Place Kitten #2\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img right http://placekitten.com/300/500 150 250 'Place Kitten #3' %}", - "{{< figure class=\"right\" src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #3\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure class=\"right\" src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #3\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img right http://placekitten.com/300/500 150 250 'Place Kitten #4' 'An image of a very cute kitten' %}", - "{{< figure class=\"right\" src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure class=\"right\" src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img http://placekitten.com/300/500 150 250 'Place Kitten #4' 'An image of a very cute kitten' %}", - "{{< figure src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img right /placekitten/300/500 'Place Kitten #4' 'An image of a very cute kitten' %}", - "{{< figure class=\"right\" src=\"/placekitten/300/500\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}"}, - {map[interface{}]interface{}{"category": "book", "layout": "post", "Date": "2015-10-01 12:13:11"}, + "{{< figure class=\"right\" src=\"/placekitten/300/500\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}", + }, + { + map[interface{}]interface{}{"category": "book", "layout": "post", "Date": "2015-10-01 12:13:11"}, "somecontent", - "---\nDate: \"2015-10-01 12:13:11\"\ncategory: book\nlayout: post\n---\nsomecontent"}, + "---\nDate: \"2015-10-01 12:13:11\"\ncategory: book\nlayout: post\n---\nsomecontent", + }, } for _, data := range testDataList { result, err := convertJekyllContent(data.metadata, data.content) diff --git a/commands/list.go b/commands/list.go index 0b7c18797..3c09cad25 100644 --- a/commands/list.go +++ b/commands/list.go @@ -46,7 +46,6 @@ func (lc *listCmd) buildSites(config map[string]interface{}) (*hugolib.HugoSites } sites, err := hugolib.NewHugoSites(*c.DepsCfg) - if err != nil { return nil, newSystemError("Error creating sites", err) } @@ -77,7 +76,6 @@ List requires a subcommand, e.g. ` + "`hugo list drafts`.", Long: `List all of the drafts in your content directory.`, RunE: func(cmd *cobra.Command, args []string) error { sites, err := cc.buildSites(map[string]interface{}{"buildDrafts": true}) - if err != nil { return newSystemError("Error building sites", err) } @@ -97,7 +95,6 @@ List requires a subcommand, e.g. ` + "`hugo list drafts`.", Long: `List all of the posts in your content directory which will be posted in the future.`, RunE: func(cmd *cobra.Command, args []string) error { sites, err := cc.buildSites(map[string]interface{}{"buildFuture": true}) - if err != nil { return newSystemError("Error building sites", err) } @@ -126,7 +123,6 @@ List requires a subcommand, e.g. ` + "`hugo list drafts`.", Long: `List all of the posts in your content directory which has already expired.`, RunE: func(cmd *cobra.Command, args []string) error { sites, err := cc.buildSites(map[string]interface{}{"buildExpired": true}) - if err != nil { return newSystemError("Error building sites", err) } @@ -159,7 +155,6 @@ List requires a subcommand, e.g. ` + "`hugo list drafts`.", "buildDrafts": true, "buildFuture": true, }) - if err != nil { return newSystemError("Error building sites", err) } diff --git a/commands/mod.go b/commands/mod.go index b390d1e75..c6870e1d2 100644 --- a/commands/mod.go +++ b/commands/mod.go @@ -91,7 +91,6 @@ Also note that if you configure a positive maxAge for the "modules" file cache, } func (b *commandsBuilder) newModCmd() *modCmd { - c := &modCmd{} const commonUsage = ` @@ -264,7 +263,6 @@ If a module is vendored, that is where Hugo will look for it's dependencies. c.baseBuilderCmd = b.newBuilderCmd(cmd) return c - } func (c *modCmd) withModsClient(failOnMissingConfig bool, f func(*modules.Client) error) error { diff --git a/commands/mod_npm.go b/commands/mod_npm.go index a73908e7a..852d98571 100644 --- a/commands/mod_npm.go +++ b/commands/mod_npm.go @@ -20,7 +20,6 @@ import ( ) func newModNPMCmd(c *modCmd) *cobra.Command { - cmd := &cobra.Command{ Use: "npm", Short: "Various npm helpers.", @@ -47,7 +46,6 @@ removed from Hugo, but we need to test this out in "real life" to get a feel of so this may/will change in future versions of Hugo. `, RunE: func(cmd *cobra.Command, args []string) error { - return c.withHugo(func(h *hugolib.HugoSites) error { return npm.Pack(h.BaseFs.SourceFs, h.BaseFs.Assets.Dirs) }) diff --git a/commands/new.go b/commands/new.go index 576976e8e..a2d873717 100644 --- a/commands/new.go +++ b/commands/new.go @@ -72,7 +72,6 @@ func (n *newCmd) newContent(cmd *cobra.Command, args []string) error { } c, err := initializeConfig(true, false, &n.hugoBuilderCommon, n, cfgInit) - if err != nil { return err } diff --git a/commands/new_site.go b/commands/new_site.go index 9fb47096a..6fac2c22c 100644 --- a/commands/new_site.go +++ b/commands/new_site.go @@ -58,7 +58,6 @@ Use ` + "`hugo new [contentPath]`" + ` to create new content.`, cc.baseBuilderCmd = b.newBuilderBasicCmd(cmd) return cc - } func (n *newSiteCmd) doNewSite(fs *hugofs.Fs, basepath string, force bool) error { diff --git a/commands/new_theme.go b/commands/new_theme.go index cb85a1db2..3ffd85c04 100644 --- a/commands/new_theme.go +++ b/commands/new_theme.go @@ -53,7 +53,6 @@ as you see fit.`, // newTheme creates a new Hugo theme template func (n *newThemeCmd) newTheme(cmd *cobra.Command, args []string) error { c, err := initializeConfig(false, false, &n.hugoBuilderCommon, n, nil) - if err != nil { return err } @@ -145,7 +144,6 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } func (n *newThemeCmd) createThemeMD(fs *hugofs.Fs, inpath string) (err error) { - by := []byte(`# theme.toml template for a Hugo theme # See https://github.com/gohugoio/hugoThemes#themetoml for an example diff --git a/commands/nodeploy.go b/commands/nodeploy.go index 146a61f17..363602c51 100644 --- a/commands/nodeploy.go +++ b/commands/nodeploy.go @@ -17,6 +17,7 @@ package commands import ( "errors" + "github.com/spf13/cobra" ) diff --git a/commands/release.go b/commands/release.go index 4de165f35..3b78590e6 100644 --- a/commands/release.go +++ b/commands/release.go @@ -61,7 +61,6 @@ func (c *releaseCommandeer) getCommand() *cobra.Command { } func (c *releaseCommandeer) flagsToConfig(cfg config.Provider) { - } func (r *releaseCommandeer) release() error { diff --git a/commands/server.go b/commands/server.go index ef504f20f..93d825993 100644 --- a/commands/server.go +++ b/commands/server.go @@ -228,7 +228,6 @@ func (sc *serverCmd) server(cmd *cobra.Command, args []string) error { } return err - } if err := memStats(); err != nil { @@ -262,7 +261,6 @@ func (sc *serverCmd) server(cmd *cobra.Command, args []string) error { jww.FEEDBACK.Printf("Watching for changes in %s\n", group) } watcher, err := c.newWatcher(watchDirs...) - if err != nil { return err } @@ -272,7 +270,6 @@ func (sc *serverCmd) server(cmd *cobra.Command, args []string) error { } return c.serve(sc) - } func getRootWatchDirsStr(baseDir string, watchDirs []string) string { @@ -301,7 +298,6 @@ func (f *fileServer) rewriteRequest(r *http.Request, toPath string) *http.Reques r2.Header.Set("X-Rewrite-Original-URI", r.URL.RequestURI()) return r2 - } func (f *fileServer) createEndpoint(i int) (*http.ServeMux, string, string, error) { @@ -393,7 +389,6 @@ func (f *fileServer) createEndpoint(i int) (*http.ServeMux, string, string, erro } else { doRedirect = false } - } } @@ -413,7 +408,6 @@ func (f *fileServer) createEndpoint(i int) (*http.ServeMux, string, string, erro } if f.c.fastRenderMode && f.c.buildErr == nil { - if strings.HasSuffix(requestURI, "/") || strings.HasSuffix(requestURI, "html") || strings.HasSuffix(requestURI, "htm") { if !f.c.visitedURLs.Contains(requestURI) { // If not already on stack, re-render that single page. @@ -453,8 +447,8 @@ var logErrorRe = regexp.MustCompile(`(?s)ERROR \d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{ func removeErrorPrefixFromLog(content string) string { return logErrorRe.ReplaceAllLiteralString(content, "") } -func (c *commandeer) serve(s *serverCmd) error { +func (c *commandeer) serve(s *serverCmd) error { isMultiHost := c.hugo().IsMultihost() var ( @@ -496,7 +490,7 @@ func (c *commandeer) serve(s *serverCmd) error { livereload.Initialize() } - var sigs = make(chan os.Signal, 1) + sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) for i := range baseURLs { diff --git a/commands/server_test.go b/commands/server_test.go index 04e874f94..cc2a6d92c 100644 --- a/commands/server_test.go +++ b/commands/server_test.go @@ -73,7 +73,6 @@ func TestServer(t *testing.T) { // Stop the server. stop <- true - } func TestFixURL(t *testing.T) { @@ -127,7 +126,6 @@ ERROR 2018/10/07 13:11:12 Rebuild failed: logged 1 error(s) withoutError := removeErrorPrefixFromLog(content) c.Assert(strings.Contains(withoutError, "ERROR"), qt.Equals, false) - } func isWindowsCI() bool { diff --git a/commands/static_syncer.go b/commands/static_syncer.go index bd696520a..23bdbe2df 100644 --- a/commands/static_syncer.go +++ b/commands/static_syncer.go @@ -128,5 +128,4 @@ func (s *staticSyncer) syncsStaticEvents(staticEvents []fsnotify.Event) error { _, err := c.doWithPublishDirs(syncFn) return err - } diff --git a/common/collections/append.go b/common/collections/append.go index b56455bc9..d6fb89241 100644 --- a/common/collections/append.go +++ b/common/collections/append.go @@ -51,7 +51,6 @@ func Append(to interface{}, from ...interface{}) (interface{}, error) { } else if !fromt.AssignableTo(tot) { // Fall back to a []interface{} slice. return appendToInterfaceSliceFromValues(tov, fromv) - } } } diff --git a/common/collections/append_test.go b/common/collections/append_test.go index 4086570b8..7d6117de8 100644 --- a/common/collections/append_test.go +++ b/common/collections/append_test.go @@ -36,28 +36,44 @@ func TestAppend(t *testing.T) { {nil, []interface{}{"a", "b"}, []string{"a", "b"}}, {nil, []interface{}{nil}, []interface{}{nil}}, {[]interface{}{}, []interface{}{[]string{"c", "d", "e"}}, []string{"c", "d", "e"}}, - {tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}, + { + tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}, []interface{}{&tstSlicer{"c"}}, - tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}, &tstSlicer{"c"}}}, - {&tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}, + tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}, &tstSlicer{"c"}}, + }, + { + &tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}, []interface{}{&tstSlicer{"c"}}, - tstSlicers{&tstSlicer{"a"}, + tstSlicers{ + &tstSlicer{"a"}, &tstSlicer{"b"}, - &tstSlicer{"c"}}}, - {testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn1{"b"}}, + &tstSlicer{"c"}, + }, + }, + { + testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn1{"b"}}, []interface{}{&tstSlicerIn1{"c"}}, - testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn1{"b"}, &tstSlicerIn1{"c"}}}, + testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn1{"b"}, &tstSlicerIn1{"c"}}, + }, //https://github.com/gohugoio/hugo/issues/5361 - {[]string{"a", "b"}, []interface{}{tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}}, - []interface{}{"a", "b", &tstSlicer{"a"}, &tstSlicer{"b"}}}, - {[]string{"a", "b"}, []interface{}{&tstSlicer{"a"}}, - []interface{}{"a", "b", &tstSlicer{"a"}}}, + { + []string{"a", "b"}, + []interface{}{tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}}, + []interface{}{"a", "b", &tstSlicer{"a"}, &tstSlicer{"b"}}, + }, + { + []string{"a", "b"}, + []interface{}{&tstSlicer{"a"}}, + []interface{}{"a", "b", &tstSlicer{"a"}}, + }, // Errors {"", []interface{}{[]string{"a", "b"}}, false}, // No string concatenation. - {"ab", + { + "ab", []interface{}{"c"}, - false}, + false, + }, } { result, err := Append(test.start, test.addend...) @@ -71,5 +87,4 @@ func TestAppend(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(result, qt.DeepEquals, test.expected) } - } diff --git a/common/collections/slice_test.go b/common/collections/slice_test.go index 3ebfe6d11..93bad84da 100644 --- a/common/collections/slice_test.go +++ b/common/collections/slice_test.go @@ -20,11 +20,13 @@ import ( qt "github.com/frankban/quicktest" ) -var _ Slicer = (*tstSlicer)(nil) -var _ Slicer = (*tstSlicerIn1)(nil) -var _ Slicer = (*tstSlicerIn2)(nil) -var _ testSlicerInterface = (*tstSlicerIn1)(nil) -var _ testSlicerInterface = (*tstSlicerIn1)(nil) +var ( + _ Slicer = (*tstSlicer)(nil) + _ Slicer = (*tstSlicerIn1)(nil) + _ Slicer = (*tstSlicerIn2)(nil) + _ testSlicerInterface = (*tstSlicerIn1)(nil) + _ testSlicerInterface = (*tstSlicerIn1)(nil) +) type testSlicerInterface interface { Name() string @@ -54,7 +56,6 @@ func (p *tstSlicerIn1) Slice(in interface{}) (interface{}, error) { default: return nil, errors.New("invalid type") } - } return result, nil } @@ -120,5 +121,4 @@ func TestSlice(t *testing.T) { c.Assert(test.expected, qt.DeepEquals, result, errMsg) } - } diff --git a/common/herrors/error_locator_test.go b/common/herrors/error_locator_test.go index bc34a2cdf..0cd5fb2d7 100644 --- a/common/herrors/error_locator_test.go +++ b/common/herrors/error_locator_test.go @@ -125,5 +125,4 @@ E`, offsetMatcher) c.Assert(location.Lines, qt.DeepEquals, []string{"A", "B", "C", "D"}) c.Assert(location.Position().LineNumber, qt.Equals, 2) c.Assert(location.LinesPos, qt.Equals, 1) - } diff --git a/common/herrors/file_error.go b/common/herrors/file_error.go index 039c25dc8..1cb31ff9f 100644 --- a/common/herrors/file_error.go +++ b/common/herrors/file_error.go @@ -21,9 +21,7 @@ import ( "github.com/pkg/errors" ) -var ( - _ causer = (*fileError)(nil) -) +var _ causer = (*fileError)(nil) // FileError represents an error when handling a file: Parsing a config file, // execute a template etc. diff --git a/common/herrors/file_error_test.go b/common/herrors/file_error_test.go index b1b5c5a02..4b42f8f39 100644 --- a/common/herrors/file_error_test.go +++ b/common/herrors/file_error_test.go @@ -52,5 +52,4 @@ func TestToLineNumberError(t *testing.T) { c.Assert(pos.ColumnNumber, qt.Equals, test.columnNumber, errMsg) c.Assert(errors.Cause(got), qt.Not(qt.IsNil)) } - } diff --git a/common/hreflect/helpers.go b/common/hreflect/helpers.go index d936da19c..cd5714d2f 100644 --- a/common/hreflect/helpers.go +++ b/common/hreflect/helpers.go @@ -67,7 +67,6 @@ func IsTruthful(in interface{}) bool { default: return IsTruthfulValue(reflect.ValueOf(in)) } - } var zeroType = reflect.TypeOf((*types.Zeroer)(nil)).Elem() diff --git a/common/hugo/hugo_test.go b/common/hugo/hugo_test.go index 8840a9e9e..0862f36e7 100644 --- a/common/hugo/hugo_test.go +++ b/common/hugo/hugo_test.go @@ -35,5 +35,4 @@ func TestHugoInfo(t *testing.T) { devHugoInfo := NewInfo("development") c.Assert(devHugoInfo.IsProduction(), qt.Equals, false) - } diff --git a/common/hugo/version.go b/common/hugo/version.go index 038537fc0..b87dab547 100644 --- a/common/hugo/version.go +++ b/common/hugo/version.go @@ -16,7 +16,6 @@ package hugo import ( "fmt" "io" - "runtime" "strings" @@ -146,7 +145,6 @@ func BuildVersionString() string { } return fmt.Sprintf("%s %s %s BuildDate: %s", program, version, osArch, date) - } func version(version float32, patchVersion int, suffix string) string { diff --git a/common/loggers/ignorableLogger.go b/common/loggers/ignorableLogger.go index 1bd4d99b8..766aae07c 100644 --- a/common/loggers/ignorableLogger.go +++ b/common/loggers/ignorableLogger.go @@ -34,7 +34,6 @@ func NewIgnorableLogger(logger Logger, statements ...string) IgnorableLogger { statementsSet := make(map[string]bool) for _, s := range statements { statementsSet[strings.ToLower(s)] = true - } return ignorableLogger{ Logger: logger, diff --git a/common/loggers/loggers.go b/common/loggers/loggers.go index 5c04b9eab..c9b5d21be 100644 --- a/common/loggers/loggers.go +++ b/common/loggers/loggers.go @@ -29,10 +29,8 @@ import ( jww "github.com/spf13/jwalterweatherman" ) -var ( - // Counts ERROR logs to the global jww logger. - GlobalErrorCounter *jww.Counter -) +// Counts ERROR logs to the global jww logger. +var GlobalErrorCounter *jww.Counter func init() { GlobalErrorCounter = &jww.Counter{} @@ -253,7 +251,6 @@ func (a labelColorizer) Write(p []byte) (n int, err error) { // bytes, so we lie a little. _, err = a.w.Write([]byte(replaced)) return len(p), err - } // InitGlobalLogger initializes the global logger, used in some rare cases. @@ -264,7 +261,6 @@ func InitGlobalLogger(stdoutThreshold, logThreshold jww.Threshold, outHandle, lo jww.SetLogOutput(logHandle) jww.SetLogThreshold(logThreshold) jww.SetStdoutThreshold(stdoutThreshold) - } func getLogWriters(outHandle, logHandle io.Writer) (io.Writer, io.Writer) { @@ -279,7 +275,6 @@ func getLogWriters(outHandle, logHandle io.Writer) (io.Writer, io.Writer) { } return outHandle, logHandle - } type fatalLogWriter int diff --git a/common/loggers/loggers_test.go b/common/loggers/loggers_test.go index 7af3ca9da..0c0cc859b 100644 --- a/common/loggers/loggers_test.go +++ b/common/loggers/loggers_test.go @@ -31,7 +31,6 @@ func TestLogger(t *testing.T) { l.Warnln("A warning") c.Assert(l.LogCounters().ErrorCounter.Count(), qt.Equals, uint64(2)) - } func TestLoggerToWriterWithPrefix(t *testing.T) { diff --git a/common/maps/maps_test.go b/common/maps/maps_test.go index bde77071d..7e527aac5 100644 --- a/common/maps/maps_test.go +++ b/common/maps/maps_test.go @@ -154,5 +154,4 @@ func TestRenameKeys(t *testing.T) { if !reflect.DeepEqual(expected, m) { t.Errorf("Expected\n%#v, got\n%#v\n", expected, m) } - } diff --git a/common/maps/params.go b/common/maps/params.go index 5e973051b..4c881093c 100644 --- a/common/maps/params.go +++ b/common/maps/params.go @@ -80,7 +80,6 @@ func GetNestedParam(keyStr, separator string, candidates ...Params) (interface{} } return nil, nil - } func GetNestedParamFn(keyStr, separator string, lookupFn func(key string) interface{}) (interface{}, string, map[string]interface{}, error) { diff --git a/common/maps/params_test.go b/common/maps/params_test.go index 46d672d87..df8cbf8d6 100644 --- a/common/maps/params_test.go +++ b/common/maps/params_test.go @@ -20,7 +20,6 @@ import ( ) func TestGetNestedParam(t *testing.T) { - m := map[string]interface{}{ "string": "value", "first": 1, @@ -48,12 +47,10 @@ func TestGetNestedParam(t *testing.T) { c.Assert(must("nested.nestednested.color", ".", m), qt.Equals, "green") c.Assert(must("string.name", ".", m), qt.IsNil) c.Assert(must("nested.foo", ".", m), qt.IsNil) - } // https://github.com/gohugoio/hugo/issues/7903 func TestGetNestedParamFnNestedNewKey(t *testing.T) { - c := qt.New(t) nested := map[string]interface{}{ @@ -71,5 +68,4 @@ func TestGetNestedParamFnNestedNewKey(t *testing.T) { c.Assert(existing, qt.IsNil) c.Assert(nestedKey, qt.Equals, "new") c.Assert(owner, qt.DeepEquals, nested) - } diff --git a/common/maps/scratch.go b/common/maps/scratch.go index 7a3cd3748..ccd03ef32 100644 --- a/common/maps/scratch.go +++ b/common/maps/scratch.go @@ -51,7 +51,6 @@ func NewScratcher() Scratcher { // // If the first add for a key is an array or slice, then the next value(s) will be appended. func (c *Scratch) Add(key string, newAddend interface{}) (string, error) { - var newVal interface{} c.mu.RLock() existingAddend, found := c.values[key] diff --git a/common/maps/scratch_test.go b/common/maps/scratch_test.go index 40df3bb6b..d893ccb03 100644 --- a/common/maps/scratch_test.go +++ b/common/maps/scratch_test.go @@ -53,7 +53,6 @@ func TestScratchAdd(t *testing.T) { if err == nil { t.Errorf("Expected error from invalid arithmetic") } - } func TestScratchAddSlice(t *testing.T) { @@ -96,7 +95,6 @@ func TestScratchAddTypedSliceToInterfaceSlice(t *testing.T) { _, err := scratch.Add("slice", []int{1, 2}) c.Assert(err, qt.IsNil) c.Assert(scratch.Get("slice"), qt.DeepEquals, []int{1, 2}) - } // https://github.com/gohugoio/hugo/issues/5361 @@ -110,7 +108,6 @@ func TestScratchAddDifferentTypedSliceToInterfaceSlice(t *testing.T) { _, err := scratch.Add("slice", []int{1, 2}) c.Assert(err, qt.IsNil) c.Assert(scratch.Get("slice"), qt.DeepEquals, []interface{}{"foo", 1, 2}) - } func TestScratchSet(t *testing.T) { diff --git a/common/para/para_test.go b/common/para/para_test.go index 9b268b0c0..e89f9360b 100644 --- a/common/para/para_test.go +++ b/common/para/para_test.go @@ -16,7 +16,6 @@ package para import ( "context" "runtime" - "sort" "sync" "sync/atomic" @@ -60,7 +59,6 @@ func TestPara(t *testing.T) { c.Assert(sort.IntsAreSorted(result), qt.Equals, false, qt.Commentf("Para does not seem to be parallel")) sort.Ints(result) c.Assert(result, qt.DeepEquals, ints) - }) c.Run("Time", func(c *qt.C) { @@ -84,7 +82,5 @@ func TestPara(t *testing.T) { c.Assert(r.Wait(), qt.IsNil) c.Assert(counter, qt.Equals, int64(n)) c.Assert(time.Since(start) < n/2*time.Millisecond, qt.Equals, true) - }) - } diff --git a/common/text/position.go b/common/text/position.go index 0c43c5ae7..5dd64526a 100644 --- a/common/text/position.go +++ b/common/text/position.go @@ -50,12 +50,11 @@ func (pos Position) IsValid() bool { var positionStringFormatfunc func(p Position) string func createPositionStringFormatter(formatStr string) func(p Position) string { - if formatStr == "" { formatStr = "\":file::line::col\"" } - var identifiers = []string{":file", ":line", ":col"} + identifiers := []string{":file", ":line", ":col"} var identifiersFound []string for i := range formatStr { diff --git a/common/text/position_test.go b/common/text/position_test.go index ba4824344..a1f43c5d4 100644 --- a/common/text/position_test.go +++ b/common/text/position_test.go @@ -29,5 +29,4 @@ func TestPositionStringFormatter(t *testing.T) { c.Assert(createPositionStringFormatter("好::col")(pos), qt.Equals, "好:13") c.Assert(createPositionStringFormatter("")(pos), qt.Equals, "\"/my/file.txt:12:13\"") c.Assert(pos.String(), qt.Equals, "\"/my/file.txt:12:13\"") - } diff --git a/common/text/transform_test.go b/common/text/transform_test.go index 70b10d149..08265f976 100644 --- a/common/text/transform_test.go +++ b/common/text/transform_test.go @@ -25,5 +25,4 @@ func TestRemoveAccents(t *testing.T) { c.Assert(string(RemoveAccents([]byte("Resumé"))), qt.Equals, "Resume") c.Assert(string(RemoveAccents([]byte("Hugo Rocks!"))), qt.Equals, "Hugo Rocks!") c.Assert(string(RemoveAccentsString("Resumé")), qt.Equals, "Resume") - } diff --git a/common/types/convert_test.go b/common/types/convert_test.go index 8a4f04db2..d053ede60 100644 --- a/common/types/convert_test.go +++ b/common/types/convert_test.go @@ -26,7 +26,6 @@ func TestToStringSlicePreserveString(t *testing.T) { c.Assert(ToStringSlicePreserveString("Hugo"), qt.DeepEquals, []string{"Hugo"}) c.Assert(ToStringSlicePreserveString([]interface{}{"A", "B"}), qt.DeepEquals, []string{"A", "B"}) c.Assert(ToStringSlicePreserveString(nil), qt.IsNil) - } func TestToString(t *testing.T) { @@ -34,5 +33,4 @@ func TestToString(t *testing.T) { c.Assert(ToString([]byte("Hugo")), qt.Equals, "Hugo") c.Assert(ToString(json.RawMessage("Hugo")), qt.Equals, "Hugo") - } diff --git a/compare/compare_strings_test.go b/compare/compare_strings_test.go index db286c2c5..9c4aa5868 100644 --- a/compare/compare_strings_test.go +++ b/compare/compare_strings_test.go @@ -61,5 +61,4 @@ func TestLexicographicSort(t *testing.T) { }) c.Assert(s, qt.DeepEquals, []string{"A", "b", "Ba", "ba", "ba", "Bz"}) - } diff --git a/config/commonConfig.go b/config/commonConfig.go index 9b4edfd90..260ebe73e 100644 --- a/config/commonConfig.go +++ b/config/commonConfig.go @@ -14,12 +14,12 @@ package config import ( - "github.com/pkg/errors" - "sort" "strings" "sync" + "github.com/pkg/errors" + "github.com/gohugoio/hugo/common/types" "github.com/gobwas/glob" @@ -88,7 +88,6 @@ type Sitemap struct { } func DecodeSitemap(prototype Sitemap, input map[string]interface{}) Sitemap { - for key, value := range input { switch key { case "changefreq": @@ -116,7 +115,6 @@ type Server struct { } func (s *Server) init() { - s.compiledInit.Do(func() { for _, h := range s.Headers { s.compiledHeaders = append(s.compiledHeaders, glob.MustCompile(h.For)) @@ -150,7 +148,6 @@ func (s *Server) MatchHeaders(pattern string) []types.KeyValueStr { }) return matches - } func (s *Server) MatchRedirect(pattern string) Redirect { @@ -176,7 +173,6 @@ func (s *Server) MatchRedirect(pattern string) Redirect { } return Redirect{} - } type Headers struct { diff --git a/config/commonConfig_test.go b/config/commonConfig_test.go index b8b6e6795..d4273277a 100644 --- a/config/commonConfig_test.go +++ b/config/commonConfig_test.go @@ -57,7 +57,6 @@ func TestBuild(t *testing.T) { c.Assert(b.UseResourceCache(herrors.ErrFeatureNotAvailable), qt.Equals, false) c.Assert(b.UseResourceCache(errors.New("err")), qt.Equals, false) c.Assert(b.UseResourceCache(nil), qt.Equals, false) - } func TestServer(t *testing.T) { @@ -98,7 +97,8 @@ status = 301 c.Assert(s.MatchHeaders("/foo.jpg"), qt.DeepEquals, []types.KeyValueStr{ {Key: "X-Content-Type-Options", Value: "nosniff"}, {Key: "X-Frame-Options", Value: "DENY"}, - {Key: "X-XSS-Protection", Value: "1; mode=block"}}) + {Key: "X-XSS-Protection", Value: "1; mode=block"}, + }) c.Assert(s.MatchRedirect("/foo/bar/baz"), qt.DeepEquals, Redirect{ From: "/foo/**", @@ -122,7 +122,8 @@ status = 301 c.Assert(s.MatchRedirect("/default/index.html"), qt.DeepEquals, Redirect{}) c.Assert(s.MatchRedirect("/default/"), qt.DeepEquals, Redirect{}) - for _, errorCase := range []string{`[[server.redirects]] + for _, errorCase := range []string{ + `[[server.redirects]] from = "/**" to = "/file" status = 301`, @@ -138,5 +139,4 @@ status = 301`, c.Assert(err, qt.Not(qt.IsNil)) } - } diff --git a/config/configLoader.go b/config/configLoader.go index 2e37a5b35..6d94f0b79 100644 --- a/config/configLoader.go +++ b/config/configLoader.go @@ -86,7 +86,6 @@ func readConfig(format metadecoders.Format, data []byte) (map[string]interface{} RenameKeys(m) return m, nil - } func loadConfigFromFile(fs afero.Fs, filename string) (map[string]interface{}, error) { diff --git a/config/privacy/privacyConfig_test.go b/config/privacy/privacyConfig_test.go index a750ba282..0fb599c0a 100644 --- a/config/privacy/privacyConfig_test.go +++ b/config/privacy/privacyConfig_test.go @@ -69,7 +69,6 @@ simple = true } c.Assert(got, qt.All(qt.Equals), true) - } func TestDecodeConfigFromTOMLCaseInsensitive(t *testing.T) { diff --git a/config/services/servicesConfig_test.go b/config/services/servicesConfig_test.go index ed3038159..6e979b999 100644 --- a/config/services/servicesConfig_test.go +++ b/config/services/servicesConfig_test.go @@ -65,5 +65,4 @@ func TestUseSettingsFromRootIfSet(t *testing.T) { c.Assert(config.Disqus.Shortname, qt.Equals, "root_short") c.Assert(config.GoogleAnalytics.ID, qt.Equals, "ga_root") - } diff --git a/create/content.go b/create/content.go index 13e668201..d1594a199 100644 --- a/create/content.go +++ b/create/content.go @@ -16,15 +16,14 @@ package create import ( "bytes" - - "github.com/pkg/errors" - "io" "os" "os/exec" "path/filepath" "strings" + "github.com/pkg/errors" + "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugofs" @@ -131,7 +130,6 @@ func newContentFromDir( sites *hugolib.HugoSites, targetFs afero.Fs, cm archetypeMap, name, targetPath string) error { - for _, f := range cm.otherFiles { meta := f.Meta() filename := meta.Path() @@ -196,11 +194,9 @@ func mapArcheTypeDir( ps *helpers.PathSpec, fs afero.Fs, archetypeDir string) (archetypeMap, error) { - var m archetypeMap walkFn := func(path string, fi hugofs.FileMetaInfo, err error) error { - if err != nil { return err } @@ -308,7 +304,6 @@ func resolveContentPath(sites *hugolib.HugoSites, fs afero.Fs, targetPath string } if siteContentDir == "" { - } if siteContentDir != "" { @@ -324,7 +319,6 @@ func resolveContentPath(sites *hugolib.HugoSites, fs afero.Fs, targetPath string } return s.PathSpec.AbsPathify(filepath.Join(contentDir, targetPath)), s } - } // FindArchetype takes a given kind/archetype of content and returns the path diff --git a/create/content_template_handler.go b/create/content_template_handler.go index 3a7007f1a..3e9701e4b 100644 --- a/create/content_template_handler.go +++ b/create/content_template_handler.go @@ -83,7 +83,6 @@ var ( ) func executeArcheTypeAsTemplate(s *hugolib.Site, name, kind, targetPath, archetypeFilename string) ([]byte, error) { - var ( archetypeContent []byte archetypeTemplate []byte @@ -145,5 +144,4 @@ func executeArcheTypeAsTemplate(s *hugolib.Site, name, kind, targetPath, archety archetypeContent = []byte(archetypeShortcodeReplacementsPost.Replace(buff.String())) return archetypeContent, nil - } diff --git a/create/content_test.go b/create/content_test.go index f43d3a5f4..37dbf98bd 100644 --- a/create/content_test.go +++ b/create/content_test.go @@ -14,6 +14,7 @@ package create_test import ( + "fmt" "os" "path/filepath" "strings" @@ -23,8 +24,6 @@ import ( "github.com/gohugoio/hugo/hugolib" - "fmt" - "github.com/gohugoio/hugo/hugofs" qt "github.com/frankban/quicktest" @@ -35,7 +34,6 @@ import ( ) func TestNewContent(t *testing.T) { - cases := []struct { kind string path string @@ -59,7 +57,8 @@ func TestNewContent(t *testing.T) { `title = "GO"`, "{{< myshortcode >}}", "{{% myshortcode %}}", - "{{</* comment */>}}\n{{%/* comment */%}}"}}, // shortcodes + "{{</* comment */>}}\n{{%/* comment */%}}", + }}, // shortcodes } for i, cas := range cases { @@ -140,7 +139,6 @@ i18n: {{ T "hugo" }} c.Assert(create.NewContent(h, "my-theme-bundle", "post/my-theme-post"), qt.IsNil) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-theme-post/index.md")), `File: index.md`, `Site Lang: en`, `Name: My Theme Post`, `i18n: Hugo Rocks!`) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-theme-post/resources/hugo1.json")), `hugo1: {{ printf "no template handling in here" }}`) - } func initFs(fs afero.Fs) error { @@ -248,7 +246,6 @@ func readFileFromFs(t *testing.T, fs afero.Fs, filename string) string { } func newTestCfg(c *qt.C, mm afero.Fs) (*viper.Viper, *hugofs.Fs) { - cfg := ` theme = "mytheme" @@ -281,5 +278,4 @@ other = "Hugo Rokkar!"`), 0755), qt.IsNil) c.Assert(err, qt.IsNil) return v, hugofs.NewFrom(mm, v) - } diff --git a/deploy/deploy.go b/deploy/deploy.go index 0c793bca0..1aaae5aa7 100644 --- a/deploy/deploy.go +++ b/deploy/deploy.go @@ -466,7 +466,7 @@ func (lf *localFile) MD5() []byte { // knownHiddenDirectory checks if the specified name is a well known // hidden directory. func knownHiddenDirectory(name string) bool { - var knownDirectories = []string{ + knownDirectories := []string{ ".well-known", } @@ -697,7 +697,6 @@ func findDiffs(localFiles map[string]*localFile, remoteFiles map[string]*blob.Li // // 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 }) diff --git a/deploy/deployConfig.go b/deploy/deployConfig.go index d4f78011e..443c5901a 100644 --- a/deploy/deployConfig.go +++ b/deploy/deployConfig.go @@ -112,7 +112,6 @@ func (m *matcher) Matches(path string) bool { // decode creates a config from a given Hugo configuration. func decodeConfig(cfg config.Provider) (deployConfig, error) { - var ( mediaTypesConfig []map[string]interface{} dcfg deployConfig diff --git a/deploy/deploy_test.go b/deploy/deploy_test.go index 987c472ca..264ca9f9e 100644 --- a/deploy/deploy_test.go +++ b/deploy/deploy_test.go @@ -211,7 +211,6 @@ func TestFindDiffs(t *testing.T) { } func TestWalkLocal(t *testing.T) { - tests := map[string]struct { Given []string Expect []string @@ -355,7 +354,10 @@ func TestLocalFile(t *testing.T) { MediaTypesConfig: []map[string]interface{}{ { "hugo/custom": map[string]interface{}{ - "suffixes": []string{"hugo"}}}}, + "suffixes": []string{"hugo"}, + }, + }, + }, WantContent: contentBytes, WantSize: contentLen, WantMD5: contentMD5[:], diff --git a/deps/deps.go b/deps/deps.go index f6b64c279..c2919c9c5 100644 --- a/deps/deps.go +++ b/deps/deps.go @@ -231,7 +231,6 @@ func New(cfg DepsCfg) (*Deps, error) { } ps, err := helpers.NewPathSpec(fs, cfg.Language, logger) - if err != nil { return nil, errors.Wrap(err, "create PathSpec") } @@ -347,7 +346,6 @@ func (d Deps) ForLanguage(cfg DepsCfg, onCreated func(d *Deps) error) (*Deps, er d.BuildStartListeners = &Listeners{} return &d, nil - } // DepsCfg contains configuration options that can be used to configure Hugo diff --git a/deps/deps_test.go b/deps/deps_test.go index 5c58ed7a3..d68276732 100644 --- a/deps/deps_test.go +++ b/deps/deps_test.go @@ -20,7 +20,6 @@ import ( ) func TestBuildFlags(t *testing.T) { - c := qt.New(t) var bf BuildState bf.Incr() @@ -28,5 +27,4 @@ func TestBuildFlags(t *testing.T) { bf.Incr() c.Assert(bf.Incr(), qt.Equals, 4) - } diff --git a/helpers/content.go b/helpers/content.go index c59e41a8c..5e56ad6bf 100644 --- a/helpers/content.go +++ b/helpers/content.go @@ -20,6 +20,7 @@ package helpers import ( "bytes" "html/template" + "strings" "unicode" "unicode/utf8" @@ -33,8 +34,6 @@ import ( bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/config" - - "strings" ) // SummaryDivider denotes where content summarization should end. The default is "<!--more-->". @@ -66,7 +65,6 @@ type ContentSpec struct { // NewContentSpec returns a ContentSpec initialized // with the appropriate fields from the given config.Provider. func NewContentSpec(cfg config.Provider, logger loggers.Logger, contentFs afero.Fs) (*ContentSpec, error) { - spec := &ContentSpec{ summaryLength: cfg.GetInt("summaryLength"), BuildFuture: cfg.GetBool("buildFuture"), @@ -81,7 +79,6 @@ func NewContentSpec(cfg config.Provider, logger loggers.Logger, contentFs afero. ContentFs: contentFs, Logger: logger, }) - if err != nil { return nil, err } @@ -112,7 +109,6 @@ var stripHTMLReplacer = strings.NewReplacer("\n", " ", "</p>", "\n", "<br>", "\n // StripHTML accepts a string, strips out all HTML tags and returns it. func StripHTML(s string) string { - // Shortcut strings with no tags in them if !strings.ContainsAny(s, "<>") { return s diff --git a/helpers/content_test.go b/helpers/content_test.go index 86e5412c2..573c1c90d 100644 --- a/helpers/content_test.go +++ b/helpers/content_test.go @@ -118,7 +118,6 @@ func TestNewContentSpec(t *testing.T) { c.Assert(spec.BuildFuture, qt.Equals, true) c.Assert(spec.BuildExpired, qt.Equals, true) c.Assert(spec.BuildDrafts, qt.Equals, true) - } var benchmarkTruncateString = strings.Repeat("This is a sentence about nothing.", 20) @@ -225,7 +224,7 @@ func TestExtractTOCGreaterThanSeventy(t *testing.T) { content := []byte("<nav>\n<ul>\nTOC This is a very long content which will definitely be greater than seventy, I promise you that.<li><a href=\"#") actualTocLessContent, actualToc := ExtractTOC(content) - //Because the start of Toc is greater than 70+startpoint of <li> content and empty TOC will be returned + // Because the start of Toc is greater than 70+startpoint of <li> content and empty TOC will be returned expectedToc := []byte("") if !bytes.Equal(actualTocLessContent, content) { @@ -255,7 +254,6 @@ func TestExtractNoTOC(t *testing.T) { var totalWordsBenchmarkString = strings.Repeat("Hugo Rocks ", 200) func TestTotalWords(t *testing.T) { - for i, this := range []struct { s string words int diff --git a/helpers/docshelper.go b/helpers/docshelper.go index 1397acc59..dbf5292d4 100644 --- a/helpers/docshelper.go +++ b/helpers/docshelper.go @@ -11,9 +11,7 @@ import ( // This is is just some helpers used to create some JSON used in the Hugo docs. func init() { - docsProvider := func() docshelper.DocProvider { - var chromaLexers []interface{} sort.Sort(lexers.Registry.Lexers) @@ -50,7 +48,6 @@ func init() { } return docshelper.DocProvider{"chroma": map[string]interface{}{"lexers": chromaLexers}} - } docshelper.AddDocProviderFunc(docsProvider) diff --git a/helpers/emoji.go b/helpers/emoji.go index a6786c005..cda0e1616 100644 --- a/helpers/emoji.go +++ b/helpers/emoji.go @@ -93,5 +93,4 @@ func initEmoji() { emojiMaxSize = len(k) } } - } diff --git a/helpers/emoji_test.go b/helpers/emoji_test.go index 89f9df5fa..e9d634ccc 100644 --- a/helpers/emoji_test.go +++ b/helpers/emoji_test.go @@ -74,7 +74,6 @@ func TestEmojiCustom(t *testing.T) { // Hugo have a byte slice, wants a byte slice and doesn't mind if the original is modified. func BenchmarkEmojiKyokomiFprint(b *testing.B) { - f := func(in []byte) []byte { buff := bufferpool.GetBuffer() defer bufferpool.PutBuffer(buff) @@ -89,7 +88,6 @@ func BenchmarkEmojiKyokomiFprint(b *testing.B) { } func BenchmarkEmojiKyokomiSprint(b *testing.B) { - f := func(in []byte) []byte { return []byte(emoji.Sprint(string(in))) } @@ -102,7 +100,6 @@ func BenchmarkHugoEmoji(b *testing.B) { } func doBenchmarkEmoji(b *testing.B, f func(in []byte) []byte) { - type input struct { in []byte expect []byte @@ -119,8 +116,8 @@ func doBenchmarkEmoji(b *testing.B, f func(in []byte) []byte) { {"No smiles for you or " + strings.Repeat("you ", 1000), "No smiles for you or " + strings.Repeat("you ", 1000)}, } - var in = make([]input, b.N*len(data)) - var cnt = 0 + in := make([]input, b.N*len(data)) + cnt := 0 for i := 0; i < b.N; i++ { for _, this := range data { in[cnt] = input{[]byte(this.input), []byte(this.expect)} @@ -142,6 +139,5 @@ func doBenchmarkEmoji(b *testing.B, f func(in []byte) []byte) { b.Fatalf("[%d] emoji std, got \n%q but expected \n%q", j, result, currIn.expect) } } - } } diff --git a/helpers/general.go b/helpers/general.go index 80e303087..9589514e0 100644 --- a/helpers/general.go +++ b/helpers/general.go @@ -157,7 +157,6 @@ func ReaderToString(lines io.Reader) string { // ReaderContains reports whether subslice is within r. func ReaderContains(r io.Reader, subslice []byte) bool { - if r == nil || len(subslice) == 0 { return false } @@ -345,7 +344,6 @@ func InitLoggers() { func Deprecated(item, alternative string, err bool) { if err { DistinctErrorLog.Printf("%s is deprecated and will be removed in Hugo %s. %s", item, hugo.CurrentVersion.Next().ReleaseVersion(), alternative) - } else { DistinctWarnLog.Printf("%s is deprecated and will be removed in a future release. %s", item, alternative) } diff --git a/helpers/general_test.go b/helpers/general_test.go index 60248b671..518188c17 100644 --- a/helpers/general_test.go +++ b/helpers/general_test.go @@ -219,7 +219,6 @@ func TestGetTitleFunc(t *testing.T) { c.Assert(GetTitleFunc("ap")(title), qt.Equals, "Somewhere Over the Rainbow") c.Assert(GetTitleFunc("")(title), qt.Equals, "Somewhere Over the Rainbow") c.Assert(GetTitleFunc("unknown")(title), qt.Equals, "Somewhere Over the Rainbow") - } func BenchmarkReaderContains(b *testing.B) { @@ -354,7 +353,6 @@ func BenchmarkMD5FromFileFast(b *testing.B) { } }) } - } func BenchmarkUniqueStrings(b *testing.B) { @@ -406,7 +404,6 @@ func BenchmarkUniqueStrings(b *testing.B) { } } }) - } func TestHashString(t *testing.T) { diff --git a/helpers/path.go b/helpers/path.go index 01c452607..abc73d081 100644 --- a/helpers/path.go +++ b/helpers/path.go @@ -36,10 +36,8 @@ import ( "github.com/spf13/afero" ) -var ( - // ErrThemeUndefined is returned when a theme has not be defined by the user. - ErrThemeUndefined = errors.New("no theme set") -) +// ErrThemeUndefined is returned when a theme has not be defined by the user. +var ErrThemeUndefined = errors.New("no theme set") // filepathPathBridge is a bridge for common functionality in filepath vs path type filepathPathBridge interface { @@ -169,7 +167,6 @@ func ReplaceExtension(path string, newExt string) string { } func makePathRelative(inPath string, possibleDirectories ...string) (string, error) { - for _, currentPath := range possibleDirectories { if strings.HasPrefix(inPath, currentPath) { return strings.TrimPrefix(inPath, currentPath), nil @@ -281,7 +278,6 @@ func fileAndExt(in string, b filepathPathBridge) (name string, ext string) { } func extractFilename(in, ext, base, pathSeparator string) (name string) { - // No file name cases. These are defined as: // 1. any "in" path that ends in a pathSeparator // 2. any "base" consisting of just an pathSeparator @@ -299,7 +295,6 @@ func extractFilename(in, ext, base, pathSeparator string) (name string) { name = base } return - } // GetRelativePath returns the relative path of a given path. @@ -474,21 +469,18 @@ func ExtractRootPaths(paths []string) []string { r[i] = root } return r - } // FindCWD returns the current working directory from where the Hugo // executable is run. func FindCWD() (string, error) { serverFile, err := filepath.Abs(os.Args[0]) - if err != nil { return "", fmt.Errorf("can't get absolute path for executable: %v", err) } path := filepath.Dir(serverFile) realFile, err := filepath.EvalSymlinks(serverFile) - if err != nil { if _, err = os.Stat(serverFile + ".exe"); err == nil { realFile = filepath.Clean(serverFile + ".exe") @@ -516,7 +508,6 @@ func SymbolicWalk(fs afero.Fs, root string, walker hugofs.WalkFunc) error { }) return w.Walk() - } // LstatIfPossible can be used to call Lstat if possible, else Stat. @@ -555,7 +546,6 @@ func OpenFilesForWriting(fs afero.Fs, filenames ...string) (io.WriteCloser, erro } return hugio.NewMultiWriteCloser(writeClosers...), nil - } // OpenFileForWriting opens or creates the given file. If the target directory @@ -598,7 +588,6 @@ func GetCacheDir(fs afero.Fs, cfg config.Provider) (string, error) { // Fall back to a cache in /tmp. return GetTempDir("hugo_cache", fs), nil - } func getCacheDir(cfg config.Provider) string { @@ -614,7 +603,6 @@ func getCacheDir(cfg config.Provider) string { // is this project: // https://github.com/philhawksworth/content-shards/blob/master/gulpfile.js return "/opt/build/cache/hugo_cache/" - } // This will fall back to an hugo_cache folder in the tmp dir, which should work fine for most CI diff --git a/helpers/path_test.go b/helpers/path_test.go index 50c23dccc..e1ac90b2f 100644 --- a/helpers/path_test.go +++ b/helpers/path_test.go @@ -184,7 +184,6 @@ func TestGetDottedRelativePath(t *testing.T) { for _, f := range []func(string) string{filepath.FromSlash, func(s string) string { return s }} { doTestGetDottedRelativePath(f, t) } - } func doTestGetDottedRelativePath(urlFixer func(string) string, t *testing.T) { @@ -422,7 +421,6 @@ func createTempDirWithZeroLengthFiles() (string, error) { } // the dir now has one, zero length file in it return d, nil - } func createTempDirWithNonZeroLengthFiles() (string, error) { @@ -451,7 +449,6 @@ func createTempDirWithNonZeroLengthFiles() (string, error) { // the dir now has one, zero length file in it return d, nil - } func deleteTempDir(d string) { @@ -490,7 +487,6 @@ func TestExists(t *testing.T) { t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err) } } - } func TestAbsPathify(t *testing.T) { @@ -544,7 +540,6 @@ func TestAbsPathify(t *testing.T) { } } } - } func TestExtNoDelimiter(t *testing.T) { @@ -611,15 +606,12 @@ func TestFileAndExt(t *testing.T) { t.Errorf("Test %d failed. Expected extension %q got %q.", i, d.expectedExt, ext) } } - } func TestPathPrep(t *testing.T) { - } func TestPrettifyPath(t *testing.T) { - } func TestExtractAndGroupRootPaths(t *testing.T) { @@ -642,16 +634,19 @@ func TestExtractAndGroupRootPaths(t *testing.T) { // Make sure the original is preserved c.Assert(in, qt.DeepEquals, inCopy) - } func TestExtractRootPaths(t *testing.T) { tests := []struct { input []string expected []string - }{{[]string{filepath.FromSlash("a/b"), filepath.FromSlash("a/b/c/"), "b", - filepath.FromSlash("/c/d"), filepath.FromSlash("d/"), filepath.FromSlash("//e//")}, - []string{"a", "a", "b", "c", "d", "e"}}} + }{{ + []string{ + filepath.FromSlash("a/b"), filepath.FromSlash("a/b/c/"), "b", + filepath.FromSlash("/c/d"), filepath.FromSlash("d/"), filepath.FromSlash("//e//"), + }, + []string{"a", "a", "b", "c", "d", "e"}, + }} for _, test := range tests { output := ExtractRootPaths(test.input) @@ -667,7 +662,7 @@ func TestFindCWD(t *testing.T) { expectedErr error } - //cwd, _ := os.Getwd() + // cwd, _ := os.Getwd() data := []test{ //{cwd, nil}, // Commenting this out. It doesn't work properly. diff --git a/helpers/pathspec.go b/helpers/pathspec.go index 557261f1c..5400249eb 100644 --- a/helpers/pathspec.go +++ b/helpers/pathspec.go @@ -45,7 +45,6 @@ func NewPathSpec(fs *hugofs.Fs, cfg config.Provider, logger loggers.Logger) (*Pa // NewPathSpecWithBaseBaseFsProvided creats a new PathSpec from the given filesystems and language. // If an existing BaseFs is provided, parts of that is reused. func NewPathSpecWithBaseBaseFsProvided(fs *hugofs.Fs, cfg config.Provider, logger loggers.Logger, baseBaseFs *filesystems.BaseFs) (*PathSpec, error) { - p, err := paths.New(fs, cfg) if err != nil { return nil, err @@ -85,5 +84,4 @@ func (p *PathSpec) PermalinkForBaseURL(link, baseURL string) string { baseURL += "/" } return baseURL + link - } diff --git a/helpers/pathspec_test.go b/helpers/pathspec_test.go index 8937b0af5..c11299516 100644 --- a/helpers/pathspec_test.go +++ b/helpers/pathspec_test.go @@ -56,5 +56,4 @@ func TestNewPathSpecFromConfig(t *testing.T) { c.Assert(p.BaseURL.String(), qt.Equals, "http://base.com") c.Assert(p.ThemesDir, qt.Equals, "thethemes") c.Assert(p.WorkingDir, qt.Equals, "thework") - } diff --git a/helpers/processing_stats.go b/helpers/processing_stats.go index 4382d5fa5..3e3e9a3ca 100644 --- a/helpers/processing_stats.go +++ b/helpers/processing_stats.go @@ -83,7 +83,6 @@ func (s *ProcessingStats) Table(w io.Writer) { table.SetHeader([]string{"", s.Name}) table.SetBorder(false) table.Render() - } // ProcessingStatsTable writes a table-formatted representation of stats to w. @@ -108,7 +107,6 @@ func ProcessingStatsTable(w io.Writer, stats ...*ProcessingStats) { } else { data[j] = append(data[j], strconv.Itoa(int(tv.val))) } - } } @@ -119,5 +117,4 @@ func ProcessingStatsTable(w io.Writer, stats ...*ProcessingStats) { table.SetHeader(names) table.SetBorder(false) table.Render() - } diff --git a/helpers/testhelpers_test.go b/helpers/testhelpers_test.go index bf249059d..4a6ebd0b1 100644 --- a/helpers/testhelpers_test.go +++ b/helpers/testhelpers_test.go @@ -32,7 +32,6 @@ func newTestCfgFor(fs *hugofs.Fs) *viper.Viper { v.SetFs(fs.Source) return v - } func newTestCfg() *viper.Viper { diff --git a/helpers/url.go b/helpers/url.go index 1e88def9e..6f4242b09 100644 --- a/helpers/url.go +++ b/helpers/url.go @@ -83,7 +83,7 @@ func sanitizeURLWithFlags(in string, f purell.NormalizationFlags) string { return u.String() // End temporary kludge - //return s + // return s } @@ -103,7 +103,6 @@ func SanitizeURLKeepTrailingSlash(in string) string { // urlize: vim-text-editor func (p *PathSpec) URLize(uri string) string { return p.URLEscape(p.MakePathSanitized(uri)) - } // URLizeFilename creates an URL from a filename by esacaping unicode letters @@ -130,7 +129,6 @@ func (p *PathSpec) URLEscape(uri string) string { // path: post/how-i-blog // result: http://spf13.com/post/how-i-blog func MakePermalink(host, plink string) *url.URL { - base, err := url.Parse(host) if err != nil { panic(err) @@ -275,7 +273,6 @@ func (p *PathSpec) RelURL(in string, addLanguage bool) string { // For relative URL entries on sites with a base url with a context root set (i.e. http://example.com/mysite), // relative URLs must not include the context root if canonifyURLs is enabled. But if it's disabled, it must be set. func AddContextRoot(baseURL, relativePath string) string { - url, err := url.Parse(baseURL) if err != nil { panic(err) diff --git a/helpers/url_test.go b/helpers/url_test.go index 6f374f027..4c16208f1 100644 --- a/helpers/url_test.go +++ b/helpers/url_test.go @@ -23,7 +23,6 @@ import ( ) func TestURLize(t *testing.T) { - v := newTestCfg() l := langs.NewDefaultLanguage(v) p, _ := NewPathSpec(hugofs.NewMem(v), l, nil) @@ -113,7 +112,6 @@ func doTestAbsURL(t *testing.T, defaultInSubDir, addLanguage, multilingual bool, } else { expected = strings.Replace(expected, "MULTI", lang+"/", 1) } - } else { expected = strings.Replace(expected, "MULTI", "", 1) } @@ -294,7 +292,6 @@ func TestURLPrep(t *testing.T) { t.Errorf("Test #%d failed. Expected %q got %q", i, d.output, output) } } - } func TestAddContextRoot(t *testing.T) { diff --git a/htesting/test_helpers.go b/htesting/test_helpers.go index 599e460f6..84b36ee27 100644 --- a/htesting/test_helpers.go +++ b/htesting/test_helpers.go @@ -48,7 +48,6 @@ func BailOut(after time.Duration) { runtime.Stack(buf, true) panic(string(buf)) }) - } // Rnd is used only for testing. diff --git a/hugofs/decorators.go b/hugofs/decorators.go index 6247f6183..62d234944 100644 --- a/hugofs/decorators.go +++ b/hugofs/decorators.go @@ -38,11 +38,9 @@ func decorateDirs(fs afero.Fs, meta FileMeta) afero.Fs { ffs.decorate = decorator return ffs - } func decoratePath(fs afero.Fs, createPath func(name string) string) afero.Fs { - ffs := &baseFileDecoratorFs{Fs: fs} decorator := func(fi os.FileInfo, name string) (os.FileInfo, error) { @@ -54,7 +52,6 @@ func decoratePath(fs afero.Fs, createPath func(name string) string) afero.Fs { ffs.decorate = decorator return ffs - } // DecorateBasePathFs adds Path info to files and directories in the @@ -81,7 +78,6 @@ func DecorateBasePathFs(base *afero.BasePathFs) afero.Fs { // NewBaseFileDecorator decorates the given Fs to provide the real filename // and an Opener func. func NewBaseFileDecorator(fs afero.Fs, callbacks ...func(fi FileMetaInfo)) afero.Fs { - ffs := &baseFileDecoratorFs{Fs: fs} decorator := func(fi os.FileInfo, filename string) (os.FileInfo, error) { @@ -128,7 +124,6 @@ func NewBaseFileDecorator(fs afero.Fs, callbacks ...func(fi FileMetaInfo)) afero } return fim, nil - } ffs.decorate = decorator @@ -161,7 +156,6 @@ func (fs *baseFileDecoratorFs) Stat(name string) (os.FileInfo, error) { } return fs.decorate(fi, name) - } func (fs *baseFileDecoratorFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { diff --git a/hugofs/fileinfo.go b/hugofs/fileinfo.go index 5bfb1ff32..d68321282 100644 --- a/hugofs/fileinfo.go +++ b/hugofs/fileinfo.go @@ -86,6 +86,7 @@ func (f FileMeta) OriginalFilename() string { func (f FileMeta) SkipDir() bool { return f.GetBool(metaKeySkipDir) } + func (f FileMeta) TranslationBaseName() string { return f.stringV(metaKeyTranslationBaseName) } @@ -236,7 +237,6 @@ func (fi *fileInfoMeta) Meta() FileMeta { } func NewFileMetaInfo(fi os.FileInfo, m FileMeta) FileMetaInfo { - if fim, ok := fi.(FileMetaInfo); ok { mergeFileMeta(fim.Meta(), m) } @@ -312,7 +312,6 @@ func decorateFileInfo( fi os.FileInfo, fs afero.Fs, opener func() (afero.File, error), filename, filepath string, inMeta FileMeta) FileMetaInfo { - var meta FileMeta var fim FileMetaInfo @@ -334,7 +333,6 @@ func decorateFileInfo( mergeFileMeta(inMeta, meta) return fim - } func isSymlink(fi os.FileInfo) bool { @@ -379,6 +377,5 @@ func sortFileInfos(fis []os.FileInfo) { sort.Slice(fis, func(i, j int) bool { fimi, fimj := fis[i].(FileMetaInfo), fis[j].(FileMetaInfo) return fimi.Meta().Filename() < fimj.Meta().Filename() - }) } diff --git a/hugofs/files/classifier.go b/hugofs/files/classifier.go index 35e416c8f..f0e0911ab 100644 --- a/hugofs/files/classifier.go +++ b/hugofs/files/classifier.go @@ -42,12 +42,14 @@ var ( "rest", "rst", "mmark", "org", - "pandoc", "pdc"} + "pandoc", "pdc", + } contentFileExtensionsSet map[string]bool htmlFileExtensions = []string{ - "html", "htm"} + "html", "htm", + } htmlFileExtensionsSet map[string]bool ) diff --git a/hugofs/files/classifier_test.go b/hugofs/files/classifier_test.go index 0cd7e4177..84036b870 100644 --- a/hugofs/files/classifier_test.go +++ b/hugofs/files/classifier_test.go @@ -39,7 +39,6 @@ func TestIsHTMLContent(t *testing.T) { c.Assert(isHTMLContent(strings.NewReader(" <!--")), qt.Equals, true) c.Assert(isHTMLContent(strings.NewReader(" ---<")), qt.Equals, false) c.Assert(isHTMLContent(strings.NewReader(" foo <")), qt.Equals, false) - } func TestComponentFolders(t *testing.T) { @@ -57,5 +56,4 @@ func TestComponentFolders(t *testing.T) { c.Assert(IsComponentFolder("content"), qt.Equals, true) c.Assert(IsComponentFolder("foo"), qt.Equals, false) c.Assert(IsComponentFolder(""), qt.Equals, false) - } diff --git a/hugofs/filter_fs.go b/hugofs/filter_fs.go index 15373c2e5..8b0afd38d 100644 --- a/hugofs/filter_fs.go +++ b/hugofs/filter_fs.go @@ -35,9 +35,7 @@ var ( ) func NewLanguageFs(langs map[string]int, fs afero.Fs) (afero.Fs, error) { - applyMeta := func(fs *FilterFs, name string, fis []os.FileInfo) { - for i, fi := range fis { if fi.IsDir() { filename := filepath.Join(name, fi.Name()) @@ -104,11 +102,9 @@ func NewLanguageFs(langs map[string]int, fs afero.Fs) (afero.Fs, error) { applyPerSource: applyMeta, applyAll: all, }, nil - } func NewFilterFs(fs afero.Fs) (afero.Fs, error) { - applyMeta := func(fs *FilterFs, name string, fis []os.FileInfo) { for i, fi := range fis { if fi.IsDir() { @@ -123,7 +119,6 @@ func NewFilterFs(fs afero.Fs) (afero.Fs, error) { } return ffs, nil - } // FilterFs is an ordered composite filesystem. @@ -144,7 +139,6 @@ func (fs *FilterFs) Chtimes(n string, a, m time.Time) error { func (fs *FilterFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { fi, b, err := lstatIfPossible(fs.fs, name) - if err != nil { return nil, false, err } @@ -157,7 +151,6 @@ func (fs *FilterFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { fs.applyFilters(parent, -1, fi) return fi, b, nil - } func (fs *FilterFs) Mkdir(n string, p os.FileMode) error { @@ -182,7 +175,6 @@ func (fs *FilterFs) Open(name string) (afero.File, error) { File: f, ffs: fs, }, nil - } func (fs *FilterFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { @@ -255,7 +247,6 @@ func (fs *FilterFs) applyFilters(name string, count int, fis ...os.FileInfo) ([] } return fis, nil - } type filterDir struct { @@ -313,7 +304,6 @@ func langInfoFrom(languages map[string]int, name string) (string, string, string } return lang, translationBaseName, translationBaseNameWithExt - } func printFs(fs afero.Fs, path string, w io.Writer) { diff --git a/hugofs/filter_fs_test.go b/hugofs/filter_fs_test.go index e3bf4c3b9..524d957d6 100644 --- a/hugofs/filter_fs_test.go +++ b/hugofs/filter_fs_test.go @@ -21,7 +21,6 @@ import ( ) func TestLangInfoFrom(t *testing.T) { - langs := map[string]int{ "sv": 10, "en": 20, @@ -44,5 +43,4 @@ func TestLangInfoFrom(t *testing.T) { v1, v2, v3 := langInfoFrom(langs, test.input) c.Assert([]string{v1, v2, v3}, qt.DeepEquals, test.expected) } - } diff --git a/hugofs/fs.go b/hugofs/fs.go index 75beda970..2c57fe8b5 100644 --- a/hugofs/fs.go +++ b/hugofs/fs.go @@ -23,10 +23,8 @@ import ( "github.com/spf13/afero" ) -var ( - // Os points to the (real) Os filesystem. - Os = &afero.OsFs{} -) +// Os points to the (real) Os filesystem. +var Os = &afero.OsFs{} // Fs abstracts the file system to separate source and destination file systems // and allows both to be mocked for testing. diff --git a/hugofs/fs_test.go b/hugofs/fs_test.go index 47a9482f5..a343bbd1f 100644 --- a/hugofs/fs_test.go +++ b/hugofs/fs_test.go @@ -31,7 +31,6 @@ func TestNewDefault(t *testing.T) { c.Assert(f.Source, hqt.IsSameType, new(afero.OsFs)) c.Assert(f.Os, qt.Not(qt.IsNil)) c.Assert(f.WorkingDir, qt.IsNil) - } func TestNewMem(t *testing.T) { @@ -57,5 +56,4 @@ func TestWorkingDir(t *testing.T) { c.Assert(f.WorkingDir, qt.Not(qt.IsNil)) c.Assert(f.WorkingDir, hqt.IsSameType, new(afero.BasePathFs)) - } diff --git a/hugofs/glob.go b/hugofs/glob.go index e4115ea7c..147b6b9f1 100644 --- a/hugofs/glob.go +++ b/hugofs/glob.go @@ -81,5 +81,4 @@ func Glob(fs afero.Fs, pattern string, handle func(fi FileMetaInfo) (bool, error } return nil - } diff --git a/hugofs/glob/glob.go b/hugofs/glob/glob.go index 88485e1f0..5d2d3d5e5 100644 --- a/hugofs/glob/glob.go +++ b/hugofs/glob/glob.go @@ -53,7 +53,6 @@ func GetGlob(pattern string) (glob.Glob, error) { globMu.Unlock() return eg.glob, eg.err - } func NormalizePath(p string) string { @@ -98,5 +97,4 @@ func HasGlobChar(s string) bool { } } return false - } diff --git a/hugofs/glob/glob_test.go b/hugofs/glob/glob_test.go index 5a6ef5b7e..cd64ba112 100644 --- a/hugofs/glob/glob_test.go +++ b/hugofs/glob/glob_test.go @@ -32,7 +32,6 @@ func TestResolveRootDir(t *testing.T) { {"dat?a/foo.json", ""}, {"a/b[a-c]/foo.json", "a"}, } { - c.Assert(ResolveRootDir(test.input), qt.Equals, test.expected) } } @@ -46,7 +45,6 @@ func TestFilterGlobParts(t *testing.T) { }{ {[]string{"a", "*", "c"}, []string{"a", "c"}}, } { - c.Assert(FilterGlobParts(test.input), qt.DeepEquals, test.expected) } } @@ -63,7 +61,6 @@ func TestNormalizePath(t *testing.T) { {filepath.FromSlash("./FOO.json"), "foo.json"}, {"//", ""}, } { - c.Assert(NormalizePath(test.input), qt.Equals, test.expected) } } @@ -82,5 +79,4 @@ func BenchmarkGetGlob(b *testing.B) { b.Fatal(err) } } - } diff --git a/hugofs/glob_test.go b/hugofs/glob_test.go index 3c7780685..b18864ef2 100644 --- a/hugofs/glob_test.go +++ b/hugofs/glob_test.go @@ -57,5 +57,4 @@ func TestGlob(t *testing.T) { c.Assert(collect("*.json"), qt.HasLen, 1) c.Assert(collect("**.xml"), qt.HasLen, 1) c.Assert(collect(filepath.FromSlash("/jsonfiles/*.json")), qt.HasLen, 2) - } diff --git a/hugofs/hashing_fs.go b/hugofs/hashing_fs.go index 94a50b960..d7b6329c9 100644 --- a/hugofs/hashing_fs.go +++ b/hugofs/hashing_fs.go @@ -22,9 +22,7 @@ import ( "github.com/spf13/afero" ) -var ( - _ afero.Fs = (*md5HashingFs)(nil) -) +var _ afero.Fs = (*md5HashingFs)(nil) // FileHashReceiver will receive the filename an the content's MD5 sum on file close. type FileHashReceiver interface { diff --git a/hugofs/hashing_fs_test.go b/hugofs/hashing_fs_test.go index b2bfb78f4..3e1f6c41d 100644 --- a/hugofs/hashing_fs_test.go +++ b/hugofs/hashing_fs_test.go @@ -49,5 +49,4 @@ func TestHashingFs(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(f.Close(), qt.IsNil) c.Assert(observer.sum, qt.Equals, "d41d8cd98f00b204e9800998ecf8427e") - } diff --git a/hugofs/nosymlink_fs.go b/hugofs/nosymlink_fs.go index fa89d61e0..e55d369e9 100644 --- a/hugofs/nosymlink_fs.go +++ b/hugofs/nosymlink_fs.go @@ -23,9 +23,7 @@ import ( "github.com/spf13/afero" ) -var ( - ErrPermissionSymlink = errors.New("symlinks not allowed in this filesystem") -) +var ErrPermissionSymlink = errors.New("symlinks not allowed in this filesystem") // NewNoSymlinkFs creates a new filesystem that prevents symlinks. func NewNoSymlinkFs(fs afero.Fs, logger loggers.Logger, allowFiles bool) afero.Fs { @@ -79,7 +77,6 @@ func (fs *noSymlinkFs) Stat(name string) (os.FileInfo, error) { } func (fs *noSymlinkFs) stat(name string) (os.FileInfo, bool, error) { - var ( fi os.FileInfo wasLstat bool diff --git a/hugofs/nosymlink_test.go b/hugofs/nosymlink_test.go index f541fc0a7..99151ec67 100644 --- a/hugofs/nosymlink_test.go +++ b/hugofs/nosymlink_test.go @@ -143,5 +143,4 @@ func TestNoSymlinkFs(t *testing.T) { } } - } diff --git a/hugofs/rootmapping_fs.go b/hugofs/rootmapping_fs.go index a38560d0a..4ffdb9c66 100644 --- a/hugofs/rootmapping_fs.go +++ b/hugofs/rootmapping_fs.go @@ -27,9 +27,7 @@ import ( "github.com/spf13/afero" ) -var ( - filepathSeparator = string(filepath.Separator) -) +var filepathSeparator = string(filepath.Separator) // NewRootMappingFs creates a new RootMappingFs on top of the provided with // root mappings with some optional metadata about the root. @@ -102,7 +100,6 @@ func newRootMappingFsFromFromTo( fs afero.Fs, fromTo ...string, ) (*RootMappingFs, error) { - rms := make([]RootMapping, len(fromTo)/2) for i, j := 0, 0; j < len(fromTo); i, j = i+1, j+2 { rms[i] = RootMapping{ @@ -223,7 +220,6 @@ func (fs *RootMappingFs) LstatIfPossible(name string) (os.FileInfo, bool, error) // Open opens the named file for reading. func (fs *RootMappingFs) Open(name string) (afero.File, error) { fis, err := fs.doLstat(name) - if err != nil { return nil, err } @@ -236,7 +232,6 @@ func (fs *RootMappingFs) Open(name string) (afero.File, error) { func (fs *RootMappingFs) Stat(name string) (os.FileInfo, error) { fi, _, err := fs.LstatIfPossible(name) return fi, err - } func (fs *RootMappingFs) hasPrefix(prefix string) bool { @@ -264,7 +259,6 @@ func (fs *RootMappingFs) getRoots(key string) (string, []RootMapping) { return "", nil } return s, v.([]RootMapping) - } func (fs *RootMappingFs) debug() { @@ -273,7 +267,6 @@ func (fs *RootMappingFs) debug() { fmt.Println("Key", s) return false }) - } func (fs *RootMappingFs) getRootsWithPrefix(prefix string) []RootMapping { @@ -347,7 +340,6 @@ func (fs *RootMappingFs) newUnionFile(fis ...FileMetaInfo) (afero.File, error) { } return uf, nil - } func (fs *RootMappingFs) cleanName(name string) string { @@ -407,7 +399,6 @@ func (fs *RootMappingFs) collectDirEntries(prefix string) ([]os.FileInfo, error) // Next add any file mounts inside the given directory. prefixInside := prefix + filepathSeparator fs.rootMapToReal.WalkPrefix(prefixInside, func(s string, v interface{}) bool { - if (strings.Count(s, filepathSeparator) - level) != 1 { // This directory is not part of the current, but we // need to include the first name part to make it @@ -534,11 +525,9 @@ func (fs *RootMappingFs) doLstat(name string) ([]FileMetaInfo, error) { if fileCount > 1 { // Not supported by this filesystem. return nil, errors.Errorf("found multiple files with name %q, use .Readdir or the source filesystem directly", name) - } return []FileMetaInfo{roots[0].fi}, nil - } func (fs *RootMappingFs) statRoot(root RootMapping, name string) (FileMetaInfo, bool, error) { @@ -561,7 +550,6 @@ func (fs *RootMappingFs) statRoot(root RootMapping, name string) (FileMetaInfo, } return decorateFileInfo(fi, fs.Fs, opener, "", "", root.Meta), b, nil - } func (fs *RootMappingFs) virtualDirOpener(name string) func() (afero.File, error) { diff --git a/hugofs/rootmapping_fs_test.go b/hugofs/rootmapping_fs_test.go index b2552431a..e5f68d7a9 100644 --- a/hugofs/rootmapping_fs_test.go +++ b/hugofs/rootmapping_fs_test.go @@ -138,7 +138,6 @@ func TestLanguageRootMapping(t *testing.T) { c.Assert(getDirnames("content", rfsSv), qt.DeepEquals, []string{"blog", "docs"}) c.Assert(getDirnames("content", rfs), qt.DeepEquals, []string{"blog", "docs"}) - } func TestRootMappingFsDirnames(t *testing.T) { @@ -166,7 +165,6 @@ func TestRootMappingFsDirnames(t *testing.T) { dirnames, err := root.Readdirnames(-1) c.Assert(err, qt.IsNil) c.Assert(dirnames, qt.DeepEquals, []string{"af3", "bf1", "cf2"}) - } func TestRootMappingFsFilename(t *testing.T) { @@ -208,29 +206,29 @@ func TestRootMappingFsMount(t *testing.T) { bfs := afero.NewBasePathFs(fs, "themes/a").(*afero.BasePathFs) rm := []RootMapping{ // Directories - RootMapping{ + { From: "content/blog", To: "mynoblogcontent", Meta: FileMeta{"lang": "no"}, }, - RootMapping{ + { From: "content/blog", To: "myenblogcontent", Meta: FileMeta{"lang": "en"}, }, - RootMapping{ + { From: "content/blog", To: "mysvblogcontent", Meta: FileMeta{"lang": "sv"}, }, // Files - RootMapping{ + { From: "content/singles/p1.md", To: "singlefiles/no.txt", ToBasedir: "singlefiles", Meta: FileMeta{"lang": "no"}, }, - RootMapping{ + { From: "content/singles/p1.md", To: "singlefiles/sv.txt", ToBasedir: "singlefiles", @@ -300,19 +298,19 @@ func TestRootMappingFsMountOverlap(t *testing.T) { c.Assert(afero.WriteFile(fs, filepath.FromSlash("de/e.txt"), []byte("some no content"), 0755), qt.IsNil) rm := []RootMapping{ - RootMapping{ + { From: "static", To: "da", }, - RootMapping{ + { From: "static/b", To: "db", }, - RootMapping{ + { From: "static/b/c", To: "dc", }, - RootMapping{ + { From: "/static/e/", To: "de", }, @@ -339,7 +337,6 @@ func TestRootMappingFsMountOverlap(t *testing.T) { fi, err := rfs.Stat(filepath.FromSlash("static/b/b.txt")) c.Assert(err, qt.IsNil) c.Assert(fi.Name(), qt.Equals, "b.txt") - } func TestRootMappingFsOs(t *testing.T) { @@ -485,5 +482,4 @@ func TestRootMappingFsOsBase(t *testing.T) { } c.Assert(getDirnames("static/a/b/c"), qt.DeepEquals, []string{"d4", "f-1.txt", "f-2.txt", "f-3.txt", "ms-1.txt"}) - } diff --git a/hugofs/slice_fs.go b/hugofs/slice_fs.go index 4fb026ab2..f1682c1b8 100644 --- a/hugofs/slice_fs.go +++ b/hugofs/slice_fs.go @@ -45,7 +45,6 @@ func NewSliceFs(dirs ...FileMetaInfo) (afero.Fs, error) { } return fs, nil - } // SliceFs is an ordered composite filesystem. @@ -63,7 +62,6 @@ func (fs *SliceFs) Chtimes(n string, a, m time.Time) error { func (fs *SliceFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { fi, _, err := fs.pickFirst(name) - if err != nil { return nil, false, err } @@ -73,7 +71,6 @@ func (fs *SliceFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { } return nil, false, errors.Errorf("lstat: files not supported: %q", name) - } func (fs *SliceFs) Mkdir(n string, p os.FileMode) error { @@ -103,7 +100,6 @@ func (fs *SliceFs) Open(name string) (afero.File, error) { idx: idx, dirname: name, }, nil - } func (fs *SliceFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { @@ -222,7 +218,6 @@ func (fs *SliceFs) readDirs(name string, startIdx, count int) ([]os.FileInfo, er } return dirs, nil - } type sliceDir struct { diff --git a/hugofs/walk.go b/hugofs/walk.go index 91dd386e2..a46b36e50 100644 --- a/hugofs/walk.go +++ b/hugofs/walk.go @@ -98,7 +98,8 @@ func NewWalkway(cfg WalkwayConfig) *Walkway { hookPre: cfg.HookPre, hookPost: cfg.HookPost, logger: logger, - seen: make(map[string]bool)} + seen: make(map[string]bool), + } } func (w *Walkway) Walk() error { @@ -134,7 +135,6 @@ func (w *Walkway) Walk() error { } return w.walk(w.root, fi, w.dirEntries, w.walkFn) - } // if the filesystem supports it, use Lstat, else use fs.Stat diff --git a/hugofs/walk_test.go b/hugofs/walk_test.go index c38c6044f..d5ae33a34 100644 --- a/hugofs/walk_test.go +++ b/hugofs/walk_test.go @@ -56,16 +56,16 @@ func TestWalkRootMappingFs(t *testing.T) { c.Assert(afero.WriteFile(fs, filepath.Join("e/f", testfile), []byte("some content"), 0755), qt.IsNil) rm := []RootMapping{ - RootMapping{ + { From: "static/b", To: "e/f", }, - RootMapping{ + { From: "static/a", To: "c/d", }, - RootMapping{ + { From: "static/c", To: "a/b", }, @@ -79,7 +79,6 @@ func TestWalkRootMappingFs(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(names, qt.DeepEquals, []string{"a/test.txt", "b/test.txt", "c/test.txt"}) - } func skipSymlink() bool { @@ -137,7 +136,6 @@ func TestWalkSymbolicLink(t *testing.T) { // Note: the docsreal folder is considered cyclic when walking from the root, but this works. c.Assert(names, qt.DeepEquals, []string{"b.txt", "docsreal/sub/a.txt"}) }) - } func collectFilenames(fs afero.Fs, base, root string) ([]string, error) { @@ -165,7 +163,6 @@ func collectFilenames(fs afero.Fs, base, root string) ([]string, error) { err := w.Walk() return names, err - } func collectFileinfos(fs afero.Fs, base, root string) ([]FileMetaInfo, error) { @@ -186,7 +183,6 @@ func collectFileinfos(fs afero.Fs, base, root string) ([]FileMetaInfo, error) { err := w.Walk() return fis, err - } func BenchmarkWalk(b *testing.B) { @@ -234,5 +230,4 @@ func BenchmarkWalk(b *testing.B) { b.Fatal(err) } } - } diff --git a/hugolib/404_test.go b/hugolib/404_test.go index cd203a669..383302e0b 100644 --- a/hugolib/404_test.go +++ b/hugolib/404_test.go @@ -57,7 +57,6 @@ Page: /404.html| Data: 1| `) - } func Test404WithBase(t *testing.T) { @@ -77,5 +76,4 @@ Page not found b.AssertFileContent("public/404.html", ` Base: Page not found`) - } diff --git a/hugolib/alias.go b/hugolib/alias.go index 6272b7910..891098c9d 100644 --- a/hugolib/alias.go +++ b/hugolib/alias.go @@ -47,7 +47,6 @@ type aliasPage struct { } func (a aliasHandler) renderAlias(permalink string, p page.Page) (io.Reader, error) { - var templ tpl.Template var found bool diff --git a/hugolib/alias_test.go b/hugolib/alias_test.go index 8f3b756ec..d5ffc06fe 100644 --- a/hugolib/alias_test.go +++ b/hugolib/alias_test.go @@ -38,8 +38,10 @@ outputs: ["HTML", "AMP", "JSON"] For some moments the old man did not reply. He stood with bowed head, buried in deep thought. But at last he spoke. ` -const basicTemplate = "<html><body>{{.Content}}</body></html>" -const aliasTemplate = "<html><body>ALIASTEMPLATE</body></html>" +const ( + basicTemplate = "<html><body>{{.Content}}</body></html>" + aliasTemplate = "<html><body>ALIASTEMPLATE</body></html>" +) func TestAlias(t *testing.T) { t.Parallel() diff --git a/hugolib/breaking_changes_test.go b/hugolib/breaking_changes_test.go index c935d6e93..a22bc240f 100644 --- a/hugolib/breaking_changes_test.go +++ b/hugolib/breaking_changes_test.go @@ -21,11 +21,9 @@ import ( ) func Test073(t *testing.T) { - asertDisabledTaxonomyAndTerm := func(b *sitesBuilder, taxonomy, term bool) { b.Assert(b.CheckExists("public/tags/index.html"), qt.Equals, taxonomy) b.Assert(b.CheckExists("public/tags/tag1/index.html"), qt.Equals, term) - } assertOutputTaxonomyAndTerm := func(b *sitesBuilder, taxonomy, term bool) { @@ -48,7 +46,6 @@ func Test073(t *testing.T) { func(err error, out string, b *sitesBuilder) { b.Assert(err, qt.IsNil) assertOutputTaxonomyAndTerm(b, true, true) - }, }, { @@ -60,7 +57,6 @@ taxonomyTerm = ["JSON"] func(err error, out string, b *sitesBuilder) { b.Assert(err, qt.IsNil) assertOutputTaxonomyAndTerm(b, true, false) - }, }, { @@ -72,7 +68,6 @@ taxonomy = ["JSON"] func(err error, out string, b *sitesBuilder) { b.Assert(err, qt.Not(qt.IsNil)) b.Assert(out, qt.Contains, `ignoreErrors = ["error-output-taxonomy"]`) - }, }, { @@ -86,7 +81,6 @@ taxonomy = ["JSON"] func(err error, out string, b *sitesBuilder) { b.Assert(err, qt.IsNil) assertOutputTaxonomyAndTerm(b, true, false) - }, }, { @@ -95,7 +89,6 @@ taxonomy = ["JSON"] func(err error, out string, b *sitesBuilder) { b.Assert(err, qt.IsNil) asertDisabledTaxonomyAndTerm(b, false, false) - }, }, { @@ -104,7 +97,6 @@ taxonomy = ["JSON"] func(err error, out string, b *sitesBuilder) { b.Assert(err, qt.IsNil) asertDisabledTaxonomyAndTerm(b, false, true) - }, }, { @@ -125,7 +117,6 @@ taxonomy = ["JSON"] }, }, } { - t.Run(this.name, func(t *testing.T) { b := newTestSitesBuilder(t).WithConfigFile("toml", this.config) b.WithTemplatesAdded("_default/list.json", "JSON") @@ -135,7 +126,5 @@ taxonomy = ["JSON"] fmt.Println(out) this.assert(err, out, b) }) - } - } diff --git a/hugolib/cascade_test.go b/hugolib/cascade_test.go index a112fe10c..78409a4b1 100644 --- a/hugolib/cascade_test.go +++ b/hugolib/cascade_test.go @@ -51,7 +51,6 @@ func BenchmarkCascade(b *testing.B) { } func TestCascade(t *testing.T) { - allLangs := []string{"en", "nn", "nb", "sv"} langs := allLangs[:3] @@ -101,9 +100,7 @@ func TestCascade(t *testing.T) { // Check cascade into bundled page b.AssertFileContent("public/bundle1/index.html", `Resources: bp1.md|home.png|`) - }) - } func TestCascadeEdit(t *testing.T) { @@ -252,7 +249,6 @@ func newCascadeTestBuilder(t testing.TB, langs []string) *sitesBuilder { metaStr := "---\n" + yamlStr + "\n---" return metaStr - } createLangConfig := func(lang string) string { @@ -290,7 +286,6 @@ defaultContentLanguageInSubDir = false b := newTestSitesBuilder(t).WithConfigFile("toml", config) createContentFiles := func(lang string) { - withContent := func(filenameContent ...string) { for i := 0; i < len(filenameContent); i += 2 { b.WithContent(path.Join(lang, filenameContent[i]), filenameContent[i+1]) @@ -414,7 +409,6 @@ S1|p1:{{ $s1.Params.p1 }}|p2:{{ $s1.Params.p2 }}| b.WithContent("s2/p1/index.md", "---\ntitle: p1_2\n---") return b - } c.Run("slice", func(c *qt.C) { @@ -431,7 +425,6 @@ p2 = "p2" b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "P1|p1:p1|p2:p2") - }) c.Run("slice with _target", func(c *qt.C) { @@ -456,7 +449,6 @@ kind="section" P1|p1:p1|p2:| S1|p1:|p2:p2| `) - }) c.Run("slice with yaml _target", func(c *qt.C) { @@ -480,7 +472,6 @@ cascade: P1|p1:p1|p2:| S1|p1:|p2:p2| `) - }) c.Run("slice with json _target", func(c *qt.C) { @@ -510,7 +501,5 @@ S1|p1:|p2:p2| P1|p1:p1|p2:| S1|p1:|p2:p2| `) - }) - } diff --git a/hugolib/case_insensitive_test.go b/hugolib/case_insensitive_test.go index 42b9d7ef6..9aa88ab5b 100644 --- a/hugolib/case_insensitive_test.go +++ b/hugolib/case_insensitive_test.go @@ -127,7 +127,6 @@ Partial Site Global: {{ site.Params.COLOR }}|{{ site.Params.COLORS.YELLOW }} `) writeToFs(t, fs, "config.toml", caseMixingSiteConfigTOML) - } func TestCaseInsensitiveConfigurationVariations(t *testing.T) { @@ -184,7 +183,6 @@ Page2: {{ $page2.Params.ColoR }} `) sites, err := NewHugoSites(deps.DepsCfg{Fs: fs, Cfg: cfg}) - if err != nil { t.Fatalf("Failed to create sites: %s", err) } diff --git a/hugolib/config.go b/hugolib/config.go index 9acb7d701..5ef78acf4 100644 --- a/hugolib/config.go +++ b/hugolib/config.go @@ -123,7 +123,6 @@ var ErrNoConfigFile = errors.New("Unable to locate config file or config directo // LoadConfig loads Hugo configuration into a new Viper and then adds // a set of defaults. func LoadConfig(d ConfigSourceDescriptor, doWithConfig ...func(cfg config.Provider) error) (*viper.Viper, []string, error) { - if d.Environment == "" { d.Environment = hugo.EnvironmentProduction } @@ -258,7 +257,6 @@ func LoadConfig(d ConfigSourceDescriptor, doWithConfig ...func(cfg config.Provid } return v, configFiles, err - } func loadLanguageSettings(cfg config.Provider, oldLangs langs.Languages) error { @@ -310,7 +308,6 @@ func (l configLoader) loadConfig(configName string, v *viper.Viper) (string, err } return filename, nil - } func (l configLoader) wrapFileError(err error, filename string) error { @@ -414,9 +411,7 @@ func (l configLoader) loadConfigFromConfigDir(v *viper.Viper) ([]string, error) } return nil - }) - if err != nil { return nil, err } @@ -427,7 +422,6 @@ func (l configLoader) loadConfigFromConfigDir(v *viper.Viper) ([]string, error) } func (l configLoader) loadModulesConfig(v1 *viper.Viper) (modules.Config, error) { - modConfig, err := modules.DecodeConfig(v1) if err != nil { return modules.Config{}, err @@ -475,7 +469,6 @@ func (l configLoader) collectModules(modConfig modules.Config, v1 *viper.Viper, } return nil - } modulesClient := modules.NewClient(modules.ClientConfig{ @@ -503,11 +496,9 @@ func (l configLoader) collectModules(modConfig modules.Config, v1 *viper.Viper, } return moduleConfig.ActiveModules, configFilenames, err - } func (l configLoader) applyThemeConfig(v1 *viper.Viper, theme modules.Module) error { - const ( paramsKey = "params" languagesKey = "languages" @@ -560,7 +551,6 @@ func (l configLoader) applyThemeConfig(v1 *viper.Viper, theme modules.Module) er } return nil - } func (configLoader) mergeStringMapKeepLeft(rootKey, key string, v1, v2 config.Provider) { @@ -587,7 +577,6 @@ func (configLoader) mergeStringMapKeepLeft(rootKey, key string, v1, v2 config.Pr } func loadDefaultSettingsFor(v *viper.Viper) error { - v.RegisterAlias("indexes", "taxonomies") /* diff --git a/hugolib/config_test.go b/hugolib/config_test.go index e8dce331d..aeeee5fa5 100644 --- a/hugolib/config_test.go +++ b/hugolib/config_test.go @@ -43,7 +43,6 @@ func TestLoadConfig(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "side") - } func TestLoadMultiConfig(t *testing.T) { @@ -359,7 +358,6 @@ map[string]interface {}{ }, }, }`, got["menu"]) - } func TestPrivacyConfig(t *testing.T) { @@ -381,7 +379,6 @@ privacyEnhanced = true b.Build(BuildCfg{SkipRender: true}) c.Assert(b.H.Sites[0].Info.Config().Privacy.YouTube.PrivacyEnhanced, qt.Equals, true) - } func TestLoadConfigModules(t *testing.T) { @@ -477,11 +474,9 @@ project n4 ` c.Assert(graphb.String(), qt.Equals, expected) - } func TestLoadConfigWithOsEnvOverrides(t *testing.T) { - c := qt.New(t) baseConfig := ` @@ -534,5 +529,4 @@ quality = 75 c.Assert(cfg.Get("intSlice"), qt.DeepEquals, []interface{}{5, 8, 9}) c.Assert(cfg.Get("params.api_config.api_key"), qt.Equals, "new_key") c.Assert(cfg.Get("params.api_config.another_key"), qt.Equals, "default another_key") - } diff --git a/hugolib/configdir_test.go b/hugolib/configdir_test.go index bc1732fb2..aa1013ec0 100644 --- a/hugolib/configdir_test.go +++ b/hugolib/configdir_test.go @@ -123,7 +123,6 @@ p3 = "p3params_no_production" noMenus := cfg.Get("languages.no.menus.docs") c.Assert(noMenus, qt.Not(qt.IsNil)) c.Assert(len(noMenus.(([]map[string]interface{}))), qt.Equals, 1) - } func TestLoadConfigDirError(t *testing.T) { @@ -150,5 +149,4 @@ baseURL = "https://example.org" fe := herrors.UnwrapErrorWithFileContext(err) c.Assert(fe, qt.Not(qt.IsNil)) c.Assert(fe.Position().Filename, qt.Equals, filepath.FromSlash("config/development/config.toml")) - } diff --git a/hugolib/content_map.go b/hugolib/content_map.go index 652609e26..ca2aa3672 100644 --- a/hugolib/content_map.go +++ b/hugolib/content_map.go @@ -130,7 +130,7 @@ type cmInsertKeyBuilder struct { } func (b cmInsertKeyBuilder) ForPage(s string) *cmInsertKeyBuilder { - //fmt.Println("ForPage:", s, "baseKey:", b.baseKey, "key:", b.key) + // fmt.Println("ForPage:", s, "baseKey:", b.baseKey, "key:", b.key) baseKey := b.baseKey b.baseKey = s @@ -154,7 +154,7 @@ func (b cmInsertKeyBuilder) ForPage(s string) *cmInsertKeyBuilder { } func (b cmInsertKeyBuilder) ForResource(s string) *cmInsertKeyBuilder { - //fmt.Println("ForResource:", s, "baseKey:", b.baseKey, "key:", b.key) + // fmt.Println("ForResource:", s, "baseKey:", b.baseKey, "key:", b.key) baseKey := helpers.AddTrailingSlash(b.baseKey) s = strings.TrimPrefix(s, baseKey) @@ -287,7 +287,6 @@ func (c *contentBundleViewInfo) sections() []string { } return []string{c.name.plural, c.termKey} - } func (c *contentBundleViewInfo) term() string { @@ -393,7 +392,6 @@ func (m *contentMap) AddFilesBundle(header hugofs.FileMetaInfo, resources ...hug } return nil - } func (m *contentMap) CreateMissingNodes() error { @@ -462,7 +460,6 @@ func (m *contentMap) CreateMissingNodes() error { } return nil - } func (m *contentMap) getBundleDir(meta hugofs.FileMeta) string { @@ -611,7 +608,6 @@ func (m *contentMap) deleteBundleMatching(matches func(b *contentNode) bool) { if s != "" { m.resources.Delete(s) } - } // Deletes any empty root section that's not backed by a content file. @@ -686,7 +682,6 @@ func (m *contentMap) splitKey(k string) []string { } return strings.Split(k, "/")[1:] - } func (m *contentMap) testDump() string { @@ -701,7 +696,6 @@ func (m *contentMap) testDump() string { } for i, r := range []*contentTree{m.pages, m.sections} { - r.Walk(func(s string, v interface{}) bool { c := v.(*contentNode) cpToString := func(c *contentNode) string { @@ -730,7 +724,6 @@ func (m *contentMap) testDump() string { m.resources.WalkPrefix(resourcesPrefix, func(s string, v interface{}) bool { sb.WriteString("\t - R: " + filepath.ToSlash((v.(*contentNode).fi.(hugofs.FileMetaInfo)).Meta().Filename()) + "\n") return false - }) return false @@ -738,7 +731,6 @@ func (m *contentMap) testDump() string { } return sb.String() - } type contentMapConfig struct { @@ -787,7 +779,6 @@ func (b *contentNode) rootSection() string { return b.path } return b.path[:firstSlash] - } type contentTree struct { @@ -906,7 +897,6 @@ func (c *contentTree) WalkBelow(prefix string, fn radix.WalkFn) { } return fn(s, v) }) - } func (c *contentTree) getMatch(matches func(b *contentNode) bool) string { diff --git a/hugolib/content_map_page.go b/hugolib/content_map_page.go index e79228ba3..296363359 100644 --- a/hugolib/content_map_page.go +++ b/hugolib/content_map_page.go @@ -225,7 +225,6 @@ func (m *pageMap) newPageFromContentNode(n *contentNode, parentBucket *pagesMapB } func (m *pageMap) newResource(fim hugofs.FileMetaInfo, owner *pageState) (resource.Resource, error) { - if owner == nil { panic("owner is nil") } @@ -424,7 +423,6 @@ func (m *pageMap) assembleResources(s string, p *pageState, parentBucket *pagesM } func (m *pageMap) assembleSections() error { - var sectionsToDelete []string var err error @@ -508,7 +506,6 @@ func (m *pageMap) assembleSections() error { } func (m *pageMap) assembleTaxonomies() error { - var taxonomiesToDelete []string var err error @@ -565,7 +562,6 @@ func (m *pageMap) assembleTaxonomies() error { } return err - } func (m *pageMap) attachPageToViews(s string, b *contentNode) { @@ -656,7 +652,6 @@ func (m *pageMap) collectSections(query pageMapQuery, fn func(c *contentNode)) e } func (m *pageMap) collectSectionsFn(query pageMapQuery, fn func(s string, c *contentNode) bool) error { - if !strings.HasSuffix(query.Prefix, "/") { query.Prefix += "/" } @@ -957,11 +952,9 @@ func (w *sectionWalker) applyAggregates() *sectionAggregateHandler { return w.walkLevel("/", func() sectionWalkHandler { return §ionAggregateHandler{} }).(*sectionAggregateHandler) - } func (w *sectionWalker) walkLevel(prefix string, createVisitor func() sectionWalkHandler) sectionWalkHandler { - level := strings.Count(prefix, "/") visitor := createVisitor() @@ -1029,7 +1022,6 @@ func (w *sectionWalker) walkLevel(prefix string, createVisitor func() sectionWal }) return visitor - } type viewName struct { diff --git a/hugolib/content_map_test.go b/hugolib/content_map_test.go index 42a69c26b..9d7212735 100644 --- a/hugolib/content_map_test.go +++ b/hugolib/content_map_test.go @@ -43,7 +43,6 @@ func BenchmarkContentMap(b *testing.B) { mfi := fi.(hugofs.FileMetaInfo) return mfi - } createFs := func(fs afero.Fs, lang string) afero.Fs { @@ -55,7 +54,6 @@ func BenchmarkContentMap(b *testing.B) { meta["lang"] = lang meta["path"] = meta.Filename() meta["classifier"] = files.ClassifyContentFile(fi.Name(), meta.GetOpener()) - }) } @@ -87,7 +85,6 @@ func BenchmarkContentMap(b *testing.B) { b.StartTimer() } }) - } func TestContentMap(t *testing.T) { @@ -104,7 +101,6 @@ func TestContentMap(t *testing.T) { mfi := fi.(hugofs.FileMetaInfo) return mfi - } createFs := func(fs afero.Fs, lang string) afero.Fs { @@ -117,12 +113,10 @@ func TestContentMap(t *testing.T) { meta["path"] = meta.Filename() meta["classifier"] = files.ClassifyContentFile(fi.Name(), meta.GetOpener()) meta["translationBaseName"] = helpers.Filename(fi.Name()) - }) } c.Run("AddFiles", func(c *qt.C) { - memfs := afero.NewMemMapFs() fsl := func(lang string) afero.Fs { @@ -254,11 +248,9 @@ func TestContentMap(t *testing.T) { `, qt.Commentf(m.testDump())) - }) c.Run("CreateMissingNodes", func(c *qt.C) { - memfs := afero.NewMemMapFs() fsl := func(lang string) afero.Fs { @@ -297,7 +289,6 @@ func TestContentMap(t *testing.T) { - P: blog/page.md `, qt.Commentf(got)) - }) c.Run("cleanKey", func(c *qt.C) { @@ -309,15 +300,12 @@ func TestContentMap(t *testing.T) { {filepath.FromSlash("/a/b/"), "/a/b"}, {"/a//b/", "/a/b"}, } { - c.Assert(cleanTreeKey(test.in), qt.Equals, test.expected) - } }) } func TestContentMapSite(t *testing.T) { - b := newTestSitesBuilder(t) pageTempl := ` diff --git a/hugolib/content_render_hooks_test.go b/hugolib/content_render_hooks_test.go index 13bfe216a..197581bb6 100644 --- a/hugolib/content_render_hooks_test.go +++ b/hugolib/content_render_hooks_test.go @@ -54,7 +54,6 @@ title: P1 b.Build(BuildCfg{}) b.AssertFileContent("public/p1/index.html", `Link First Link|PARTIAL1_EDITED PARTIAL2_EDITEDEND`) - } func TestRenderHooks(t *testing.T) { @@ -243,7 +242,6 @@ SHORT3| // https://github.com/gohugoio/hugo/issues/7349 b.AssertFileContent("public/docs/p8/index.html", "Docs Level: 1") - } func TestRenderHooksDeleteTemplate(t *testing.T) { @@ -271,7 +269,6 @@ title: P1 b.Build(BuildCfg{}) b.AssertFileContent("public/p1/index.html", `<p><a href="https://www.google.com" title="Google's Homepage">First Link</a></p>`) - } func TestRenderHookAddTemplate(t *testing.T) { @@ -297,11 +294,9 @@ title: P1 b.Build(BuildCfg{}) b.AssertFileContent("public/p1/index.html", `<p>html-render-link</p>`) - } func TestRenderHooksRSS(t *testing.T) { - b := newTestSitesBuilder(t) b.WithTemplates("index.html", ` @@ -352,12 +347,10 @@ P3. [I'm an inline-style link](https://www.example.org) P2: <p>P1. xml-link: https://www.bep.is|</p> P3: <p>P3. xml-link: https://www.example.org|</p> `) - } // https://github.com/gohugoio/hugo/issues/6629 func TestRenderLinkWithMarkupInText(t *testing.T) { - b := newTestSitesBuilder(t) b.WithConfigFile("toml", ` @@ -400,11 +393,9 @@ Image: <p>Some regular <strong>markup</strong>.</p> <p>html-image: image.jpg|Text: Hello<br> Goodbye|Plain: Hello GoodbyeEND</p> `) - } func TestRenderString(t *testing.T) { - b := newTestSitesBuilder(t) b.WithTemplates("index.html", ` @@ -433,7 +424,6 @@ RSTART:<p><strong>Bold Block Markdown</strong></p> RSTART:<em>italic org mode</em>:REND RSTART:Hook Heading: 2:REND `) - } // https://github.com/gohugoio/hugo/issues/6882 @@ -460,5 +450,4 @@ func TestRenderStringOnListPage(t *testing.T) { } { b.AssertFileContent("public/"+filename, `<strong>Hello</strong>`) } - } diff --git a/hugolib/datafiles_test.go b/hugolib/datafiles_test.go index 294dc8379..f31024cf5 100644 --- a/hugolib/datafiles_test.go +++ b/hugolib/datafiles_test.go @@ -14,17 +14,16 @@ package hugolib import ( + "fmt" "path/filepath" "reflect" + "runtime" "testing" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/deps" - "fmt" - "runtime" - qt "github.com/frankban/quicktest" ) @@ -197,7 +196,6 @@ func TestDataDirMultipleSources(t *testing.T) { doTestDataDir(t, dd, expected, "theme", "mytheme") - } // test (and show) the way values from four different sources, @@ -301,7 +299,8 @@ func TestDataDirNestedDirectories(t *testing.T) { expected := map[string]interface{}{ "a": []interface{}{"1", "2", "3"}, - "test1": map[string]interface{}{"20": map[string]interface{}{"05": map[string]interface{}{"b": map[string]interface{}{"artist": "Charlie Parker"}}, "06": map[string]interface{}{"a": map[string]interface{}{"artist": "Michael Brecker"}}}}} + "test1": map[string]interface{}{"20": map[string]interface{}{"05": map[string]interface{}{"b": map[string]interface{}{"artist": "Charlie Parker"}}, "06": map[string]interface{}{"a": map[string]interface{}{"artist": "Michael Brecker"}}}}, + } doTestDataDir(t, dd, expected, "theme", "mytheme") } @@ -331,9 +330,7 @@ func doTestDataDir(t *testing.T, dd dataDir, expected interface{}, configKeyValu } func doTestDataDirImpl(t *testing.T, dd dataDir, expected interface{}, configKeyValues ...interface{}) (err string) { - var ( - cfg, fs = newTestCfg() - ) + cfg, fs := newTestCfg() for i := 0; i < len(configKeyValues); i += 2 { cfg.Set(configKeyValues[i].(string), configKeyValues[i+1]) diff --git a/hugolib/disableKinds_test.go b/hugolib/disableKinds_test.go index 73786c730..87a60d636 100644 --- a/hugolib/disableKinds_test.go +++ b/hugolib/disableKinds_test.go @@ -13,9 +13,8 @@ package hugolib import ( - "testing" - "fmt" + "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/resources/page" @@ -100,7 +99,6 @@ title: Headless Local Lists Sub b.WithSourceFile("content/sect/no-publishresources/data.json", "DATA") return b - } getPage := func(b *sitesBuilder, ref string) page.Page { @@ -210,7 +208,6 @@ title: Headless Local Lists Sub b.Assert(getPageInPagePages(sect, "/sect/page.md"), qt.Not(qt.IsNil)) b.AssertFileContent("public/sitemap.xml", "sitemap") b.AssertFileContent("public/index.xml", "rss") - }) disableKind = kindRSS @@ -269,7 +266,6 @@ title: Headless Local Lists Sub b.Assert(getPageInSitePages(b, ref), qt.IsNil) sect := getPage(b, "/sect") b.Assert(getPageInPagePages(sect, ref), qt.IsNil) - }) c.Run("Build config, local list", func(c *qt.C) { @@ -356,7 +352,6 @@ home = [ "HTML", "RSS" ] // In Hugo 0.65 we consolidated the code paths and made RSS a pure output format, // but we should make sure to not break existing sites. b.Assert(b.CheckExists("public/index.xml"), qt.Equals, false) - } func TestBundleNoPublishResources(t *testing.T) { @@ -419,5 +414,4 @@ Section: MySection|RelPermalink: |Outputs: 0 b.Assert(b.CheckExists("public/sect/no-render/index.html"), qt.Equals, false) b.Assert(b.CheckExists("public/sect-no-render/index.html"), qt.Equals, false) - } diff --git a/hugolib/embedded_shortcodes_test.go b/hugolib/embedded_shortcodes_test.go index b8acb2d80..3ea1d8ab0 100644 --- a/hugolib/embedded_shortcodes_test.go +++ b/hugolib/embedded_shortcodes_test.go @@ -17,13 +17,12 @@ import ( "encoding/json" "fmt" "html/template" + "path/filepath" "strings" "testing" "github.com/spf13/cast" - "path/filepath" - "github.com/gohugoio/hugo/deps" qt "github.com/frankban/quicktest" @@ -86,12 +85,14 @@ func TestShortcodeHighlight(t *testing.T) { for _, this := range []struct { in, expected string }{ - {`{{< highlight java >}} + { + `{{< highlight java >}} void do(); {{< /highlight >}}`, `(?s)<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java"`, }, - {`{{< highlight java "style=friendly" >}} + { + `{{< highlight java "style=friendly" >}} void do(); {{< /highlight >}}`, `(?s)<div class="highlight"><pre style="background-color:#f0f0f0;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java">`, @@ -205,7 +206,6 @@ title: Shorty th.assertFileContentRegexp(filepath.Join("public", "simple", "index.html"), this.expected) } - } func TestShortcodeVimeo(t *testing.T) { diff --git a/hugolib/embedded_templates_test.go b/hugolib/embedded_templates_test.go index 39a905589..840b98232 100644 --- a/hugolib/embedded_templates_test.go +++ b/hugolib/embedded_templates_test.go @@ -76,5 +76,4 @@ title: My Site <meta property="og:image" content="https://example.org/siteimg1.jpg"/> <meta itemprop="image" content="https://example.org/siteimg1.jpg"/> `) - } diff --git a/hugolib/fileInfo.go b/hugolib/fileInfo.go index 4997142a1..fdfd34b16 100644 --- a/hugolib/fileInfo.go +++ b/hugolib/fileInfo.go @@ -63,7 +63,6 @@ func (fi *fileInfo) String() string { // TODO(bep) rename func newFileInfo(sp *source.SourceSpec, fi hugofs.FileMetaInfo) (*fileInfo, error) { - baseFi, err := sp.NewFileInfo(fi) if err != nil { return nil, err @@ -74,7 +73,6 @@ func newFileInfo(sp *source.SourceSpec, fi hugofs.FileMetaInfo) (*fileInfo, erro } return f, nil - } type bundleDirType int diff --git a/hugolib/filesystems/basefs.go b/hugolib/filesystems/basefs.go index ae3807360..e977633c8 100644 --- a/hugolib/filesystems/basefs.go +++ b/hugolib/filesystems/basefs.go @@ -16,6 +16,7 @@ package filesystems import ( + "fmt" "io" "os" "path" @@ -33,8 +34,6 @@ import ( "github.com/gohugoio/hugo/hugofs" - "fmt" - "github.com/gohugoio/hugo/hugolib/paths" "github.com/spf13/afero" ) @@ -80,7 +79,7 @@ func (fs *BaseFs) AllDirs() []hugofs.FileMetaInfo { fs.Content.Dirs, fs.Assets.Dirs, fs.Layouts.Dirs, - //fs.Resources.Dirs, + // fs.Resources.Dirs, fs.StaticDirs, } { dirs = append(dirs, dirSet...) @@ -160,7 +159,6 @@ func (s *SourceFilesystems) FileSystems() []*SourceFilesystem { s.Archetypes, // TODO(bep) static } - } // A SourceFilesystem holds the filesystem for a given source type in Hugo (data, @@ -192,7 +190,6 @@ func (s SourceFilesystems) ContentStaticAssetFs(lang string) afero.Fs { base := afero.NewCopyOnWriteFs(s.Assets.Fs, staticFs) return afero.NewCopyOnWriteFs(base, s.Content.Fs) - } // StaticFs returns the static filesystem for the given language. @@ -277,7 +274,6 @@ func (s SourceFilesystems) MakeStaticPathRelative(filename string) string { // MakePathRelative creates a relative path from the given filename. func (d *SourceFilesystem) MakePathRelative(filename string) (string, bool) { - for _, dir := range d.Dirs { meta := dir.(hugofs.FileMetaInfo).Meta() currentPath := meta.Filename() @@ -416,7 +412,6 @@ func (b *sourceFilesystemsBuilder) newSourceFilesystem(name string, fs afero.Fs, } func (b *sourceFilesystemsBuilder) Build() (*SourceFilesystems, error) { - if b.theBigFs == nil { theBigFs, err := b.createMainOverlayFs(b.p) @@ -435,7 +430,6 @@ func (b *sourceFilesystemsBuilder) Build() (*SourceFilesystems, error) { dirs := b.theBigFs.overlayDirs[componentID] return b.newSourceFilesystem(componentID, afero.NewBasePathFs(b.theBigFs.overlayMounts, componentID), dirs) - } b.theBigFs.finalizeDirs() @@ -491,11 +485,9 @@ func (b *sourceFilesystemsBuilder) Build() (*SourceFilesystems, error) { } return b.result, nil - } func (b *sourceFilesystemsBuilder) createMainOverlayFs(p *paths.Paths) (*filesystemsCollector, error) { - var staticFsMap map[string]afero.Fs if b.p.Cfg.GetBool("multihost") { staticFsMap = make(map[string]afero.Fs) @@ -536,7 +528,6 @@ func (b *sourceFilesystemsBuilder) createMainOverlayFs(p *paths.Paths) (*filesys err := b.createOverlayFs(collector, modsReversed) return collector, err - } func (b *sourceFilesystemsBuilder) isContentMount(mnt modules.Mount) bool { @@ -550,7 +541,6 @@ func (b *sourceFilesystemsBuilder) isStaticMount(mnt modules.Mount) bool { func (b *sourceFilesystemsBuilder) createModFs( collector *filesystemsCollector, md mountsDescriptor) error { - var ( fromTo []hugofs.RootMapping fromToContent []hugofs.RootMapping @@ -641,7 +631,6 @@ func (b *sourceFilesystemsBuilder) createModFs( sfs, found := collector.staticPerLanguage[lang] if found { collector.staticPerLanguage[lang] = afero.NewCopyOnWriteFs(sfs, bfs) - } else { collector.staticPerLanguage[lang] = bfs } @@ -672,7 +661,6 @@ func (b *sourceFilesystemsBuilder) createModFs( } return nil - } func printFs(fs afero.Fs, path string, w io.Writer) { @@ -719,7 +707,6 @@ func (c *filesystemsCollector) addDirs(rfs *hugofs.RootMappingFs) { for _, componentFolder := range files.ComponentFolders { c.addDir(rfs, componentFolder) } - } func (c *filesystemsCollector) addDir(rfs *hugofs.RootMappingFs, componentFolder string) { @@ -737,7 +724,6 @@ func (c *filesystemsCollector) finalizeDirs() { c.reverseFis(dirs) } }) - } func (c *filesystemsCollector) reverseFis(fis []hugofs.FileMetaInfo) { diff --git a/hugolib/filesystems/basefs_test.go b/hugolib/filesystems/basefs_test.go index 2d273ae88..139d0c20e 100644 --- a/hugolib/filesystems/basefs_test.go +++ b/hugolib/filesystems/basefs_test.go @@ -274,7 +274,6 @@ func TestRealDirs(t *testing.T) { c.Assert(realDirs[len(realDirs)-1], qt.Equals, filepath.Join(themesDir, "mytheme/assets/scss")) c.Assert(bfs.theBigFs, qt.Not(qt.IsNil)) - } func TestStaticFs(t *testing.T) { @@ -305,7 +304,6 @@ func TestStaticFs(t *testing.T) { sfs := bfs.StaticFs("en") checkFileContent(sfs, "f1.txt", c, "Hugo Rocks!") checkFileContent(sfs, "f2.txt", c, "Hugo Themes Still Rocks!") - } func TestStaticFsMultiHost(t *testing.T) { @@ -402,7 +400,6 @@ func TestMakePathRelative(t *testing.T) { c.Assert(makeRel(filepath.Join(workDir, "dist", "d1", "foo.txt")), qt.Equals, filepath.FromSlash("mydist/d1/foo.txt")) c.Assert(makeRel(filepath.Join(workDir, "static", "d2", "foo.txt")), qt.Equals, filepath.FromSlash("d2/foo.txt")) c.Assert(makeRel(filepath.Join(workDir, "dust", "d3", "foo.txt")), qt.Equals, filepath.FromSlash("foo/bar/d3/foo.txt")) - } func checkFileCount(fs afero.Fs, dirname string, c *qt.C, expected int) { @@ -412,7 +409,6 @@ func checkFileCount(fs afero.Fs, dirname string, c *qt.C, expected int) { } func checkFileContent(fs afero.Fs, filename string, c *qt.C, expected ...string) { - b, err := afero.ReadFile(fs, filename) c.Assert(err, qt.IsNil) diff --git a/hugolib/gitinfo.go b/hugolib/gitinfo.go index 6acc47d17..17717ed52 100644 --- a/hugolib/gitinfo.go +++ b/hugolib/gitinfo.go @@ -32,7 +32,6 @@ func (g *gitInfo) forPage(p page.Page) *gitmap.GitInfo { name = strings.TrimPrefix(name, "/") return g.repo.Files[name] - } func newGitInfo(cfg config.Provider) (*gitInfo, error) { diff --git a/hugolib/hugo_modules_test.go b/hugolib/hugo_modules_test.go index b2ab59ef0..f63da5a07 100644 --- a/hugolib/hugo_modules_test.go +++ b/hugolib/hugo_modules_test.go @@ -93,11 +93,9 @@ github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877/go.mod h1 `) return b, clean - } t.Run("Target in subfolder", func(t *testing.T) { - b, clean := newTestBuilder(t, "ignoreImports=true") defer clean() @@ -107,7 +105,6 @@ github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877/go.mod h1 }) t.Run("Ignore config", func(t *testing.T) { - b, clean := newTestBuilder(t, "ignoreConfig=true") defer clean() @@ -120,7 +117,6 @@ JS imported in module: | }) t.Run("Ignore imports", func(t *testing.T) { - b, clean := newTestBuilder(t, "ignoreImports=true") defer clean() @@ -133,7 +129,6 @@ JS imported in module: | }) t.Run("Create package.json", func(t *testing.T) { - b, clean := newTestBuilder(t, "") defer clean() @@ -197,7 +192,6 @@ JS imported in module: | }) t.Run("Create package.json, no default", func(t *testing.T) { - b, clean := newTestBuilder(t, "") defer clean() @@ -249,11 +243,9 @@ JS imported in module: | // https://github.com/gohugoio/hugo/issues/7690 b.AssertFileContent("package.hugo.json", origPackageJSON) - }) t.Run("Create package.json, no default, no package.json", func(t *testing.T) { - b, clean := newTestBuilder(t, "") defer clean() @@ -287,11 +279,8 @@ JS imported in module: | "name": "myhugosite", "version": "0.1.0" }` - }) - }) - } // TODO(bep) this fails when testmodBuilder is also building ... @@ -532,7 +521,6 @@ other="Theme C" "i18n theme: Theme C", "i18n theme2: Theme2 D", ) - } func TestModulesIgnoreConfig(t *testing.T) { @@ -560,7 +548,6 @@ a = "Should Be Ignored!" b.AssertFileContentFn("public/index.html", func(s string) bool { return !strings.Contains(s, "Ignored") }) - } func TestModulesDisabled(t *testing.T) { @@ -596,7 +583,6 @@ b = "B param" b.AssertFileContentFn("public/index.html", func(s string) bool { return strings.Contains(s, "A param") && !strings.Contains(s, "B param") }) - } func TestModulesIncompatible(t *testing.T) { @@ -650,7 +636,6 @@ min_version = 0.55.0 c := qt.New(t) c.Assert(logger.LogCounters().WarnCounter.Count(), qt.Equals, uint64(3)) - } func TestModulesSymlinks(t *testing.T) { @@ -740,7 +725,8 @@ weight = 2 bfs.Content.Fs, bfs.Data.Fs, bfs.Assets.Fs, - bfs.I18n.Fs} { + bfs.I18n.Fs, + } { if i != 0 { continue @@ -756,7 +742,6 @@ weight = 2 } _, err := fs.Stat(filepath.FromSlash(filename)) - if err != nil { if i > 0 && strings.HasSuffix(filename, "toml") && strings.Contains(err.Error(), "files not supported") { // OK @@ -803,7 +788,7 @@ title: "My Page" b.Build(BuildCfg{}) - //helpers.PrintFs(b.H.Fs.Source, "public", os.Stdout) + // helpers.PrintFs(b.H.Fs.Source, "public", os.Stdout) b.AssertFileContent("public/mypage/index.html", "Permalink: https://example.org/mypage/") } @@ -929,7 +914,6 @@ title: "Readme Edit" b.AssertFileContent("public/index.html", ` Readme Edit `) - } func TestMountsPaths(t *testing.T) { @@ -969,7 +953,6 @@ workingDir = %q clean: clean, workingDir: workingDir, } - } c.Run("Default", func(c *qt.C) { @@ -991,7 +974,6 @@ title: P1 b.Assert(filepath.ToSlash(f.PathFile()), qt.Equals, "content/blog/p1.md") b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(test.workingDir, "layouts", "_default", "single.html")), qt.Equals, filepath.FromSlash("_default/single.html")) - }) c.Run("Mounts", func(c *qt.C) { @@ -1047,9 +1029,7 @@ title: P1 b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(absShortcodesDir, "myshort.html")), qt.Equals, filepath.FromSlash("shortcodes/myshort.html")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(subContentDir, "p1.md")), qt.Equals, filepath.FromSlash("blog/sub/p1.md")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(test.workingDir, "README.md")), qt.Equals, filepath.FromSlash("_index.md")) - }) - } // https://github.com/gohugoio/hugo/issues/6299 @@ -1074,7 +1054,6 @@ func TestSiteWithGoModButNoModules(t *testing.T) { b.WithSourceFile("go.mod", "") b.Build(BuildCfg{}) - } // https://github.com/gohugoio/hugo/issues/6622 @@ -1128,5 +1107,4 @@ P1: {{ $p1.Title }}|{{ $p1.RelPermalink }}|Filename: {{ $p1.File.Filename }} b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "P1: Abs|/p1/", "Filename: "+contentFilename) - } diff --git a/hugolib/hugo_sites.go b/hugolib/hugo_sites.go index 25ae3dd19..a016cab99 100644 --- a/hugolib/hugo_sites.go +++ b/hugolib/hugo_sites.go @@ -295,13 +295,11 @@ func (h *HugoSites) GetContentPage(filename string) page.Page { // NewHugoSites creates a new collection of sites given the input sites, building // a language configuration based on those. func newHugoSites(cfg deps.DepsCfg, sites ...*Site) (*HugoSites, error) { - if cfg.Language != nil { return nil, errors.New("Cannot provide Language in Cfg when sites are provided") } langConfig, err := newMultiLingualFromSites(cfg.Cfg, sites...) - if err != nil { return nil, errors.Wrap(err, "failed to create language config") } @@ -437,7 +435,6 @@ func applyDeps(cfg deps.DepsCfg, sites ...*Site) error { s.outputFormatsConfig, s.mediaTypesConfig, ) - if err != nil { return err } @@ -535,10 +532,7 @@ func (s *Site) withSiteTemplates(withTemplates ...func(templ tpl.TemplateManager } func createSitesFromConfig(cfg deps.DepsCfg) ([]*Site, error) { - - var ( - sites []*Site - ) + var sites []*Site languages := getLanguages(cfg.Cfg) @@ -619,13 +613,11 @@ func (h *HugoSites) createSitesFromConfig(cfg config.Provider) error { depsCfg := deps.DepsCfg{Fs: h.Fs, Cfg: cfg} sites, err := createSitesFromConfig(depsCfg) - if err != nil { return err } langConfig, err := newMultiLingualFromSites(depsCfg.Cfg, sites...) - if err != nil { return err } @@ -707,7 +699,6 @@ func (cfg *BuildCfg) shouldRender(p *pageState) bool { } func (h *HugoSites) renderCrossSitesSitemap() error { - if !h.multilingual.enabled() || h.IsMultihost() { return nil } @@ -750,7 +741,6 @@ func (h *HugoSites) renderCrossSitesRobotsTXT() error { }, }, output.RobotsTxtFormat) - if err != nil { return err } @@ -779,11 +769,9 @@ func (h *HugoSites) removePageByFilename(filename string) { }) return nil }) - } func (h *HugoSites) createPageCollections() error { - allPages := newLazyPagesFactory(func() page.Pages { var pages page.Pages for _, s := range h.Sites { @@ -1083,7 +1071,6 @@ func (m *contentChangeMap) resolveAndRemove(filename string) (string, bundleDirT } return dir, bundleNot - } func (m *contentChangeMap) addSymbolicLinkMapping(fim hugofs.FileMetaInfo) { diff --git a/hugolib/hugo_sites_build.go b/hugolib/hugo_sites_build.go index bd5c2b661..c1a4ab190 100644 --- a/hugolib/hugo_sites_build.go +++ b/hugolib/hugo_sites_build.go @@ -44,7 +44,6 @@ import ( // Build builds all sites. If filesystem events are provided, // this is considered to be a potential partial rebuild. func (h *HugoSites) Build(config BuildCfg, events ...fsnotify.Event) error { - if h.running { // Make sure we don't trigger rebuilds in parallel. h.runningMu.Lock() @@ -70,7 +69,6 @@ func (h *HugoSites) Build(config BuildCfg, events ...fsnotify.Event) error { to <- h.pickOneAndLogTheRest(errors) close(to) - }(errCollector, errs) if h.Metrics != nil { @@ -186,7 +184,6 @@ func (h *HugoSites) Build(config BuildCfg, events ...fsnotify.Event) error { } return nil - } // Build lifecycle methods below. @@ -242,11 +239,9 @@ func (h *HugoSites) process(config *BuildCfg, init func(config *BuildCfg) error, } return firstSite.process(*config) - } func (h *HugoSites) assemble(bcfg *BuildCfg) error { - if len(h.Sites) > 1 { // The first is initialized during process; initialize the rest for _, site := range h.Sites[1:] { @@ -269,7 +264,6 @@ func (h *HugoSites) assemble(bcfg *BuildCfg) error { } return nil - } func (h *HugoSites) render(config *BuildCfg) error { @@ -327,7 +321,6 @@ func (h *HugoSites) render(config *BuildCfg) error { } } - } if !config.SkipRender { @@ -366,7 +359,6 @@ func (h *HugoSites) postProcess() error { b, err := json.MarshalIndent(jsConfig, "", " ") if err != nil { h.Log.Warnf("Failed to create jsconfig.json: %s", err) - } else { filename := filepath.Join(assetsDir, "jsconfig.json") if h.running { @@ -400,7 +392,6 @@ func (h *HugoSites) postProcess() error { g, _ := workers.Start(context.Background()) handleFile := func(filename string) error { - content, err := afero.ReadFile(h.BaseFs.PublishFs, filename) if err != nil { return err @@ -443,7 +434,6 @@ func (h *HugoSites) postProcess() error { } return nil - } _ = afero.Walk(h.BaseFs.PublishFs, "", func(path string, info os.FileInfo, err error) error { @@ -468,7 +458,6 @@ func (h *HugoSites) postProcess() error { } return g.Wait() - } type publishStats struct { @@ -512,5 +501,4 @@ func (h *HugoSites) writeBuildStats() error { } return nil - } diff --git a/hugolib/hugo_sites_build_errors_test.go b/hugolib/hugo_sites_build_errors_test.go index d90a8b364..997aae564 100644 --- a/hugolib/hugo_sites_build_errors_test.go +++ b/hugolib/hugo_sites_build_errors_test.go @@ -34,11 +34,9 @@ func (t testSiteBuildErrorAsserter) assertErrorMessage(e1, e2 string) { // The error message will contain filenames with OS slashes. Normalize before compare. e1, e2 = filepath.ToSlash(e1), filepath.ToSlash(e2) t.c.Assert(e2, qt.Contains, e1) - } func TestSiteBuildErrors(t *testing.T) { - const ( yamlcontent = "yamlcontent" tomlcontent = "tomlcontent" @@ -92,7 +90,6 @@ func TestSiteBuildErrors(t *testing.T) { a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 1) a.c.Assert(fe.ChromaLexer, qt.Equals, "go-html-template") a.assertErrorMessage("\"layouts/foo/single.html:5:1\": parse failed: template: foo/single.html:5: unexpected \"}\" in operand", fe.Error()) - }, }, { @@ -107,7 +104,6 @@ func TestSiteBuildErrors(t *testing.T) { a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 14) a.c.Assert(fe.ChromaLexer, qt.Equals, "go-html-template") a.assertErrorMessage("\"layouts/_default/single.html:5:14\": execute of template failed", fe.Error()) - }, }, { @@ -122,7 +118,6 @@ func TestSiteBuildErrors(t *testing.T) { a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 14) a.c.Assert(fe.ChromaLexer, qt.Equals, "go-html-template") a.assertErrorMessage("\"layouts/_default/single.html:5:14\": execute of template failed", fe.Error()) - }, }, { @@ -184,7 +179,6 @@ func TestSiteBuildErrors(t *testing.T) { fe := a.getFileError(err) a.c.Assert(fe.Position().LineNumber, qt.Equals, 6) a.c.Assert(fe.ErrorContext.ChromaLexer, qt.Equals, "toml") - }, }, { @@ -198,7 +192,6 @@ func TestSiteBuildErrors(t *testing.T) { a.c.Assert(fe.Position().LineNumber, qt.Equals, 3) a.c.Assert(fe.ErrorContext.ChromaLexer, qt.Equals, "json") - }, }, { @@ -235,7 +228,6 @@ func TestSiteBuildErrors(t *testing.T) { return content } return test.fileFixer(content) - } b.WithTemplatesAdded("layouts/shortcodes/sc.html", f(shortcode, `SHORTCODE L1 @@ -348,9 +340,7 @@ title: "A page" --- {{< c >}}`) - } b.CreateSites().BuildFail(BuildCfg{}) - } diff --git a/hugolib/hugo_sites_build_test.go b/hugolib/hugo_sites_build_test.go index 8d0872bd5..4d6a8697c 100644 --- a/hugolib/hugo_sites_build_test.go +++ b/hugolib/hugo_sites_build_test.go @@ -2,10 +2,9 @@ package hugolib import ( "fmt" + "path/filepath" "strings" "testing" - - "path/filepath" "time" qt "github.com/frankban/quicktest" @@ -199,7 +198,6 @@ p1 = "p1en" } func TestMultiSitesBuild(t *testing.T) { - for _, config := range []struct { content string suffix string @@ -208,7 +206,6 @@ func TestMultiSitesBuild(t *testing.T) { {multiSiteYAMLConfigTemplate, "yml"}, {multiSiteJSONConfigTemplate, "json"}, } { - t.Run(config.suffix, func(t *testing.T) { t.Parallel() doTestMultiSitesBuild(t, config.content, config.suffix) @@ -245,7 +242,7 @@ func doTestMultiSitesBuild(t *testing.T, configTemplate, configSuffix string) { c.Assert(enSite.language.Lang, qt.Equals, "en") - //dumpPages(enSite.RegularPages()...) + // dumpPages(enSite.RegularPages()...) c.Assert(len(enSite.RegularPages()), qt.Equals, 5) c.Assert(len(enSite.AllPages()), qt.Equals, 32) @@ -412,7 +409,6 @@ func doTestMultiSitesBuild(t *testing.T, configTemplate, configSuffix string) { c.Assert(logoEn, qt.Not(qt.IsNil)) b.AssertFileContent("public/en/bundles/b1/index.html", "Resources: image/png: /blog/en/bundles/b1/logo.png") b.AssertFileContent("public/en/bundles/b1/logo.png", "PNG Data") - } func TestMultiSitesRebuild(t *testing.T) { @@ -470,7 +466,6 @@ func TestMultiSitesRebuild(t *testing.T) { []fsnotify.Event{{Name: filepath.FromSlash("content/sect/doc2.en.md"), Op: fsnotify.Remove}}, func(t *testing.T) { c.Assert(len(enSite.RegularPages()), qt.Equals, 4, qt.Commentf("1 en removed")) - }, }, { @@ -508,7 +503,6 @@ func TestMultiSitesRebuild(t *testing.T) { c.Assert(len(enSite.RegularPages()), qt.Equals, 6) doc1 := readDestination(t, fs, "public/en/sect/doc1-slug/index.html") c.Assert(strings.Contains(doc1, "CHANGED"), qt.Equals, true) - }, }, // Rename a file @@ -527,7 +521,8 @@ func TestMultiSitesRebuild(t *testing.T) { c.Assert(enSite.RegularPages()[1].Title(), qt.Equals, "new_en_1") rendered := readDestination(t, fs, "public/en/new1renamed/index.html") c.Assert(rendered, qt.Contains, "new_en_1") - }}, + }, + }, { // Change a template func(t *testing.T) { @@ -567,7 +562,6 @@ func TestMultiSitesRebuild(t *testing.T) { c.Assert(homeEn, qt.Not(qt.IsNil)) c.Assert(len(homeEn.Translations()), qt.Equals, 3) c.Assert(homeEn.Translations()[0].Language().Lang, qt.Equals, "fr") - }, }, // Change a shortcode @@ -593,14 +587,12 @@ func TestMultiSitesRebuild(t *testing.T) { } err := b.H.Build(BuildCfg{}, this.events...) - if err != nil { t.Fatalf("[%d] Failed to rebuild sites: %s", i, err) } this.assertFunc(t) } - } // https://github.com/gohugoio/hugo/issues/4706 @@ -762,7 +754,6 @@ Title: My categories `) for _, lang := range []string{"en", "nn"} { - b.WithContent(lang+"/mysection/page.md", ` --- Title: My Page @@ -770,7 +761,6 @@ categories: ["mycat"] --- `) - } b.Build(BuildCfg{}) @@ -781,7 +771,6 @@ categories: ["mycat"] "/categories", "/categories/mycat", } { - t.Run(path, func(t *testing.T) { c := qt.New(t) @@ -802,7 +791,6 @@ categories: ["mycat"] c.Assert(len(m1), qt.Equals, 1) c.Assert(len(m2), qt.Equals, 1) }) - } } diff --git a/hugolib/hugo_sites_multihost_test.go b/hugolib/hugo_sites_multihost_test.go index 4fe496042..b008fbdef 100644 --- a/hugolib/hugo_sites_multihost_test.go +++ b/hugolib/hugo_sites_multihost_test.go @@ -13,7 +13,7 @@ func TestMultihosts(t *testing.T) { c := qt.New(t) - var configTemplate = ` + configTemplate := ` paginate = 1 disablePathToLower = true defaultContentLanguage = "fr" @@ -116,5 +116,4 @@ languageName = "Nynorsk" c.Assert(len(bundleFr.Resources()), qt.Equals, 1) b.AssertFileContent("public/fr/bundles/b1/logo.png", "PNG Data") b.AssertFileContent("public/fr/bundles/b1/index.html", " image/png: /bundles/b1/logo.png") - } diff --git a/hugolib/hugo_sites_rebuild_test.go b/hugolib/hugo_sites_rebuild_test.go index 4c4741385..d312d2199 100644 --- a/hugolib/hugo_sites_rebuild_test.go +++ b/hugolib/hugo_sites_rebuild_test.go @@ -20,7 +20,6 @@ import ( ) func TestSitesRebuild(t *testing.T) { - configFile := ` baseURL = "https://example.com" title = "Rebuild this" @@ -142,7 +141,6 @@ Data Inline: Rocks! b.AssertFileContent("public/index.html", ` Data: Rules! Data Inline: Rules!`) - }) // https://github.com/gohugoio/hugo/issues/6968 @@ -165,7 +163,6 @@ Data Inline: Rules!`) b.Build(BuildCfg{testCounters: counters}) b.Assert(int(counters.contentRenderCounter), qt.Equals, 0) - }) t.Run("Page.Render, edit baseof", func(t *testing.T) { @@ -190,7 +187,6 @@ prender: {{ $p.Title }}|{{ $p.Content }} b.AssertFileContent("public/index.html", ` Render /prender/: Baseof Edited:Single Main: Page 1|Mypartial1: Mypartial1:END `) - }) t.Run("Page.Render, edit partial in baseof", func(t *testing.T) { @@ -215,7 +211,6 @@ prender: {{ $p.Title }}|{{ $p.Content }} b.AssertFileContent("public/index.html", ` Render /prender/: Baseof:Single Main: Page 1|Mypartial1: Mypartial1|Mypartial3: Mypartial3 Edited:END `) - }) t.Run("Edit RSS shortcode", func(t *testing.T) { @@ -255,9 +250,7 @@ Output Shortcode AMP b.AssertFileContent("public/amp/output/index.html", ` Output Shortcode AMP Edited `) - }) - } // Issues #7623 #7625 @@ -320,5 +313,4 @@ P6 content P5 changed content P6 changed content `) - } diff --git a/hugolib/hugo_smoke_test.go b/hugolib/hugo_smoke_test.go index 5aa508290..798504f0d 100644 --- a/hugolib/hugo_smoke_test.go +++ b/hugolib/hugo_smoke_test.go @@ -122,7 +122,7 @@ Footnotes: ` - var pageContentAutoSummary = strings.Replace(pageContentAndSummaryDivider, "<!--more-->", "", 1) + pageContentAutoSummary := strings.Replace(pageContentAndSummaryDivider, "<!--more-->", "", 1) b := newTestSitesBuilder(t).WithConfigFile("toml", configFile) b.WithTemplatesAdded("shortcodes/markdown-shortcode.html", ` @@ -282,12 +282,10 @@ Some **Markdown** in JSON shortcode. // Markdown vs shortcodes // Check that all footnotes are grouped (even those from inside the shortcode) b.AssertFileContentRe("public/blog/markyshort/index.html", `Footnotes:.*<ol>.*Fn 1.*Fn 2.*Fn 3.*</ol>`) - } // https://github.com/golang/go/issues/30286 func TestDataRace(t *testing.T) { - const page = ` --- title: "The Page" diff --git a/hugolib/image_test.go b/hugolib/image_test.go index 84d43f5e9..9f0967414 100644 --- a/hugolib/image_test.go +++ b/hugolib/image_test.go @@ -38,7 +38,6 @@ func TestImageOps(t *testing.T) { defer clean() newBuilder := func(timeout interface{}) *sitesBuilder { - v := viper.New() v.Set("workingDir", workDir) v.Set("baseURL", "https://example.org") @@ -169,11 +168,9 @@ IMG SHORTCODE: /images/sunset_hu59e56ffff1bc1d8d122b1403d34e039f_90587_129x239_r b.Build(BuildCfg{}) assertImages() - } func TestImageResizeMultilingual(t *testing.T) { - b := newTestSitesBuilder(t).WithConfigFile("toml", ` baseURL="https://example.org" defaultContentLanguage = "en" @@ -247,5 +244,4 @@ SUNSET2: {{ $resized2.RelPermalink }}/{{ $resized2.Width }}/Lat: {{ $resized2.Ex // TODO(bep) add this as a default assertion after Build()? b.AssertNoDuplicateWrites() - } diff --git a/hugolib/js_test.go b/hugolib/js_test.go index b4f1d2157..fbbd335b3 100644 --- a/hugolib/js_test.go +++ b/hugolib/js_test.go @@ -136,7 +136,6 @@ if (hasSpace.test(string)) var React = __toModule(require("react")); function greeter(person) { `) - } func TestJSBuild(t *testing.T) { @@ -208,5 +207,4 @@ Hello3 from mod2. Date from date-fns: ${today} Hello from lib in the main project Hello5 from mod2. var myparam = "Hugo Rocks!";`) - } diff --git a/hugolib/language_content_dir_test.go b/hugolib/language_content_dir_test.go index 0d1033c1f..117fdfb14 100644 --- a/hugolib/language_content_dir_test.go +++ b/hugolib/language_content_dir_test.go @@ -102,7 +102,7 @@ Content. var contentFiles []string section := "sect" - var contentRoot = func(lang string) string { + contentRoot := func(lang string) string { switch lang { case "nn": return "content/norsk" @@ -111,10 +111,9 @@ Content. default: return "content/main" } - } - var contentSectionRoot = func(lang string) string { + contentSectionRoot := func(lang string) string { return contentRoot(lang) + "/" + section } @@ -215,7 +214,7 @@ Content. err := b.BuildE(BuildCfg{}) - //dumpPages(b.H.Sites[1].RegularPages()...) + // dumpPages(b.H.Sites[1].RegularPages()...) c.Assert(err, qt.IsNil) @@ -228,7 +227,7 @@ Content. b.AssertFileContent("/my/project/public/en/mystatic/file1.yaml", "en") b.AssertFileContent("/my/project/public/nn/mystatic/file1.yaml", "nn") - //dumpPages(nnSite.RegularPages()...) + // dumpPages(nnSite.RegularPages()...) c.Assert(len(nnSite.RegularPages()), qt.Equals, 12) c.Assert(len(enSite.RegularPages()), qt.Equals, 13) @@ -317,7 +316,6 @@ Content. c.Assert(len(nnSect.Pages()), qt.Equals, 12) nnHome, _ := nnSite.Info.Home() c.Assert(nnHome.RelPermalink(), qt.Equals, "/nn/") - } // https://github.com/gohugoio/hugo/issues/6463 @@ -404,5 +402,4 @@ Page: /fr/event/page1/|ev-fr1 Page: /fr/event/page2/|ev-fr2 Page: /fr/other/page1/|other-fr1 Page: /fr/other/page2/|other-fr2`) - } diff --git a/hugolib/language_test.go b/hugolib/language_test.go index 9c3e434c2..16dcbcb03 100644 --- a/hugolib/language_test.go +++ b/hugolib/language_test.go @@ -24,7 +24,6 @@ import ( ) func TestI18n(t *testing.T) { - c := qt.New(t) //https://github.com/gohugoio/hugo/issues/7804 diff --git a/hugolib/menu_test.go b/hugolib/menu_test.go index cfb4b954b..8717fa7db 100644 --- a/hugolib/menu_test.go +++ b/hugolib/menu_test.go @@ -14,9 +14,8 @@ package hugolib import ( - "testing" - "fmt" + "testing" qt "github.com/frankban/quicktest" ) @@ -104,11 +103,9 @@ Menu Main: {{ partial "menu.html" (dict "page" . "menu" "main") }}`, "/sect1/|Section One|Section One|100|-|-|"+ "/sect2/|Sect2s|Sect2s|0|-|HasMenuCurrent|"+ "/sect3/|Sect3s|Sect3s|0|-|-|") - } func TestMenuFrontMatter(t *testing.T) { - b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithTemplatesAdded("index.html", ` @@ -155,12 +152,10 @@ menu: "Main|P1: /blog/page1/", "Other|P2: /blog/page2/", ) - } // https://github.com/gohugoio/hugo/issues/5849 func TestMenuPageMultipleOutputFormats(t *testing.T) { - config := ` baseURL = "https://example.com" @@ -219,7 +214,6 @@ menu: "main" // https://github.com/gohugoio/hugo/issues/5989 func TestMenuPageSortByDate(t *testing.T) { - b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithContent("blog/a.md", ` @@ -269,7 +263,6 @@ menu: } func TestMenuParams(t *testing.T) { - b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithTemplatesAdded("index.html", ` @@ -315,5 +308,4 @@ menu: "Main|P1: /blog/page1/|map[]", "Main|P2: /blog/page2/|map[]", ) - } diff --git a/hugolib/multilingual.go b/hugolib/multilingual.go index 9b34c75e6..baebc9e0f 100644 --- a/hugolib/multilingual.go +++ b/hugolib/multilingual.go @@ -14,9 +14,8 @@ package hugolib import ( - "sync" - "errors" + "sync" "github.com/gohugoio/hugo/langs" @@ -69,7 +68,6 @@ func newMultiLingualFromSites(cfg config.Provider, sites ...*Site) (*Multilingua } return &Multilingual{Languages: languages, DefaultLang: langs.NewLanguage(defaultLang, cfg)}, nil - } func (ml *Multilingual) enabled() bool { diff --git a/hugolib/openapi_test.go b/hugolib/openapi_test.go index 82f080311..3f1bc400d 100644 --- a/hugolib/openapi_test.go +++ b/hugolib/openapi_test.go @@ -65,5 +65,4 @@ API: {{ $api.Info.Title | safeHTML }} b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `API: Hugo API`) - } diff --git a/hugolib/page.go b/hugolib/page.go index fac3f3492..47aeb6e9a 100644 --- a/hugolib/page.go +++ b/hugolib/page.go @@ -243,7 +243,6 @@ func (p *pageState) RegularPages() page.Pages { } p.regularPages = pages - }) return p.regularPages @@ -358,11 +357,9 @@ func (p *pageState) TranslationKey() string { } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } - }) return p.translationKey - } // AllTranslations returns all translations, including the current Page. @@ -469,7 +466,6 @@ func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { }) return p.layoutDescriptor - } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { @@ -500,7 +496,6 @@ func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { } return nil - } // Must be run after the site section tree etc. is built and ready. @@ -546,7 +541,6 @@ func (p *pageState) renderResources() (err error) { for _, i := range toBeDeleted { p.deleteResource(i) } - }) return @@ -681,7 +675,6 @@ func (p *pageState) Render(layout ...string) (template.HTML, error) { 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 @@ -714,7 +707,6 @@ func (p *pageState) getContentConverter() converter.Converter { markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) - }) if err != nil { @@ -724,7 +716,6 @@ func (p *pageState) getContentConverter() converter.Converter { } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { - s := p.shortcodeState rn := &pageContentMap{ @@ -893,7 +884,6 @@ func (p *pageState) parseError(err error, input []byte, offset int) error { } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) - } func (p *pageState) pathOrTitle() string { @@ -955,7 +945,6 @@ func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { 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 { diff --git a/hugolib/page__content.go b/hugolib/page__content.go index 91f26dc18..c08ac67af 100644 --- a/hugolib/page__content.go +++ b/hugolib/page__content.go @@ -65,7 +65,6 @@ func (p pageContent) contentToRender(renderedShortcodes map[string]string) []byt // Insert the placeholder so we can insert the content after // markdown processing. c = append(c, []byte(v.placeholder)...) - } default: panic(fmt.Sprintf("unknown item type %T", it)) diff --git a/hugolib/page__data.go b/hugolib/page__data.go index 9fc97f8f6..7ab668503 100644 --- a/hugolib/page__data.go +++ b/hugolib/page__data.go @@ -60,7 +60,6 @@ func (p *pageData) Data() interface{} { // Assign the function to the map to make sure it is lazily initialized p.data["pages"] = p.Pages - }) return p.data diff --git a/hugolib/page__menus.go b/hugolib/page__menus.go index 7b0ef0e43..e64ffa2c9 100644 --- a/hugolib/page__menus.go +++ b/hugolib/page__menus.go @@ -51,7 +51,6 @@ func (p *pageMenus) Menus() navigation.PageMenus { func (p *pageMenus) menus() navigation.PageMenus { p.init() return p.pm - } func (p *pageMenus) init() { @@ -68,7 +67,5 @@ func (p *pageMenus) init() { if err != nil { p.p.s.Log.Errorln(p.p.wrapError(err)) } - }) - } diff --git a/hugolib/page__meta.go b/hugolib/page__meta.go index d23718315..b14938655 100644 --- a/hugolib/page__meta.go +++ b/hugolib/page__meta.go @@ -238,7 +238,6 @@ func (p *pageMeta) Path() string { // RelatedKeywords implements the related.Document interface needed for fast page searches. func (p *pageMeta) RelatedKeywords(cfg related.IndexConfig) ([]related.Keyword, error) { - v, err := p.Param(cfg.Name) if err != nil { return nil, err @@ -269,7 +268,6 @@ func (p *pageMeta) Section() string { } panic("invalid page state") - } func (p *pageMeta) SectionsEntries() []string { @@ -368,9 +366,8 @@ func (pm *pageMeta) setMetadata(parentBucket *pagesMapBucket, p *pageState, fron } } else { p.bucket.cascade = map[page.PageMatcher]maps.Params{ - page.PageMatcher{}: maps.ToStringMap(cv), + {}: maps.ToStringMap(cv), } - } } } @@ -486,7 +483,6 @@ func (pm *pageMeta) setMetadata(parentBucket *pagesMapBucket, p *pageState, fron // this may get its language path added twice. // TODO(bep) eventually remove this. p.s.Log.Warnf(`Front matter in %q with the url %q with no leading / has what looks like the language prefix added. In Hugo 0.55 we added support for page relative URLs in front matter, no language prefix needed. Check the URL and consider to either add a leading / or remove the language prefix.`, p.pathOrTitle(), url) - } } pm.urlPaths.URL = url @@ -661,7 +657,6 @@ func (p *pageMeta) noListAlways() bool { } func (p *pageMeta) getListFilter(local bool) contentTreeNodeCallback { - return newContentTreeFilter(func(n *contentNode) bool { if n == nil { return true @@ -763,7 +758,6 @@ func (p *pageMeta) applyDefaultValues(n *contentNode) error { } return nil - } func (p *pageMeta) newContentConverter(ps *pageState, markup string, renderingConfigOverrides map[string]interface{}) (converter.Converter, error) { @@ -791,7 +785,6 @@ func (p *pageMeta) newContentConverter(ps *pageState, markup string, renderingCo ConfigOverrides: renderingConfigOverrides, }, ) - if err != nil { return converter.NopConverter, err } diff --git a/hugolib/page__new.go b/hugolib/page__new.go index 9ec089f27..b37631477 100644 --- a/hugolib/page__new.go +++ b/hugolib/page__new.go @@ -90,7 +90,6 @@ func newPageBase(metaProvider *pageMeta) (*pageState, error) { ps.AlternativeOutputFormatsProvider = ps return ps, nil - } func newPageBucket(p *pageState) *pagesMapBucket { @@ -102,7 +101,6 @@ func newPageFromMeta( parentBucket *pagesMapBucket, meta map[string]interface{}, metaProvider *pageMeta) (*pageState, error) { - if metaProvider.f == nil { metaProvider.f = page.NewZeroFile(metaProvider.s.DistinctWarningLog) } @@ -170,11 +168,9 @@ func newPageFromMeta( } return nil, nil - }) return ps, err - } // Used by the legacy 404, sitemap and robots.txt rendering @@ -182,7 +178,6 @@ func newPageStandalone(m *pageMeta, f output.Format) (*pageState, error) { m.configuredOutputFormats = output.Formats{f} m.standalone = true p, err := newPageFromMeta(nil, nil, nil, m) - if err != nil { return nil, err } @@ -192,7 +187,6 @@ func newPageStandalone(m *pageMeta, f output.Format) (*pageState, error) { } return p, nil - } type pageDeprecatedWarning struct { @@ -205,6 +199,7 @@ func (p *pageDeprecatedWarning) LanguagePrefix() string { return p.p.s.Info.Lang func (p *pageDeprecatedWarning) GetParam(key string) interface{} { return p.p.m.params[strings.ToLower(key)] } + func (p *pageDeprecatedWarning) RSSLink() template.URL { f := p.p.OutputFormats().Get("RSS") if f == nil { @@ -212,6 +207,7 @@ func (p *pageDeprecatedWarning) RSSLink() template.URL { } return template.URL(f.Permalink()) } + func (p *pageDeprecatedWarning) URL() string { if p.p.IsPage() && p.p.m.urlPaths.URL != "" { // This is the url set in front matter @@ -219,5 +215,4 @@ func (p *pageDeprecatedWarning) URL() string { } // Fall back to the relative permalink. return p.p.RelPermalink() - } diff --git a/hugolib/page__output.go b/hugolib/page__output.go index 1792e8d6a..a3235db49 100644 --- a/hugolib/page__output.go +++ b/hugolib/page__output.go @@ -25,7 +25,6 @@ func newPageOutput( pp pagePaths, f output.Format, render bool) *pageOutput { - var targetPathsProvider targetPathsHolder var linksProvider resource.ResourceLinksProvider @@ -65,7 +64,6 @@ func newPageOutput( } return po - } // We create a pageOutput for every output format combination, even if this @@ -118,7 +116,6 @@ func (o *pageOutput) initRenderHooks() error { }) return initErr - } func (p *pageOutput) initContentProvider(cp *pageContentOutput) { @@ -134,5 +131,4 @@ func (p *pageOutput) enablePlaceholders() { if p.cp != nil { p.cp.enablePlaceholders() } - } diff --git a/hugolib/page__paginator.go b/hugolib/page__paginator.go index 5948735d1..a5a3f07a6 100644 --- a/hugolib/page__paginator.go +++ b/hugolib/page__paginator.go @@ -59,7 +59,6 @@ func (p *pagePaginator) Paginate(seq interface{}, options ...interface{}) (*page } p.current = paginator.Pagers()[0] - }) if initErr != nil { @@ -102,7 +101,6 @@ func (p *pagePaginator) Paginator(options ...interface{}) (*page.Pager, error) { } p.current = paginator.Pagers()[0] - }) if initErr != nil { diff --git a/hugolib/page__paths.go b/hugolib/page__paths.go index d41b7c2bc..947cdde9d 100644 --- a/hugolib/page__paths.go +++ b/hugolib/page__paths.go @@ -26,7 +26,6 @@ func newPagePaths( s *Site, p page.Page, pm *pageMeta) (pagePaths, error) { - targetPathDescriptor, err := createTargetPathDescriptor(s, p, pm) if err != nil { return pagePaths{}, err @@ -71,7 +70,8 @@ func newPagePaths( targets[f.Name] = targetPathsHolder{ paths: paths, - OutputFormat: pageOutputFormats[permalinksIndex]} + OutputFormat: pageOutputFormats[permalinksIndex], + } } @@ -86,7 +86,6 @@ func newPagePaths( targetPaths: targets, targetPathDescriptor: targetPathDescriptor, }, nil - } type pagePaths struct { @@ -163,5 +162,4 @@ func createTargetPathDescriptor(s *Site, p page.Page, pm *pageMeta) (page.Target } return desc, nil - } diff --git a/hugolib/page__per_output.go b/hugolib/page__per_output.go index aceeaeb36..dfc82c062 100644 --- a/hugolib/page__per_output.go +++ b/hugolib/page__per_output.go @@ -65,7 +65,6 @@ var ( var pageContentOutputDependenciesID = identity.KeyValueIdentity{Key: "pageOutput", Value: "dependencies"} func newPageContentOutput(p *pageState, po *pageOutput) (*pageContentOutput, error) { - parent := p.init var dependencyTracker identity.Manager @@ -195,7 +194,6 @@ func newPageContentOutput(p *pageState, po *pageOutput) (*pageContentOutput, err cp.content = helpers.BytesToHTML(cp.workContent) return nil - } // Recursive loops can only happen in content files with template code (shortcodes etc.) @@ -225,7 +223,6 @@ func newPageContentOutput(p *pageState, po *pageOutput) (*pageContentOutput, err }) return cp, nil - } type renderHooks struct { @@ -370,7 +367,6 @@ func (p *pageContentOutput) setAutoSummary() error { p.truncated = truncated return nil - } func (cp *pageContentOutput) renderContent(content []byte, renderTOC bool) (converter.Result, error) { @@ -379,7 +375,6 @@ func (cp *pageContentOutput) renderContent(content []byte, renderTOC bool) (conv } func (cp *pageContentOutput) renderContentWithConverter(c converter.Converter, content []byte, renderTOC bool) (converter.Result, error) { - r, err := c.Convert( converter.RenderContext{ Src: content, @@ -396,7 +391,6 @@ func (cp *pageContentOutput) renderContentWithConverter(c converter.Converter, c } return r, err - } func (p *pageContentOutput) setWordCounts(isCJKLanguage bool) { @@ -467,7 +461,6 @@ func executeToString(h tpl.TemplateHandler, templ tpl.Template, data interface{} return "", err } return b.String(), nil - } func splitUserDefinedSummaryAndContent(markup string, c []byte) (summary []byte, content []byte, err error) { @@ -487,7 +480,6 @@ func splitUserDefinedSummaryAndContent(markup string, c []byte) (summary []byte, switch markup { case "asciidocext": startTag = "div" - } // Walk back and forward to the surrounding tags. diff --git a/hugolib/page__position.go b/hugolib/page__position.go index 458b3e423..a087872cc 100644 --- a/hugolib/page__position.go +++ b/hugolib/page__position.go @@ -24,7 +24,6 @@ func newPagePosition(n *nextPrev) pagePosition { func newPagePositionInSection(n *nextPrev) pagePositionInSection { return pagePositionInSection{nextPrev: n} - } type nextPrev struct { diff --git a/hugolib/page__ref.go b/hugolib/page__ref.go index 41bd527db..f2b819c57 100644 --- a/hugolib/page__ref.go +++ b/hugolib/page__ref.go @@ -89,7 +89,6 @@ func (p pageRef) ref(argsm map[string]interface{}, source interface{}) (string, } return s.refLink(args.Path, source, false, args.OutputFormat) - } func (p pageRef) relRef(argsm map[string]interface{}, source interface{}) (string, error) { @@ -107,7 +106,6 @@ func (p pageRef) relRef(argsm map[string]interface{}, source interface{}) (strin } return s.refLink(args.Path, source, true, args.OutputFormat) - } type refArgs struct { diff --git a/hugolib/page__tree.go b/hugolib/page__tree.go index a617ad384..e4f3c6b51 100644 --- a/hugolib/page__tree.go +++ b/hugolib/page__tree.go @@ -59,7 +59,6 @@ func (pt pageTree) IsAncestor(other interface{}) (bool, error) { } return strings.HasPrefix(ref2.key, ref1.key+cmBranchSeparator), nil - } func (pt pageTree) CurrentSection() page.Page { @@ -106,7 +105,6 @@ func (pt pageTree) IsDescendant(other interface{}) (bool, error) { } return strings.HasPrefix(ref1.key, ref2.key+cmBranchSeparator), nil - } func (pt pageTree) FirstSection() page.Page { @@ -151,7 +149,6 @@ func (pt pageTree) InSection(other interface{}) (bool, error) { s2, _ := ref2.getCurrentSection() return s1 == s2, nil - } func (pt pageTree) Page() page.Page { diff --git a/hugolib/page_kinds.go b/hugolib/page_kinds.go index 683d12c1b..b63da1d13 100644 --- a/hugolib/page_kinds.go +++ b/hugolib/page_kinds.go @@ -19,11 +19,8 @@ import ( "github.com/gohugoio/hugo/resources/page" ) -var ( - - // This is all the kinds we can expect to find in .Site.Pages. - allKindsInPages = []string{page.KindPage, page.KindHome, page.KindSection, page.KindTerm, page.KindTaxonomy} -) +// This is all the kinds we can expect to find in .Site.Pages. +var allKindsInPages = []string{page.KindPage, page.KindHome, page.KindSection, page.KindTerm, page.KindTaxonomy} const ( diff --git a/hugolib/page_permalink_test.go b/hugolib/page_permalink_test.go index 9081ea898..0939cc1ff 100644 --- a/hugolib/page_permalink_test.go +++ b/hugolib/page_permalink_test.go @@ -104,11 +104,9 @@ Content } }) } - } func TestRelativeURLInFrontMatter(t *testing.T) { - config := ` baseURL = "https://example.com" defaultContentLanguage = "en" @@ -148,5 +146,4 @@ Some content. b.AssertFileContent("public/myblog/p1/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p1/|Permalink: https://example.com/myblog/p1/|") b.AssertFileContent("public/myblog/p2/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p2/|Permalink: https://example.com/myblog/p2/|") b.AssertFileContent("public/myblog/p3/index.html", "Single: A page|Hello|en|RelPermalink: /myblog/p3/|Permalink: https://example.com/myblog/p3/|") - } diff --git a/hugolib/page_test.go b/hugolib/page_test.go index 3a30216ed..b21fd1d2d 100644 --- a/hugolib/page_test.go +++ b/hugolib/page_test.go @@ -17,6 +17,10 @@ import ( "fmt" "html/template" "os" + "path/filepath" + "strings" + "testing" + "time" "github.com/gohugoio/hugo/markup/rst" @@ -26,11 +30,6 @@ import ( "github.com/gohugoio/hugo/common/loggers" - "path/filepath" - "strings" - "testing" - "time" - "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/resources/page" @@ -370,7 +369,6 @@ func normalizeExpected(ext, str string) string { func testAllMarkdownEnginesForPages(t *testing.T, assertFunc func(t *testing.T, ext string, pages page.Pages), settings map[string]interface{}, pageSources ...string) { - engines := []struct { ext string shouldExecute func() bool @@ -391,7 +389,6 @@ func testAllMarkdownEnginesForPages(t *testing.T, cfg.Set(k, v) } return nil - }) contentDir := "content" @@ -430,7 +427,6 @@ func testAllMarkdownEnginesForPages(t *testing.T, b.Assert(content(home), qt.Contains, "Home Page Content") } - } // Issue #1076 @@ -492,7 +488,6 @@ categories: ["cool stuff"] checkDated(p, p.Kind()) } checkDate(s.Info.LastChange(), "site") - } func TestPageDatesSections(t *testing.T) { @@ -646,7 +641,6 @@ Simple Page With Some Date` for _, p := range pages { c.Assert(hasDate(p), qt.Equals, true) } - } fields := []string{"date", "publishdate", "pubdate", "published"} @@ -677,7 +671,6 @@ title: Raw p := s.RegularPages()[0] c.Assert("**Raw**", qt.Equals, p.RawContent()) - } func TestPageWithShortCodeInSummary(t *testing.T) { @@ -714,7 +707,6 @@ func TestPageWithAdditionalExtension(t *testing.T) { } func TestTableOfContents(t *testing.T) { - cfg, fs := newTestCfg() c := qt.New(t) @@ -738,7 +730,6 @@ func TestPageWithMoreTag(t *testing.T) { checkPageContent(t, p, normalizeExpected(ext, "<p>Summary Same Line</p>\n\n<p>Some more text</p>\n")) checkPageSummary(t, p, normalizeExpected(ext, "<p>Summary Same Line</p>")) checkPageType(t, p, "page") - } testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithSummaryDelimiterSameLine) @@ -746,7 +737,6 @@ func TestPageWithMoreTag(t *testing.T) { // #2973 func TestSummaryWithHTMLTagsOnNextLine(t *testing.T) { - assertFunc := func(t *testing.T, ext string, pages page.Pages) { c := qt.New(t) p := pages[0] @@ -838,7 +828,6 @@ func TestPageWithLastmodFromGitInfo(t *testing.T) { // 2018-08-11 is the Git author date for testsite/content_nn/first-post.md c.Assert(nnSite.RegularPages()[0].Lastmod().Format("2006-01-02"), qt.Equals, "2018-08-11") - } func TestPageWithFrontMatterConfig(t *testing.T) { @@ -904,7 +893,6 @@ Content } }) } - } func TestWordCountWithAllCJKRunesWithoutHasCJKLanguage(t *testing.T) { @@ -970,7 +958,6 @@ func TestWordCountWithIsCJKLanguageFalse(t *testing.T) { } testAllMarkdownEnginesForPages(t, assertFunc, settings, simplePageWithIsCJKLanguageFalse) - } func TestWordCount(t *testing.T) { @@ -988,7 +975,6 @@ func TestWordCount(t *testing.T) { if p.ReadingTime() != 3 { t.Fatalf("[%s] incorrect min read. expected %v, got %v", ext, 3, p.ReadingTime()) } - } testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithLongContent) @@ -1052,7 +1038,6 @@ func TestTranslationKey(t *testing.T) { p2 := s.RegularPages()[1] c.Assert(p2.TranslationKey(), qt.Equals, "page/sect/simple") - } func TestChompBOM(t *testing.T) { @@ -1125,7 +1110,6 @@ but if you like it, hit :+1: and get subscribed! } } - } func TestPageHTMLContent(t *testing.T) { @@ -1162,7 +1146,6 @@ title: "HTML Content" "Summary: \n<p>This is summary</p>\n|Truncated: true", "|<p>This is the main content.</p>|", ) - } // https://github.com/gohugoio/hugo/issues/5381 @@ -1278,7 +1261,6 @@ Content:{{ .Content }} "Title: hello", "Content:<p>This is the content.</p>", ) - } // https://github.com/gohugoio/hugo/issues/5781 @@ -1305,11 +1287,11 @@ Content. func TestShouldBuild(t *testing.T) { t.Parallel() - var past = time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) - var future = time.Date(2037, 11, 17, 20, 34, 58, 651387237, time.UTC) - var zero = time.Time{} + past := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) + future := time.Date(2037, 11, 17, 20, 34, 58, 651387237, time.UTC) + zero := time.Time{} - var publishSettings = []struct { + publishSettings := []struct { buildFuture bool buildExpired bool buildDrafts bool @@ -1434,7 +1416,6 @@ tags: } else { c.Assert(p.RelPermalink(), qt.Equals, "/post/test0.dot/") } - }) } } @@ -1442,7 +1423,6 @@ tags: // https://github.com/gohugoio/hugo/issues/4675 func TestWordCountAndSimilarVsSummary(t *testing.T) { - t.Parallel() c := qt.New(t) @@ -1534,7 +1514,6 @@ Summary: In Chinese, 好 means good. b.AssertFileContent("public/p4/index.html", "WordCount: 7\nFuzzyWordCount: 100\nReadingTime: 1\nLen Plain: 638\nLen PlainWords: 7\nTruncated: true\nLen Summary: 43\nLen Content: 651") b.AssertFileContent("public/p5/index.html", "WordCount: 206\nFuzzyWordCount: 300\nReadingTime: 1\nLen Plain: 638\nLen PlainWords: 7\nTruncated: true\nLen Summary: 229\nLen Content: 652") b.AssertFileContent("public/p6/index.html", "WordCount: 7\nFuzzyWordCount: 100\nReadingTime: 1\nLen Plain: 638\nLen PlainWords: 7\nTruncated: false\nLen Summary: 637\nLen Content: 652") - } func TestScratchSite(t *testing.T) { @@ -1619,7 +1598,6 @@ author = "Jo Nesbø" "Author name page string: Kurt Vonnegut|", "Author page string: Jo Nesbø|", "Author site config: Kurt Vonnegut") - } func TestGoldmark(t *testing.T) { @@ -1742,7 +1720,6 @@ $$$ for i, ext := range []string{"md", "html"} { b.WithContent(fmt.Sprintf("page%d.%s", i+1, ext), content) - } b.Build(BuildCfg{}) diff --git a/hugolib/pagebundler_test.go b/hugolib/pagebundler_test.go index fa420a025..8f9459564 100644 --- a/hugolib/pagebundler_test.go +++ b/hugolib/pagebundler_test.go @@ -14,8 +14,11 @@ package hugolib import ( + "fmt" + "io" "os" "path" + "path/filepath" "regexp" "strings" "testing" @@ -29,16 +32,10 @@ import ( "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/page" - "io" - "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/media" - "path/filepath" - - "fmt" - "github.com/gohugoio/hugo/deps" "github.com/spf13/viper" @@ -265,12 +262,10 @@ func TestPageBundlerSiteRegular(t *testing.T) { b.AssertFileContent(filepath.FromSlash("/work/public/root/index.html"), "Single Title") } - }) } } } - } func TestPageBundlerSiteMultilingual(t *testing.T) { @@ -296,7 +291,7 @@ func TestPageBundlerSiteMultilingual(t *testing.T) { c.Assert(len(s.RegularPages()), qt.Equals, 8) c.Assert(len(s.Pages()), qt.Equals, 16) - //dumpPages(s.AllPages()...) + // dumpPages(s.AllPages()...) c.Assert(len(s.AllPages()), qt.Equals, 31) bundleWithSubPath := s.getPage(page.KindPage, "lb/index") @@ -350,7 +345,6 @@ func TestPageBundlerSiteMultilingual(t *testing.T) { b.AssertFileContent("public/nn/bc/data1.nn.json", "data1.nn") b.AssertFileContent("public/nn/bc/data2.json", "data2") b.AssertFileContent("public/nn/bc/logo-bc.png", "logo") - }) } } @@ -393,7 +387,6 @@ func TestMultilingualDisableLanguage(t *testing.T) { c.Assert(p.Language().Lang != "nn", qt.Equals, true) return false }) - } func TestPageBundlerSiteWitSymbolicLinksInContent(t *testing.T) { @@ -499,7 +492,6 @@ TheContent. b.AssertFileContent(filepath.FromSlash(workDir+"/public/a/page/index.html"), "TheContent") b.AssertFileContent(filepath.FromSlash(workDir+"/public/symbolic1/s1/index.html"), "TheContent") b.AssertFileContent(filepath.FromSlash(workDir+"/public/symbolic2/a1/index.html"), "TheContent") - } func TestPageBundlerHeadless(t *testing.T) { @@ -583,7 +575,6 @@ HEADLESS {{< myShort >}} c.Assert(s.RegularPages(), qt.HasLen, 1) c.Assert(s.home.RegularPages(), qt.HasLen, 1) c.Assert(s.home.Pages(), qt.HasLen, 1) - } func TestPageBundlerHeadlessIssue6552(t *testing.T) { @@ -705,7 +696,6 @@ Single content. b.AssertFileContent("public/section-not-bundle/index.html", "Section Page", "Content: <p>Section content.</p>") b.AssertFileContent("public/section-not-bundle/single/index.html", "Section Single", "|<p>Single content.</p>") - } func newTestBundleSources(t testing.TB) (*hugofs.Fs, *viper.Viper) { @@ -873,7 +863,6 @@ Content for 은행. c.Assert(err, qt.IsNil) return fs, cfg - } func newTestBundleSourcesMultilingual(t *testing.T) (*hugofs.Fs, *viper.Viper) { @@ -955,7 +944,7 @@ TheContent. writeSource(t, fs, filepath.Join(workDir, "base", "lb", "c", "one.png"), "content") writeSource(t, fs, filepath.Join(workDir, "base", "lb", "c", "d", "deep.png"), "content") - //Translated bundle in some sensible sub path. + // Translated bundle in some sensible sub path. writeSource(t, fs, filepath.Join(workDir, "base", "bf", "my-bf-bundle", "index.md"), pageContent) writeSource(t, fs, filepath.Join(workDir, "base", "bf", "my-bf-bundle", "index.nn.md"), pageContent) writeSource(t, fs, filepath.Join(workDir, "base", "bf", "my-bf-bundle", "page.md"), pageContent) @@ -994,7 +983,6 @@ date: 2017-01-15 b.Build(BuildCfg{}) b.AssertFileContent("public/mybundle/data.json", "My changed data") - } // https://github.com/gohugoio/hugo/issues/4870 @@ -1023,7 +1011,6 @@ slug: %s c.Assert(b.CheckExists("public/about/services1/this-is-the-slug/index.html"), qt.Equals, true) c.Assert(b.CheckExists("public/about/services2/this-is-another-slug/index.html"), qt.Equals, true) - } func TestBundleMisc(t *testing.T) { @@ -1112,13 +1099,11 @@ slug: leaf b.AssertFileContentFn("public/en/index.html", func(s string) bool { // Check ignored files return !regexp.MustCompile("README|ignore").MatchString(s) - }) b.AssertFileContent("public/nn/index.html", filepath.FromSlash("page|sect1/sect2/page.md|CurrentSection: sect1")) b.AssertFileContentFn("public/nn/index.html", func(s string) bool { return !strings.Contains(s, "enonly") - }) // Check order of inherited data file @@ -1136,7 +1121,6 @@ slug: leaf b.AssertFileContent("public/en/b2/index.html", "/en/b2/leaf/", filepath.FromSlash("section|sect1/sect2/_index.md|CurrentSection: sect1/sect2/_index.md")) - } // Issue 6136 @@ -1214,7 +1198,6 @@ Num Pages: {{ len .Site.Pages }} "page|/en/blog/sect2/b1/|Content: s2.b1|Resources: R: data.json|s2.b1.data|", "page|/en/blog/sect2/b2/|Content: s2.b2|Resources: R: s2.b2.bundlecontent|", ) - } // #6208 @@ -1256,11 +1239,9 @@ title: %q page|bundle sub index| page|bundle sub p2| `) - } func TestBundleTransformMany(t *testing.T) { - b := newTestSitesBuilder(t).WithSimpleConfigFile().Running() for i := 1; i <= 50; i++ { diff --git a/hugolib/pagecollections.go b/hugolib/pagecollections.go index 49378452f..c1c9ef88b 100644 --- a/hugolib/pagecollections.go +++ b/hugolib/pagecollections.go @@ -205,7 +205,6 @@ func (c *PageCollections) getSectionOrPage(ref string) (*contentNode, string) { } return m.getPage(s, name), name - } // For Ref/Reflink and .Site.GetPage do simple name lookups for the potentially ambigous myarticle.md and /myarticle.md, @@ -326,7 +325,6 @@ func (c *PageCollections) getContentNode(context page.Page, isReflink bool, ref // Ref/relref supports this potentially ambigous lookup. return getByName(path.Base(name)) - } func (*PageCollections) findPagesByKindIn(kind string, inPages page.Pages) page.Pages { diff --git a/hugolib/pagecollections_test.go b/hugolib/pagecollections_test.go index b9623eb34..d664b7f4e 100644 --- a/hugolib/pagecollections_test.go +++ b/hugolib/pagecollections_test.go @@ -71,7 +71,6 @@ func BenchmarkGetPage(b *testing.B) { } func createGetPageRegularBenchmarkSite(t testing.TB) *Site { - var ( c = qt.New(t) cfg, fs = newTestCfg() @@ -89,7 +88,6 @@ func createGetPageRegularBenchmarkSite(t testing.TB) *Site { } return buildSingleSite(c, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) - } func TestBenchmarkGetPageRegular(t *testing.T) { @@ -142,7 +140,6 @@ func BenchmarkGetPageRegular(b *testing.B) { c.Assert(page, qt.Not(qt.IsNil)) } }) - } type getPageTest struct { @@ -172,7 +169,6 @@ func (t *getPageTest) check(p page.Page, err error, errorMsg string, c *qt.C) { } func TestGetPage(t *testing.T) { - var ( cfg, fs = newTestCfg() c = qt.New(t) @@ -246,10 +242,10 @@ func TestGetPage(t *testing.T) { {"Absolute, page in subsection", page.KindPage, nil, []string{"/sect3/page1.md", "/Sect3/Page1.md"}, "Title3_1"}, {"Absolute, section, subsection with same name", page.KindSection, nil, []string{"/sect3/sect7"}, "another sect7"}, {"Absolute, page, deep", page.KindPage, nil, []string{"/sect3/subsect/deep.md"}, "deep page"}, - {"Absolute, page, OS slashes", page.KindPage, nil, []string{filepath.FromSlash("/sect5/page3.md")}, "Title5_3"}, //test OS-specific path + {"Absolute, page, OS slashes", page.KindPage, nil, []string{filepath.FromSlash("/sect5/page3.md")}, "Title5_3"}, // test OS-specific path {"Absolute, unique", page.KindPage, nil, []string{"/sect3/unique.md"}, "UniqueBase"}, {"Absolute, unique, case", page.KindPage, nil, []string{"/sect3/Unique2.md", "/sect3/unique2.md", "/sect3/unique2", "/sect3/Unique2"}, "UniqueBase2"}, - //next test depends on this page existing + // next test depends on this page existing // {"NoPage", nil, []string{"/unique.md"}, ""}, // ISSUE #4969: this is resolving to /sect3/unique.md {"Absolute, missing page", "NoPage", nil, []string{"/missing-page.md"}, ""}, {"Absolute, missing section", "NoPage", nil, []string{"/missing-section"}, ""}, @@ -267,7 +263,7 @@ func TestGetPage(t *testing.T) { {"Rel sect7 dot", page.KindSection, sec3, []string{"./sect7"}, "another sect7"}, {"Dot deep", page.KindPage, sec3, []string{"./subsect/deep.md"}, "deep page"}, {"Dot dot inner", page.KindPage, sec3, []string{"./subsect/../../sect7/page9.md"}, "Title7_9"}, - {"Dot OS slash", page.KindPage, sec3, []string{filepath.FromSlash("../sect5/page3.md")}, "Title5_3"}, //test OS-specific path + {"Dot OS slash", page.KindPage, sec3, []string{filepath.FromSlash("../sect5/page3.md")}, "Title5_3"}, // test OS-specific path {"Dot unique", page.KindPage, sec3, []string{"./unique.md"}, "UniqueBase"}, {"Dot sect", "NoPage", sec3, []string{"./sect2"}, ""}, //{"NoPage", sec3, []string{"sect2"}, ""}, // ISSUE: /sect3 page relative query is resolving to /sect2 @@ -275,7 +271,7 @@ func TestGetPage(t *testing.T) { {"Abs, ignore context, home", page.KindHome, sec3, []string{"/"}, "home page"}, {"Abs, ignore context, about", page.KindPage, sec3, []string{"/about.md"}, "about page"}, {"Abs, ignore context, page in section", page.KindPage, sec3, []string{"/sect4/page2.md"}, "Title4_2"}, - {"Abs, ignore context, page subsect deep", page.KindPage, sec3, []string{"/sect3/subsect/deep.md"}, "deep page"}, //next test depends on this page existing + {"Abs, ignore context, page subsect deep", page.KindPage, sec3, []string{"/sect3/subsect/deep.md"}, "deep page"}, // next test depends on this page existing {"Abs, ignore context, page deep", "NoPage", sec3, []string{"/subsect/deep.md"}, ""}, // Taxonomies @@ -308,10 +304,8 @@ func TestGetPage(t *testing.T) { page2, err := s.getPageNew(test.context, ref) test.check(page2, err, errorMsg, c) } - }) } - } // https://github.com/gohugoio/hugo/issues/6034 @@ -338,7 +332,6 @@ NOT FOUND b.AssertFileContent("public/what/index.html", `Members: members what`) b.AssertFileContent("public/where/index.html", `Members: members where`) b.AssertFileContent("public/who/index.html", `NOT FOUND`) - } // https://github.com/gohugoio/hugo/issues/7016 @@ -377,7 +370,6 @@ NOT FOUND b.AssertFileContent("public/index.html", `Docs p1: p1`) b.AssertFileContent("public/en/index.html", `NOT FOUND`) - } func TestShouldDoSimpleLookup(t *testing.T) { @@ -387,7 +379,6 @@ func TestShouldDoSimpleLookup(t *testing.T) { c.Assert(shouldDoSimpleLookup("/foo.md"), qt.Equals, true) c.Assert(shouldDoSimpleLookup("./foo.md"), qt.Equals, false) c.Assert(shouldDoSimpleLookup("docs/foo.md"), qt.Equals, false) - } func TestRegularPagesRecursive(t *testing.T) { @@ -426,5 +417,4 @@ Sect1 RegularPagesRecursive: page:/docs/sect1/ps1/|page:/docs/sect1/ps2/|page:/d `) - } diff --git a/hugolib/pages_capture.go b/hugolib/pages_capture.go index 9f2e4bab1..98e9fda51 100644 --- a/hugolib/pages_capture.go +++ b/hugolib/pages_capture.go @@ -44,7 +44,6 @@ func newPagesCollector( logger loggers.Logger, contentTracker *contentChangeMap, proc pagesCollectorProcessorProvider, filenames ...string) *pagesCollector { - return &pagesCollector{ fs: sp.SourceFs, contentMap: contentMap, @@ -75,7 +74,6 @@ func (b *fileinfoBundle) containsResource(name string) bool { } return false - } type pageBundles map[string]*fileinfoBundle @@ -154,7 +152,6 @@ func (c *pagesCollector) isCascadingEdit(dir contentDirKey) (bool, string) { } return true - }) return isCascade, section @@ -213,7 +210,6 @@ func (c *pagesCollector) Collect() (collectErr error) { } return - } func (c *pagesCollector) isBundleHeader(fi hugofs.FileMetaInfo) bool { @@ -343,7 +339,6 @@ func (c *pagesCollector) collectDir(dirname string, partial bool, inFilter func( dir hugofs.FileMetaInfo, path string, readdir []hugofs.FileMetaInfo) error { - if btype > bundleNot && c.tracker != nil { c.tracker.add(path, btype) } @@ -367,7 +362,6 @@ func (c *pagesCollector) collectDir(dirname string, partial bool, inFilter func( } return nil - } filter := func(fim hugofs.FileMetaInfo) bool { @@ -469,7 +463,6 @@ func (c *pagesCollector) collectDir(dirname string, partial bool, inFilter func( // Keep walking. return readdir, nil - } var postHook hugofs.WalkHook @@ -504,14 +497,13 @@ func (c *pagesCollector) collectDir(dirname string, partial bool, inFilter func( Info: fim, HookPre: preHook, HookPost: postHook, - WalkFn: wfn}) + WalkFn: wfn, + }) return w.Walk() - } func (c *pagesCollector) handleBundleBranch(readdir []hugofs.FileMetaInfo) error { - // Maps bundles to its language. bundles := pageBundles{} @@ -542,7 +534,6 @@ func (c *pagesCollector) handleBundleBranch(readdir []hugofs.FileMetaInfo) error } return c.handleFiles(contentFiles...) - } func (c *pagesCollector) handleBundleLeaf(dir hugofs.FileMetaInfo, path string, readdir []hugofs.FileMetaInfo) error { @@ -558,7 +549,6 @@ func (c *pagesCollector) handleBundleLeaf(dir hugofs.FileMetaInfo, path string, } return c.addToBundle(info, bundleLeaf, bundles) - } // Start a new walker from the given path. @@ -568,14 +558,14 @@ func (c *pagesCollector) handleBundleLeaf(dir hugofs.FileMetaInfo, path string, Logger: c.logger, Info: dir, DirEntries: readdir, - WalkFn: walk}) + WalkFn: walk, + }) if err := w.Walk(); err != nil { return err } return c.proc.Process(bundles) - } func (c *pagesCollector) handleFiles(fis ...hugofs.FileMetaInfo) error { diff --git a/hugolib/pages_capture_test.go b/hugolib/pages_capture_test.go index 4401ca6ed..0fdc73e76 100644 --- a/hugolib/pages_capture_test.go +++ b/hugolib/pages_capture_test.go @@ -30,13 +30,12 @@ import ( ) func TestPagesCapture(t *testing.T) { - cfg, hfs := newTestCfg() fs := hfs.Source c := qt.New(t) - var writeFile = func(filename string) { + writeFile := func(filename string) { c.Assert(afero.WriteFile(fs, filepath.FromSlash(filename), []byte(fmt.Sprintf("content-%s", filename)), 0755), qt.IsNil) } @@ -61,7 +60,6 @@ func TestPagesCapture(t *testing.T) { c.Assert(coll.Collect(), qt.IsNil) c.Assert(len(proc.items), qt.Equals, 4) }) - } type testPagesCollectorProcessor struct { @@ -73,6 +71,7 @@ func (proc *testPagesCollectorProcessor) Process(item interface{}) error { proc.items = append(proc.items, item) return nil } + func (proc *testPagesCollectorProcessor) Start(ctx context.Context) context.Context { return ctx } diff --git a/hugolib/pages_language_merge_test.go b/hugolib/pages_language_merge_test.go index 7d7181214..fb59235c1 100644 --- a/hugolib/pages_language_merge_test.go +++ b/hugolib/pages_language_merge_test.go @@ -85,7 +85,6 @@ func TestMergeLanguages(t *testing.T) { unchanged, err := nnSite.RegularPages().MergeByLanguageInterface(nil) c.Assert(err, qt.IsNil) c.Assert(unchanged, deepEqualsPages, nnSite.RegularPages()) - } func TestMergeLanguagesTemplate(t *testing.T) { diff --git a/hugolib/pages_process.go b/hugolib/pages_process.go index af029fee9..90b67a717 100644 --- a/hugolib/pages_process.go +++ b/hugolib/pages_process.go @@ -156,7 +156,6 @@ func (p *sitePagesProcessor) copyFile(fim hugofs.FileMetaInfo) error { defer f.Close() return s.publish(&s.PathSpec.ProcessingStats.Files, target, f) - } func (p *sitePagesProcessor) doProcess(item interface{}) error { @@ -189,7 +188,6 @@ func (p *sitePagesProcessor) doProcess(item interface{}) error { panic(fmt.Sprintf("unrecognized item type in Process: %T", item)) } return nil - } func (p *sitePagesProcessor) shouldSkip(fim hugofs.FileMetaInfo) bool { diff --git a/hugolib/pages_test.go b/hugolib/pages_test.go index 6a371b421..0d879d2c7 100644 --- a/hugolib/pages_test.go +++ b/hugolib/pages_test.go @@ -55,13 +55,13 @@ func BenchmarkPagesPrevNext(b *testing.B) { } for _, variant := range []Variant{ - Variant{".Next", nil, func(p page.Page, pages page.Pages) { p.Next() }}, - Variant{".Prev", nil, func(p page.Page, pages page.Pages) { p.Prev() }}, - Variant{"Pages.Next", nil, func(p page.Page, pages page.Pages) { pages.Next(p) }}, - Variant{"Pages.Prev", nil, func(p page.Page, pages page.Pages) { pages.Prev(p) }}, - Variant{"Pages.Shuffled.Next", shufflePages, func(p page.Page, pages page.Pages) { pages.Next(p) }}, - Variant{"Pages.Shuffled.Prev", shufflePages, func(p page.Page, pages page.Pages) { pages.Prev(p) }}, - Variant{"Pages.ByTitle.Next", func(pages page.Pages) page.Pages { return pages.ByTitle() }, func(p page.Page, pages page.Pages) { pages.Next(p) }}, + {".Next", nil, func(p page.Page, pages page.Pages) { p.Next() }}, + {".Prev", nil, func(p page.Page, pages page.Pages) { p.Prev() }}, + {"Pages.Next", nil, func(p page.Page, pages page.Pages) { pages.Next(p) }}, + {"Pages.Prev", nil, func(p page.Page, pages page.Pages) { pages.Prev(p) }}, + {"Pages.Shuffled.Next", shufflePages, func(p page.Page, pages page.Pages) { pages.Next(p) }}, + {"Pages.Shuffled.Prev", shufflePages, func(p page.Page, pages page.Pages) { pages.Prev(p) }}, + {"Pages.ByTitle.Next", func(pages page.Pages) page.Pages { return pages.ByTitle() }, func(p page.Page, pages page.Pages) { pages.Next(p) }}, } { for _, numPages := range []int{300, 5000} { b.Run(fmt.Sprintf("%s-pages-%d", variant.name, numPages), func(b *testing.B) { diff --git a/hugolib/paginator_test.go b/hugolib/paginator_test.go index e6a196150..a8d8ac8df 100644 --- a/hugolib/paginator_test.go +++ b/hugolib/paginator_test.go @@ -47,7 +47,6 @@ title: Page %d Content. `, i)) } - } b.WithContent(content...) @@ -97,7 +96,6 @@ URL: {{ $pag.URL }} b.AssertFileContent("public/nn/index.xml", "Page Number: 1", "0: 1/1 true") - } // Issue 6023 diff --git a/hugolib/paths/paths.go b/hugolib/paths/paths.go index 97d4f17ba..8af77b072 100644 --- a/hugolib/paths/paths.go +++ b/hugolib/paths/paths.go @@ -82,7 +82,6 @@ type Paths struct { func New(fs *hugofs.Fs, cfg config.Provider) (*Paths, error) { baseURLstr := cfg.GetString("baseURL") baseURL, err := newBaseURLFromString(baseURLstr) - if err != nil { return nil, errors.Wrapf(err, "Failed to create baseURL from %q:", baseURLstr) } @@ -106,7 +105,6 @@ func New(fs *hugofs.Fs, cfg config.Provider) (*Paths, error) { if l, ok := cfg.(*langs.Language); ok { language = l - } if l, ok := cfg.Get("languagesSorted").(langs.Languages); ok { @@ -268,7 +266,6 @@ func (p *Paths) RelPathify(filename string) string { } return strings.TrimPrefix(strings.TrimPrefix(filename, p.WorkingDir), FilePathSeparator) - } // AbsPathify creates an absolute path if given a working dir and arelative path. diff --git a/hugolib/permalinker.go b/hugolib/permalinker.go index 29dad6ce4..aeaa673f7 100644 --- a/hugolib/permalinker.go +++ b/hugolib/permalinker.go @@ -13,9 +13,7 @@ package hugolib -var ( - _ Permalinker = (*pageState)(nil) -) +var _ Permalinker = (*pageState)(nil) // Permalinker provides permalinks of both the relative and absolute kind. type Permalinker interface { diff --git a/hugolib/resource_chain_babel_test.go b/hugolib/resource_chain_babel_test.go index e6e4ed8d3..e56c037f1 100644 --- a/hugolib/resource_chain_babel_test.go +++ b/hugolib/resource_chain_babel_test.go @@ -127,5 +127,4 @@ var Car = function Car(brand) { this.carname = brand; }; `) - } diff --git a/hugolib/resource_chain_test.go b/hugolib/resource_chain_test.go index 7573199aa..5ee62254a 100644 --- a/hugolib/resource_chain_test.go +++ b/hugolib/resource_chain_test.go @@ -15,14 +15,10 @@ package hugolib import ( "bytes" - - jww "github.com/spf13/jwalterweatherman" - "fmt" "io" "math/rand" "os" - "os/exec" "path/filepath" "runtime" @@ -30,6 +26,8 @@ import ( "testing" "time" + jww "github.com/spf13/jwalterweatherman" + "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/htesting" @@ -92,7 +90,6 @@ T1: {{ $r.Content }} b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#fff}`) - } func TestSCSSWithRegularCSSImport(t *testing.T) { @@ -155,7 +152,6 @@ moo { /* foo */ `) - } func TestSCSSWithThemeOverrides(t *testing.T) { @@ -241,7 +237,6 @@ T1: {{ $r.Content }} b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: moo{color:#ccc}boo{color:green}`) - } // https://github.com/gohugoio/hugo/issues/6274 @@ -289,7 +284,6 @@ T1: {{ $r.Content }} b.Build(BuildCfg{}) b.AssertFileContent(filepath.Join(workDir, "public/index.html"), `T1: foo{color:#ccc}`) - } func TestResourceChainBasic(t *testing.T) { @@ -394,11 +388,9 @@ 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) @@ -431,7 +423,6 @@ End. s.Build(BuildCfg{}) } - } func TestResourceChains(t *testing.T) { @@ -472,7 +463,6 @@ T6: {{ $bundle1.Permalink }} 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) { @@ -550,10 +540,8 @@ T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} 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) { @@ -561,11 +549,9 @@ Fingerprinted: {{ $fingerprinted.RelPermalink }} {{ $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 @@ -579,10 +565,8 @@ 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", ` @@ -604,7 +588,6 @@ T4: {{ $r2.Data.Integrity }}| 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) { @@ -615,7 +598,6 @@ 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 @@ -629,7 +611,6 @@ 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}`, @@ -766,7 +747,6 @@ $color: #333; test.prepare(b) b.Build(BuildCfg{}) test.verify(b) - }) } } @@ -785,7 +765,6 @@ func TestMultiSiteResource(t *testing.T) { 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) { @@ -842,7 +821,6 @@ Hello2: Hello Hello1: Bonjour Hello2: Bonjour `) - } func TestResourceChainPostCSS(t *testing.T) { @@ -971,7 +949,6 @@ Styles Content: Len: 770878| b.Assert(strings.Contains(content, "class-in-a"), qt.Equals, true) b.Assert(strings.Contains(content, "class-in-b"), qt.Equals, true) - } assertCss(b) @@ -1031,7 +1008,6 @@ class-in-b { build("always", true) build("fallback", true) build("never", true) - } func TestResourceMinifyDisabled(t *testing.T) { diff --git a/hugolib/robotstxt_test.go b/hugolib/robotstxt_test.go index e924cb8dc..6bc39e97c 100644 --- a/hugolib/robotstxt_test.go +++ b/hugolib/robotstxt_test.go @@ -38,5 +38,4 @@ func TestRobotsTXTOutput(t *testing.T) { b.Build(BuildCfg{}) b.AssertFileContent("public/robots.txt", "User-agent: Googlebot") - } diff --git a/hugolib/shortcode.go b/hugolib/shortcode.go index 619047e38..483fad2e1 100644 --- a/hugolib/shortcode.go +++ b/hugolib/shortcode.go @@ -16,29 +16,25 @@ package hugolib import ( "bytes" "fmt" + "html/template" + "path" + "reflect" + "regexp" + "sort" "strconv" + "strings" + "sync" "github.com/gohugoio/hugo/helpers" - "html/template" - "path" - "github.com/gohugoio/hugo/common/herrors" "github.com/pkg/errors" - "reflect" - - "regexp" - "sort" - "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" _errors "github.com/pkg/errors" - "strings" - "sync" - "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/common/urls" @@ -153,7 +149,6 @@ func (scp *ShortcodeWithPage) Get(key interface{}) interface{} { } return x.Interface() - } func (scp *ShortcodeWithPage) page() page.Page { @@ -230,7 +225,7 @@ func (sc shortcode) String() string { keys = append(keys, k) } sort.Strings(keys) - var tmp = make(map[string]interface{}) + tmp := make(map[string]interface{}) for _, k := range keys { tmp[k] = v[k] @@ -261,7 +256,6 @@ type shortcodeHandler struct { } func newShortcodeHandler(p *pageState, s *Site, placeholderFunc func() string) *shortcodeHandler { - sh := &shortcodeHandler{ p: p, s: s, @@ -286,7 +280,6 @@ func renderShortcode( sc *shortcode, parent *ShortcodeWithPage, p *pageState) (string, bool, error) { - var tmpl tpl.Template // Tracks whether this shortcode or any of its children has template variations @@ -360,7 +353,6 @@ func renderShortcode( if sc.doMarkup && (level > 0 || sc.configVersion() == 1) { var err error b, err := p.pageOutput.cp.renderContent([]byte(inner), false) - if err != nil { return "", false, err } @@ -413,7 +405,6 @@ func (s *shortcodeHandler) hasShortcodes() bool { } func (s *shortcodeHandler) renderShortcodesForPage(p *pageState, f output.Format) (map[string]string, bool, error) { - rendered := make(map[string]string) tplVariants := tpl.TemplateVariants{ @@ -455,9 +446,9 @@ func (s *shortcodeHandler) extractShortcode(ordinal, level int, pt *pageparser.I } sc := &shortcode{ordinal: ordinal} - var cnt = 0 - var nestedOrdinal = 0 - var nextLevel = level + 1 + cnt := 0 + nestedOrdinal := 0 + nextLevel := level + 1 fail := func(err error, i pageparser.Item) error { return s.parseError(err, pt.Input(), i.Pos) @@ -568,7 +559,6 @@ Loop: } else { return sc, errShortCodeIllegalState } - } } else { // positional params @@ -583,7 +573,6 @@ Loop: } else { return sc, errShortCodeIllegalState } - } } case currItem.IsDone(): @@ -599,7 +588,6 @@ Loop: // Replace prefixed shortcode tokens with the real content. // Note: This function will rewrite the input slice. func replaceShortcodeTokens(source []byte, replacements map[string]string) ([]byte, error) { - if len(replacements) == 0 { return source, nil } diff --git a/hugolib/shortcode_test.go b/hugolib/shortcode_test.go index 9e923b093..7f206a788 100644 --- a/hugolib/shortcode_test.go +++ b/hugolib/shortcode_test.go @@ -17,6 +17,8 @@ import ( "fmt" "path/filepath" "reflect" + "strings" + "testing" "github.com/gohugoio/hugo/markup/asciidocext" "github.com/gohugoio/hugo/markup/rst" @@ -26,9 +28,6 @@ import ( "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" - "strings" - "testing" - "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/tpl" "github.com/spf13/cast" @@ -96,7 +95,6 @@ func TestNonSC(t *testing.T) { func TestHyphenatedSC(t *testing.T) { t.Parallel() wt := func(tem tpl.TemplateManager) error { - tem.AddTemplate("_internal/shortcodes/hyphenated-video.html", `Playing Video {{ .Get 0 }}`) return nil } @@ -286,7 +284,6 @@ func TestParentShortcode(t *testing.T) { } CheckShortCodeMatch(t, `{{< r1 pr1="p1" >}}1: {{< r2 pr2="p2" >}}2: {{< r3 pr3="p3" >}}{{< /r3 >}}{{< /r2 >}}{{< /r1 >}}`, "1: p1 1: 2: p1p2 2: 3: p1p2p3 ", wt) - } func TestFigureOnlySrc(t *testing.T) { @@ -392,7 +389,6 @@ title: "Shortcodes Galore!" return func(c *qt.C, shortcode *shortcode, err error) { c.Assert(err, qt.IsNil) c.Assert(str(shortcode), qt.Matches, ".*"+re+".*") - } } @@ -413,10 +409,14 @@ title: "Shortcodes Galore!" {"inner", `{{< inner >}}Inner Content{{< / inner >}}`, regexpCheck("inner;inline:false;closing:true;inner:{Inner Content};")}, // issue #934 {"inner self-closing", `{{< inner />}}`, regexpCheck("inner;.*inner:{}")}, - {"nested inner", `{{< inner >}}Inner Content->{{% inner2 param1 %}}inner2txt{{% /inner2 %}}Inner close->{{< / inner >}}`, - regexpCheck("inner;.*inner:{Inner Content->.*Inner close->}")}, - {"nested, nested inner", `{{< inner >}}inner2->{{% inner2 param1 %}}inner2txt->inner3{{< inner3>}}inner3txt{{</ inner3 >}}{{% /inner2 %}}final close->{{< / inner >}}`, - regexpCheck("inner:{inner2-> inner2.*{{inner2txt->inner3.*final close->}")}, + { + "nested inner", `{{< inner >}}Inner Content->{{% inner2 param1 %}}inner2txt{{% /inner2 %}}Inner close->{{< / inner >}}`, + regexpCheck("inner;.*inner:{Inner Content->.*Inner close->}"), + }, + { + "nested, nested inner", `{{< inner >}}inner2->{{% inner2 param1 %}}inner2txt->inner3{{< inner3>}}inner3txt{{</ inner3 >}}{{% /inner2 %}}final close->{{< / inner >}}`, + regexpCheck("inner:{inner2-> inner2.*{{inner2txt->inner3.*final close->}"), + }, {"closed without content", `{{< inner param1 >}}{{< / inner >}}`, regexpCheck("inner.*inner:{}")}, {"inline", `{{< my.inline >}}Hi{{< /my.inline >}}`, regexpCheck("my.inline;inline:true;closing:true;inner:{Hi};")}, } { @@ -441,10 +441,8 @@ title: "Shortcodes Galore!" short, err := handler.extractShortcode(0, 0, iter) test.check(c, short, err) - }) } - } func TestShortcodesInSite(t *testing.T) { @@ -456,11 +454,14 @@ func TestShortcodesInSite(t *testing.T) { outFile string expected interface{} }{ - {"sect/doc1.md", `a{{< b >}}c`, - filepath.FromSlash("public/sect/doc1/index.html"), "<p>abc</p>\n"}, + { + "sect/doc1.md", `a{{< b >}}c`, + filepath.FromSlash("public/sect/doc1/index.html"), "<p>abc</p>\n", + }, // Issue #1642: Multiple shortcodes wrapped in P // Deliberately forced to pass even if they maybe shouldn't. - {"sect/doc2.md", `a + { + "sect/doc2.md", `a {{< b >}} {{< c >}} @@ -468,8 +469,10 @@ func TestShortcodesInSite(t *testing.T) { e`, filepath.FromSlash("public/sect/doc2/index.html"), - "<p>a</p>\n\n<p>b<br />\nc\nd</p>\n\n<p>e</p>\n"}, - {"sect/doc3.md", `a + "<p>a</p>\n\n<p>b<br />\nc\nd</p>\n\n<p>e</p>\n", + }, + { + "sect/doc3.md", `a {{< b >}} {{< c >}} @@ -478,8 +481,10 @@ e`, e`, filepath.FromSlash("public/sect/doc3/index.html"), - "<p>a</p>\n\n<p>b<br />\nc</p>\n\nd\n\n<p>e</p>\n"}, - {"sect/doc4.md", `a + "<p>a</p>\n\n<p>b<br />\nc</p>\n\nd\n\n<p>e</p>\n", + }, + { + "sect/doc4.md", `a {{< b >}} {{< b >}} {{< b >}} @@ -497,23 +502,33 @@ e`, `, filepath.FromSlash("public/sect/doc4/index.html"), - "<p>a\nb\nb\nb\nb\nb</p>\n"}, + "<p>a\nb\nb\nb\nb\nb</p>\n", + }, // #2192 #2209: Shortcodes in markdown headers - {"sect/doc5.md", `# {{< b >}} + { + "sect/doc5.md", `# {{< b >}} ## {{% c %}}`, - filepath.FromSlash("public/sect/doc5/index.html"), `-hbhb">b</h1>`}, + filepath.FromSlash("public/sect/doc5/index.html"), `-hbhb">b</h1>`, + }, // #2223 pygments - {"sect/doc6.md", "\n```bash\nb = {{< b >}} c = {{% c %}}\n```\n", + { + "sect/doc6.md", "\n```bash\nb = {{< b >}} c = {{% c %}}\n```\n", filepath.FromSlash("public/sect/doc6/index.html"), - `<span class="nv">b</span>`}, + `<span class="nv">b</span>`, + }, // #2249 - {"sect/doc7.ad", `_Shortcodes:_ *b: {{< b >}} c: {{% c %}}*`, + { + "sect/doc7.ad", `_Shortcodes:_ *b: {{< b >}} c: {{% c %}}*`, filepath.FromSlash("public/sect/doc7/index.html"), - "<div class=\"paragraph\">\n<p><em>Shortcodes:</em> <strong>b: b c: c</strong></p>\n</div>\n"}, - {"sect/doc8.rst", `**Shortcodes:** *b: {{< b >}} c: {{% c %}}*`, + "<div class=\"paragraph\">\n<p><em>Shortcodes:</em> <strong>b: b c: c</strong></p>\n</div>\n", + }, + { + "sect/doc8.rst", `**Shortcodes:** *b: {{< b >}} c: {{% c %}}*`, filepath.FromSlash("public/sect/doc8/index.html"), - "<div class=\"document\">\n\n\n<p><strong>Shortcodes:</strong> <em>b: b c: c</em></p>\n</div>"}, - {"sect/doc9.mmark", ` + "<div class=\"document\">\n\n\n<p><strong>Shortcodes:</strong> <em>b: b c: c</em></p>\n</div>", + }, + { + "sect/doc9.mmark", ` --- menu: main: @@ -521,9 +536,11 @@ menu: --- **Shortcodes:** *b: {{< b >}} c: {{% c %}}*`, filepath.FromSlash("public/sect/doc9/index.html"), - "<p><strong>Shortcodes:</strong> <em>b: b c: c</em></p>\n"}, + "<p><strong>Shortcodes:</strong> <em>b: b c: c</em></p>\n", + }, // Issue #1229: Menus not available in shortcode. - {"sect/doc10.md", `--- + { + "sect/doc10.md", `--- menu: main: identifier: 'parent' @@ -532,22 +549,27 @@ tags: --- **Menus:** {{< menu >}}`, filepath.FromSlash("public/sect/doc10/index.html"), - "<p><strong>Menus:</strong> 1</p>\n"}, + "<p><strong>Menus:</strong> 1</p>\n", + }, // Issue #2323: Taxonomies not available in shortcode. - {"sect/doc11.md", `--- + { + "sect/doc11.md", `--- tags: - Bugs --- **Tags:** {{< tags >}}`, filepath.FromSlash("public/sect/doc11/index.html"), - "<p><strong>Tags:</strong> 2</p>\n"}, - {"sect/doc12.md", `--- + "<p><strong>Tags:</strong> 2</p>\n", + }, + { + "sect/doc12.md", `--- title: "Foo" --- {{% html-indented-v1 %}}`, "public/sect/doc12/index.html", - "<h1>Hugo!</h1>"}, + "<h1>Hugo!</h1>", + }, } temp := tests[:0] @@ -582,7 +604,6 @@ title: "Foo" templ.AddTemplate("_internal/shortcodes/tags.html", `{{ len .Page.Site.Taxonomies.tags }}`) return nil - } cfg, fs := newTestCfg() @@ -615,7 +636,6 @@ title: "Foo" }) } - } func TestShortcodeMultipleOutputFormats(t *testing.T) { @@ -741,11 +761,9 @@ CSV: {{< myShort >}} "Single CSV", "ShortCSV", ) - } func BenchmarkReplaceShortcodeTokens(b *testing.B) { - type input struct { in []byte replacements map[string]string @@ -764,8 +782,8 @@ func BenchmarkReplaceShortcodeTokens(b *testing.B) { {strings.Repeat("A ", 3000) + " HAHAHUGOSHORTCODE-1HBHB." + strings.Repeat("BC ", 1000) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A ", 3000) + " Hello World." + strings.Repeat("BC ", 1000) + " Hello World.")}, } - var in = make([]input, b.N*len(data)) - var cnt = 0 + in := make([]input, b.N*len(data)) + cnt := 0 for i := 0; i < b.N; i++ { for _, this := range data { in[cnt] = input{[]byte(this.input), this.replacements, this.expect} @@ -780,7 +798,6 @@ func BenchmarkReplaceShortcodeTokens(b *testing.B) { currIn := in[cnt] cnt++ results, err := replaceShortcodeTokens(currIn.in, currIn.replacements) - if err != nil { b.Fatalf("[%d] failed: %s", i, err) continue @@ -790,7 +807,6 @@ func BenchmarkReplaceShortcodeTokens(b *testing.B) { } } - } } @@ -826,9 +842,12 @@ func TestReplaceShortcodeTokens(t *testing.T) { {"Hello <p>HAHAHUGOSHORTCODE-1HBHB. END</p>.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World. END</p>."}, {"<p>Hello HAHAHUGOSHORTCODE-1HBHB</p>. END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "<p>Hello World</p>. END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB12", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World12"}, - {"Hello HAHAHUGOSHORTCODE-1HBHB. HAHAHUGOSHORTCODE-1HBHB-HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB END", "P", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": strings.Repeat("BC", 100)}, + { + "Hello HAHAHUGOSHORTCODE-1HBHB. HAHAHUGOSHORTCODE-1HBHB-HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB END", "P", + map[string]string{"HAHAHUGOSHORTCODE-1HBHB": strings.Repeat("BC", 100)}, fmt.Sprintf("Hello %s. %s-%s %s %s %s END", - strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100))}, + strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100)), + }, } { results, err := replaceShortcodeTokens([]byte(this.input), this.replacements) @@ -848,7 +867,6 @@ func TestReplaceShortcodeTokens(t *testing.T) { } } - } func TestShortcodeGetContent(t *testing.T) { @@ -919,7 +937,6 @@ C-%s` "Single Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "P2:docbp1/<p>C-bp1</p>", ) - } // https://github.com/gohugoio/hugo/issues/5833 @@ -978,7 +995,6 @@ SHORTCODE: {{< c >}} b.Build(BuildCfg{}) assert("Edit.") - } func TestShortcodePreserveOrder(t *testing.T) { @@ -1036,7 +1052,6 @@ weight: %d ordinal: 0 scratch ordinal: 1 scratch get ordinal: 0 ordinal: 2 scratch ordinal: 3 scratch get ordinal: 2 ordinal: 4 scratch ordinal: 5 scratch get ordinal: 4`) - } func TestShortcodeVariables(t *testing.T) { @@ -1074,7 +1089,6 @@ String: {{ . | safeHTML }} filepath.FromSlash("String: \"content/page.md:7:4\""), "Name: s1", ) - } func TestInlineShortcodes(t *testing.T) { @@ -1311,10 +1325,8 @@ title: "Hugo Rocks!" `, ) } - }) } - } // https://github.com/gohugoio/hugo/issues/6857 @@ -1334,5 +1346,4 @@ title: "No Inner!" err := b.BuildE(BuildCfg{}) b.Assert(err.Error(), qt.Contains, `failed to extract shortcode: shortcode "noinner" has no .Inner, yet a closing tag was provided`) - } diff --git a/hugolib/site.go b/hugolib/site.go index 05dd2307a..4175fecc2 100644 --- a/hugolib/site.go +++ b/hugolib/site.go @@ -251,7 +251,6 @@ func (s *Site) prepareInits() { }) s.init.prevNextInSection = init.Branch(func() (interface{}, error) { - var sections page.Pages s.home.treeRef.m.collectSectionsRecursiveIncludingSelf(pageMapQuery{Prefix: s.home.treeRef.key}, func(n *contentNode) { sections = append(sections, n.p) @@ -317,7 +316,6 @@ func (s *Site) prepareInits() { err := s.pageMap.assembleTaxonomies() return nil, err }) - } type siteRenderingContext struct { @@ -375,7 +373,8 @@ func (s *Site) isEnabled(kind string) bool { // reset returns a new Site prepared for rebuild. func (s *Site) reset() *Site { - return &Site{Deps: s.Deps, + return &Site{ + Deps: s.Deps, disabledKinds: s.disabledKinds, titleFunc: s.titleFunc, relatedDocsHandler: s.relatedDocsHandler.Clone(), @@ -394,7 +393,6 @@ func (s *Site) reset() *Site { PageCollections: s.PageCollections, siteCfg: s.siteCfg, } - } // newSite creates a new site with the given configuration. @@ -427,7 +425,6 @@ func newSite(cfg deps.DepsCfg) (*Site, error) { // This is a potentially ambigous situation. It may be correct. ignorableLogger.Errorsf(constants.ErrIDAmbigousDisableKindTaxonomy, `You have the value 'taxonomy' in the disabledKinds list. In Hugo 0.73.0 we fixed these to be what most people expect (taxonomy and term). But this also means that your site configuration may not do what you expect. If it is correct, you can suppress this message by following the instructions below.`) - } var ( @@ -566,7 +563,6 @@ But this also means that your site configuration may not do what you expect. If s.prepareInits() return s, nil - } // NewSite creates a new site with the given dependency configuration. @@ -623,7 +619,6 @@ func newSiteForLang(lang *langs.Language, withTemplate ...func(templ tpl.Templat cfg := deps.DepsCfg{WithTemplate: withTemplates, Cfg: lang} return NewSiteForCfg(cfg) - } // NewSiteForCfg creates a new site for the given configuration. @@ -635,7 +630,6 @@ func NewSiteForCfg(cfg deps.DepsCfg) (*Site, error) { return nil, err } return h.Sites[0], nil - } type SiteInfo struct { @@ -669,12 +663,10 @@ type SiteInfo struct { func (s *SiteInfo) Pages() page.Pages { return s.s.Pages() - } func (s *SiteInfo) RegularPages() page.Pages { return s.s.RegularPages() - } func (s *SiteInfo) AllPages() page.Pages { @@ -761,7 +753,6 @@ func (s *SiteInfo) ServerPort() int { // GoogleAnalytics is kept here for historic reasons. func (s *SiteInfo) GoogleAnalytics() string { return s.Config().Services.GoogleAnalytics.ID - } // DisqusShortname is kept here for historic reasons. @@ -1193,7 +1184,6 @@ func (s *Site) processPartial(config *BuildCfg, init func(config *BuildCfg) erro } return nil - } func (s *Site) process(config BuildCfg) (err error) { @@ -1206,11 +1196,9 @@ func (s *Site) process(config BuildCfg) (err error) { return } return err - } func (s *Site) render(ctx *siteRenderContext) (err error) { - if err := page.Clear(); err != nil { return err } @@ -1228,7 +1216,6 @@ func (s *Site) render(ctx *siteRenderContext) (err error) { return } } - } if err = s.renderPages(ctx); err != nil { @@ -1309,7 +1296,7 @@ func (s *Site) initializeSiteInfo() error { languagePrefix = "/" + lang.Lang } - var uglyURLs = func(p page.Page) bool { + uglyURLs := func(p page.Page) bool { return false } @@ -1388,7 +1375,6 @@ func (s *Site) readAndProcessContent(filenames ...string) error { } func (s *Site) getMenusFromConfig() navigation.Menus { - ret := navigation.Menus{} if menus := s.language.GetStringMap("menus"); menus != nil { @@ -1425,7 +1411,6 @@ func (s *Site) getMenusFromConfig() navigation.Menus { } func (s *SiteInfo) createNodeMenuEntryURL(in string) string { - if !strings.HasPrefix(in, "/") { return in } @@ -1471,15 +1456,16 @@ func (s *Site) assembleMenus() { return false } - me := navigation.MenuEntry{Identifier: id, - Name: p.LinkTitle(), - Weight: p.Weight(), - Page: p} + me := navigation.MenuEntry{ + Identifier: id, + Name: p.LinkTitle(), + Weight: p.Weight(), + Page: p, + } flat[twoD{sectionPagesMenu, me.KeyName()}] = &me return false }) - } // Add menu entries provided by pages @@ -1538,7 +1524,6 @@ func (s *Site) getLanguageTargetPathLang(alwaysInSubDir bool) string { // get any lanaguagecode to prefix the relative permalink with. func (s *Site) getLanguagePermalinkLang(alwaysInSubDir bool) string { - if !s.Info.IsMultiLingual() || s.h.IsMultihost() { return "" } @@ -1800,7 +1785,6 @@ func (s *Site) kindFromSections(sections []string) string { } return s.kindFromSectionPath(path.Join(sections...)) - } func (s *Site) kindFromSectionPath(sectionPath string) string { @@ -1823,7 +1807,6 @@ func (s *Site) newPage( parentbBucket *pagesMapBucket, kind, title string, sections ...string) *pageState { - m := map[string]interface{}{} if title != "" { m["title"] = title @@ -1838,7 +1821,6 @@ func (s *Site) newPage( kind: kind, sections: sections, }) - if err != nil { panic(err) } diff --git a/hugolib/siteJSONEncode_test.go b/hugolib/siteJSONEncode_test.go index ac0286ce2..94bac1873 100644 --- a/hugolib/siteJSONEncode_test.go +++ b/hugolib/siteJSONEncode_test.go @@ -41,5 +41,4 @@ Content. b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `"Date":"2019-02-28T00:00:00Z"`) - } diff --git a/hugolib/site_benchmark_new_test.go b/hugolib/site_benchmark_new_test.go index 1f16c97e5..228dbeb5d 100644 --- a/hugolib/site_benchmark_new_test.go +++ b/hugolib/site_benchmark_new_test.go @@ -118,7 +118,6 @@ See my [About](/about/) page for details. ` func getBenchmarkSiteNewTestCases() []siteBenchmarkTestcase { - pageContentWithCategory := func(size int, category string) string { return getBenchmarkTestDataPageContentForMarkdown(size, category, benchmarkMarkdownSnippets) } @@ -132,40 +131,41 @@ baseURL = "https://example.com" ` benchmarks := []siteBenchmarkTestcase{ - {"Bundle with image", func(b testing.TB) *sitesBuilder { - sb := newTestSitesBuilder(b).WithConfigFile("toml", config) - sb.WithContent("content/blog/mybundle/index.md", pageContent(1)) - sb.WithSunset("content/blog/mybundle/sunset1.jpg") + { + "Bundle with image", func(b testing.TB) *sitesBuilder { + sb := newTestSitesBuilder(b).WithConfigFile("toml", config) + sb.WithContent("content/blog/mybundle/index.md", pageContent(1)) + sb.WithSunset("content/blog/mybundle/sunset1.jpg") - return sb - }, + return sb + }, func(s *sitesBuilder) { s.AssertFileContent("public/blog/mybundle/index.html", "/blog/mybundle/sunset1.jpg") s.CheckExists("public/blog/mybundle/sunset1.jpg") - }, }, - {"Bundle with JSON file", func(b testing.TB) *sitesBuilder { - sb := newTestSitesBuilder(b).WithConfigFile("toml", config) - sb.WithContent("content/blog/mybundle/index.md", pageContent(1)) - sb.WithContent("content/blog/mybundle/mydata.json", `{ "hello": "world" }`) + { + "Bundle with JSON file", func(b testing.TB) *sitesBuilder { + sb := newTestSitesBuilder(b).WithConfigFile("toml", config) + sb.WithContent("content/blog/mybundle/index.md", pageContent(1)) + sb.WithContent("content/blog/mybundle/mydata.json", `{ "hello": "world" }`) - return sb - }, + return sb + }, func(s *sitesBuilder) { s.AssertFileContent("public/blog/mybundle/index.html", "Resources: application/json: /blog/mybundle/mydata.json") s.CheckExists("public/blog/mybundle/mydata.json") - }, }, - {"Tags and categories", func(b testing.TB) *sitesBuilder { - sb := newTestSitesBuilder(b).WithConfigFile("toml", ` + { + "Tags and categories", func(b testing.TB) *sitesBuilder { + sb := newTestSitesBuilder(b).WithConfigFile("toml", ` title = "Tags and Cats" baseURL = "https://example.com" `) - const pageTemplate = ` + const pageTemplate = ` --- title: "Some tags and cats" categories: ["caGR", "cbGR"] @@ -175,50 +175,51 @@ tags: ["taGR", "tbGR"] Some content. ` - for i := 1; i <= 100; i++ { - content := strings.Replace(pageTemplate, "GR", strconv.Itoa(i/3), -1) - sb.WithContent(fmt.Sprintf("content/page%d.md", i), content) - } + for i := 1; i <= 100; i++ { + content := strings.Replace(pageTemplate, "GR", strconv.Itoa(i/3), -1) + sb.WithContent(fmt.Sprintf("content/page%d.md", i), content) + } - return sb - }, + return sb + }, func(s *sitesBuilder) { s.AssertFileContent("public/page3/index.html", "/page3/|Permalink: https://example.com/page3/") s.AssertFileContent("public/tags/ta3/index.html", "|ta3|") }, }, - {"Canonify URLs", func(b testing.TB) *sitesBuilder { - sb := newTestSitesBuilder(b).WithConfigFile("toml", ` + { + "Canonify URLs", func(b testing.TB) *sitesBuilder { + sb := newTestSitesBuilder(b).WithConfigFile("toml", ` title = "Canon" baseURL = "https://example.com" canonifyURLs = true `) - for i := 1; i <= 100; i++ { - sb.WithContent(fmt.Sprintf("content/page%d.md", i), pageContent(i)) - } + for i := 1; i <= 100; i++ { + sb.WithContent(fmt.Sprintf("content/page%d.md", i), pageContent(i)) + } - return sb - }, + return sb + }, func(s *sitesBuilder) { s.AssertFileContent("public/page8/index.html", "https://example.com/about/") }, }, - {"Deep content tree", func(b testing.TB) *sitesBuilder { - return getBenchmarkSiteDeepContent(b) - }, + { + "Deep content tree", func(b testing.TB) *sitesBuilder { + return getBenchmarkSiteDeepContent(b) + }, func(s *sitesBuilder) { s.CheckExists("public/blog/mybundle/index.html") s.Assert(len(s.H.Sites), qt.Equals, 4) s.Assert(len(s.H.Sites[0].RegularPages()), qt.Equals, len(s.H.Sites[1].RegularPages())) s.Assert(len(s.H.Sites[0].RegularPages()), qt.Equals, 30) - }, }, - {"Many HTML templates", func(b testing.TB) *sitesBuilder { - - pageTemplateTemplate := ` + { + "Many HTML templates", func(b testing.TB) *sitesBuilder { + pageTemplateTemplate := ` <!DOCTYPE html> <html> <head> @@ -243,7 +244,7 @@ canonifyURLs = true </html> ` - sb := newTestSitesBuilder(b).WithConfigFile("toml", ` + sb := newTestSitesBuilder(b).WithConfigFile("toml", ` baseURL = "https://example.com" [languages] @@ -262,37 +263,36 @@ contentDir="content/sv" `) - createContent := func(dir, name string) { - sb.WithContent(filepath.Join("content", dir, name), pageContent(1)) - } + createContent := func(dir, name string) { + sb.WithContent(filepath.Join("content", dir, name), pageContent(1)) + } - for _, lang := range []string{"en", "fr", "no", "sv"} { - sb.WithTemplatesAdded(fmt.Sprintf("_default/single.%s.html", lang), pageTemplateTemplate) - sb.WithTemplatesAdded(fmt.Sprintf("_default/list.%s.html", lang), pageTemplateTemplate) + for _, lang := range []string{"en", "fr", "no", "sv"} { + sb.WithTemplatesAdded(fmt.Sprintf("_default/single.%s.html", lang), pageTemplateTemplate) + sb.WithTemplatesAdded(fmt.Sprintf("_default/list.%s.html", lang), pageTemplateTemplate) - for level := 1; level <= 5; level++ { - sectionDir := path.Join(lang, strings.Repeat("section/", level)) - createContent(sectionDir, "_index.md") - for i := 1; i <= 3; i++ { - leafBundleDir := path.Join(sectionDir, fmt.Sprintf("bundle%d", i)) - createContent(leafBundleDir, "index.md") + for level := 1; level <= 5; level++ { + sectionDir := path.Join(lang, strings.Repeat("section/", level)) + createContent(sectionDir, "_index.md") + for i := 1; i <= 3; i++ { + leafBundleDir := path.Join(sectionDir, fmt.Sprintf("bundle%d", i)) + createContent(leafBundleDir, "index.md") + } } } - } - return sb - }, + return sb + }, func(s *sitesBuilder) { s.CheckExists("public/blog/mybundle/index.html") s.Assert(len(s.H.Sites), qt.Equals, 4) s.Assert(len(s.H.Sites[0].RegularPages()), qt.Equals, len(s.H.Sites[1].RegularPages())) s.Assert(len(s.H.Sites[0].RegularPages()), qt.Equals, 15) - }, }, - {"Page collections", func(b testing.TB) *sitesBuilder { - - pageTemplateTemplate := ` + { + "Page collections", func(b testing.TB) *sitesBuilder { + pageTemplateTemplate := ` {{ if .IsNode }} {{ len .Paginator.Pages }} {{ end }} @@ -308,7 +308,7 @@ contentDir="content/sv" {{ with .Prev }}Prev: {{ .RelPermalink }}{{ end }} ` - sb := newTestSitesBuilder(b).WithConfigFile("toml", ` + sb := newTestSitesBuilder(b).WithConfigFile("toml", ` baseURL = "https://example.com" [languages] @@ -327,57 +327,55 @@ contentDir="content/sv" `) - sb.WithTemplates("index.html", pageTemplateTemplate) - sb.WithTemplates("_default/single.html", pageTemplateTemplate) - sb.WithTemplates("_default/list.html", pageTemplateTemplate) + sb.WithTemplates("index.html", pageTemplateTemplate) + sb.WithTemplates("_default/single.html", pageTemplateTemplate) + sb.WithTemplates("_default/list.html", pageTemplateTemplate) - r := rand.New(rand.NewSource(99)) + r := rand.New(rand.NewSource(99)) - createContent := func(dir, name string) { - var content string - if strings.Contains(name, "_index") { - content = pageContent(1) + createContent := func(dir, name string) { + var content string + if strings.Contains(name, "_index") { + content = pageContent(1) + } else { + content = pageContentWithCategory(1, fmt.Sprintf("category%d", r.Intn(5)+1)) + } - } else { - content = pageContentWithCategory(1, fmt.Sprintf("category%d", r.Intn(5)+1)) + sb.WithContent(filepath.Join("content", dir, name), content) } - sb.WithContent(filepath.Join("content", dir, name), content) - } - - createBundledFiles := func(dir string) { - sb.WithContent(filepath.Join("content", dir, "data.json"), `{ "hello": "world" }`) - for i := 1; i <= 3; i++ { - sb.WithContent(filepath.Join("content", dir, fmt.Sprintf("page%d.md", i)), pageContent(1)) + createBundledFiles := func(dir string) { + sb.WithContent(filepath.Join("content", dir, "data.json"), `{ "hello": "world" }`) + for i := 1; i <= 3; i++ { + sb.WithContent(filepath.Join("content", dir, fmt.Sprintf("page%d.md", i)), pageContent(1)) + } } - } - for _, lang := range []string{"en", "fr", "no", "sv"} { - for level := 1; level <= r.Intn(5)+1; level++ { - sectionDir := path.Join(lang, strings.Repeat("section/", level)) - createContent(sectionDir, "_index.md") - createBundledFiles(sectionDir) - for i := 1; i <= r.Intn(20)+1; i++ { - leafBundleDir := path.Join(sectionDir, fmt.Sprintf("bundle%d", i)) - createContent(leafBundleDir, "index.md") - createBundledFiles(path.Join(leafBundleDir, "assets1")) - createBundledFiles(path.Join(leafBundleDir, "assets1", "assets2")) + for _, lang := range []string{"en", "fr", "no", "sv"} { + for level := 1; level <= r.Intn(5)+1; level++ { + sectionDir := path.Join(lang, strings.Repeat("section/", level)) + createContent(sectionDir, "_index.md") + createBundledFiles(sectionDir) + for i := 1; i <= r.Intn(20)+1; i++ { + leafBundleDir := path.Join(sectionDir, fmt.Sprintf("bundle%d", i)) + createContent(leafBundleDir, "index.md") + createBundledFiles(path.Join(leafBundleDir, "assets1")) + createBundledFiles(path.Join(leafBundleDir, "assets1", "assets2")) + } } } - } - return sb - }, + return sb + }, func(s *sitesBuilder) { s.CheckExists("public/blog/mybundle/index.html") s.Assert(len(s.H.Sites), qt.Equals, 4) s.Assert(len(s.H.Sites[0].RegularPages()), qt.Equals, 26) - }, }, - {"List terms", func(b testing.TB) *sitesBuilder { - - pageTemplateTemplate := ` + { + "List terms", func(b testing.TB) *sitesBuilder { + pageTemplateTemplate := ` <ul> {{ range (.GetTerms "categories") }} <li><a href="{{ .Permalink }}">{{ .LinkTitle }}</a></li> @@ -385,46 +383,44 @@ contentDir="content/sv" </ul> ` - sb := newTestSitesBuilder(b).WithConfigFile("toml", ` + sb := newTestSitesBuilder(b).WithConfigFile("toml", ` baseURL = "https://example.com" `) - sb.WithTemplates("_default/single.html", pageTemplateTemplate) + sb.WithTemplates("_default/single.html", pageTemplateTemplate) - r := rand.New(rand.NewSource(99)) + r := rand.New(rand.NewSource(99)) - createContent := func(dir, name string) { - var content string - if strings.Contains(name, "_index") { - content = pageContent(1) - } else { - content = pageContentWithCategory(1, fmt.Sprintf("category%d", r.Intn(5)+1)) - sb.WithContent(filepath.Join("content", dir, name), content) + createContent := func(dir, name string) { + var content string + if strings.Contains(name, "_index") { + content = pageContent(1) + } else { + content = pageContentWithCategory(1, fmt.Sprintf("category%d", r.Intn(5)+1)) + sb.WithContent(filepath.Join("content", dir, name), content) + } } - } - for level := 1; level <= r.Intn(5)+1; level++ { - sectionDir := path.Join(strings.Repeat("section/", level)) - createContent(sectionDir, "_index.md") - for i := 1; i <= r.Intn(33); i++ { - leafBundleDir := path.Join(sectionDir, fmt.Sprintf("bundle%d", i)) - createContent(leafBundleDir, "index.md") + for level := 1; level <= r.Intn(5)+1; level++ { + sectionDir := path.Join(strings.Repeat("section/", level)) + createContent(sectionDir, "_index.md") + for i := 1; i <= r.Intn(33); i++ { + leafBundleDir := path.Join(sectionDir, fmt.Sprintf("bundle%d", i)) + createContent(leafBundleDir, "index.md") + } } - } - return sb - }, + return sb + }, func(s *sitesBuilder) { s.AssertFileContent("public/section/bundle8/index.html", ` <li><a href="https://example.com/categories/category1/">category1</a></li>`) s.Assert(len(s.H.Sites), qt.Equals, 1) s.Assert(len(s.H.Sites[0].RegularPages()), qt.Equals, 35) - }, }, } return benchmarks - } // Run the benchmarks below as tests. Mostly useful when adding new benchmark @@ -440,7 +436,6 @@ func TestBenchmarkSiteNew(b *testing.T) { b.Fatal(err) } bm.check(s) - }) } } @@ -465,7 +460,6 @@ Edited!!`, p.Title())) // We could probably optimize that case, but it's not trivial. b.Assert(int(counters.contentRenderCounter), qt.Equals, 4) b.AssertFileContent("public"+p.RelPermalink()+"index.html", "Edited!!") - } func BenchmarkSiteNew(b *testing.B) { diff --git a/hugolib/site_output.go b/hugolib/site_output.go index 6a630f4ea..c9c9f0ae5 100644 --- a/hugolib/site_output.go +++ b/hugolib/site_output.go @@ -51,7 +51,6 @@ func createDefaultOutputFormats(allFormats output.Formats) map[string]output.For } return m - } func createSiteOutputFormats(allFormats output.Formats, outputs map[string]interface{}, rssDisabled bool) (map[string]output.Formats, error) { @@ -84,7 +83,6 @@ func createSiteOutputFormats(allFormats output.Formats, outputs map[string]inter // This is legacy behaviour. We used to have both // a RSS page kind and output format. continue - } return nil, fmt.Errorf("failed to resolve output format %q from site config", format) } @@ -107,5 +105,4 @@ func createSiteOutputFormats(allFormats output.Formats, outputs map[string]inter } return outFormats, nil - } diff --git a/hugolib/site_output_test.go b/hugolib/site_output_test.go index c324be7dd..5a329942c 100644 --- a/hugolib/site_output_test.go +++ b/hugolib/site_output_test.go @@ -14,6 +14,7 @@ package hugolib import ( + "fmt" "strings" "testing" @@ -22,8 +23,6 @@ import ( "github.com/spf13/afero" - "fmt" - "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/output" "github.com/spf13/viper" @@ -40,7 +39,6 @@ func TestSiteWithPageOutputs(t *testing.T) { } func doTestSiteWithPageOutputs(t *testing.T, outputs []string) { - outputsStr := strings.Replace(fmt.Sprintf("%q", outputs), " ", ", ", -1) siteConfig := ` @@ -215,7 +213,6 @@ Len Pages: {{ .Kind }} {{ len .Site.RegularPages }} Page Number: {{ .Paginator.P b.Assert(home.HasShortcode("myShort"), qt.Equals, true) b.Assert(home.HasShortcode("doesNotExist"), qt.Equals, false) - } // Issue #3447 @@ -250,9 +247,8 @@ baseName = "feed" s := h.Sites[0] - //Issue #3450 + // Issue #3450 c.Assert(s.Info.RSSLink, qt.Equals, "http://example.com/blog/feed.xml") - } // Issue #3614 @@ -325,11 +321,9 @@ baseName = "customdelimbase" c.Assert(outputs.Get("DEF").RelPermalink(), qt.Equals, "/blog/defaultdelimbase.defd") c.Assert(outputs.Get("NOS").RelPermalink(), qt.Equals, "/blog/nosuffixbase") c.Assert(outputs.Get("CUS").RelPermalink(), qt.Equals, "/blog/customdelimbase_del") - } func TestCreateSiteOutputFormats(t *testing.T) { - t.Run("Basic", func(t *testing.T) { c := qt.New(t) @@ -358,7 +352,6 @@ func TestCreateSiteOutputFormats(t *testing.T) { c.Assert(outputs[kindSitemap], deepEqualsOutputFormats, output.Formats{output.SitemapFormat}) c.Assert(outputs[kindRobotsTXT], deepEqualsOutputFormats, output.Formats{output.RobotsTxtFormat}) c.Assert(outputs[kind404], deepEqualsOutputFormats, output.Formats{output.HTMLFormat}) - }) // Issue #4528 @@ -376,9 +369,7 @@ func TestCreateSiteOutputFormats(t *testing.T) { outputs, err := createSiteOutputFormats(output.DefaultFormats, cfg.GetStringMap("outputs"), false) c.Assert(err, qt.IsNil) c.Assert(outputs[page.KindTaxonomy], deepEqualsOutputFormats, output.Formats{output.JSONFormat}) - }) - } func TestCreateSiteOutputFormatsInvalidConfig(t *testing.T) { @@ -432,7 +423,6 @@ func TestCreateSiteOutputFormatsCustomFormats(t *testing.T) { // https://github.com/gohugoio/hugo/issues/5849 func TestOutputFormatPermalinkable(t *testing.T) { - config := ` baseURL = "https://example.com" @@ -575,7 +565,6 @@ Output Formats: {{ len .OutputFormats }};{{ range .OutputFormats }}{{ .Name }};{ "This RelPermalink: /blog/html-base-nobase/", outputFormats, ) - } func TestSiteWithPageNoOutputs(t *testing.T) { @@ -625,5 +614,4 @@ WordCount: {{ .WordCount }} b.AssertFileContent("public/outputs-empty/index.html", "HTML:", "Word1. Word2.") b.AssertFileContent("public/outputs-string/index.html", "O1:", "Word1. Word2.") - } diff --git a/hugolib/site_render.go b/hugolib/site_render.go index 531d481f0..84293cfc0 100644 --- a/hugolib/site_render.go +++ b/hugolib/site_render.go @@ -53,7 +53,6 @@ func (s siteRenderContext) renderSingletonPages() bool { // 1 for all sites return s.sitesOutIdx == 0 - } // renderPages renders pages each corresponding to a markdown file. @@ -107,7 +106,6 @@ func pageRenderer( pages <-chan *pageState, results chan<- error, wg *sync.WaitGroup) { - defer wg.Done() for p := range pages { @@ -184,7 +182,6 @@ func (s *Site) logMissingLayout(name, layout, kind, outputFormat string) { // renderPaginator must be run after the owning Page has been rendered. func (s *Site) renderPaginator(p *pageState, templ tpl.Template) error { - paginatePath := s.Cfg.GetString("paginatePath") d := p.targetPathDescriptor @@ -234,7 +231,6 @@ func (s *Site) render404() error { }, output.HTMLFormat, ) - if err != nil { return err } @@ -269,10 +265,10 @@ func (s *Site) renderSitemap() error { kind: kindSitemap, urlPaths: pagemeta.URLPath{ URL: s.siteCfg.sitemap.Filename, - }}, + }, + }, output.HTMLFormat, ) - if err != nil { return err } @@ -305,7 +301,6 @@ func (s *Site) renderRobotsTXT() error { }, }, output.RobotsTxtFormat) - if err != nil { return err } @@ -317,7 +312,6 @@ func (s *Site) renderRobotsTXT() error { templ := s.lookupLayouts("robots.txt", "_default/robots.txt", "_internal/_default/robots.txt") return s.renderAndWritePage(&s.PathSpec.ProcessingStats.Pages, "Robots Txt", p.targetPaths().TargetFilename, p, templ) - } // renderAliases renders shell pages that simply have a redirect in the header. @@ -385,7 +379,6 @@ func (s *Site) renderAliases() error { // renderMainLanguageRedirect creates a redirect to the main language home, // depending on if it lives in sub folder (e.g. /en) or not. func (s *Site) renderMainLanguageRedirect() error { - if !s.h.multilingual.enabled() || s.h.IsMultihost() { // No need for a redirect return nil diff --git a/hugolib/site_sections_test.go b/hugolib/site_sections_test.go index 81196be7f..2a4c39533 100644 --- a/hugolib/site_sections_test.go +++ b/hugolib/site_sections_test.go @@ -25,7 +25,6 @@ import ( ) func TestNestedSections(t *testing.T) { - var ( c = qt.New(t) cfg, fs = newTestCfg() @@ -139,7 +138,6 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} // > b,c c.Assert(getPage(p, "/empty1/b"), qt.IsNil) // No _index.md page. c.Assert(getPage(p, "/empty1/b/c"), qt.Not(qt.IsNil)) - }}, {"empty2", func(c *qt.C, p page.Page) { // > b,c,d where b and d have _index.md files. @@ -157,7 +155,6 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} c.Assert(cp.Eq(d), qt.Equals, false) c.Assert(cp.Eq(cp), qt.Equals, true) c.Assert(cp.Eq("asdf"), qt.Equals, false) - }}, {"empty3", func(c *qt.C, p page.Page) { // b,c,d with regular page in b @@ -166,7 +163,6 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} e3 := getPage(p, "/empty3/b/empty3") c.Assert(e3, qt.Not(qt.IsNil)) c.Assert(e3.File().LogicalName(), qt.Equals, "empty3.md") - }}, {"empty3", func(c *qt.C, p page.Page) { xxx := getPage(p, "/empty3/nil") @@ -234,7 +230,6 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} } c.Assert(p.Eq(p.CurrentSection()), qt.Equals, true) - }}, {"l1,l2_2", func(c *qt.C, p page.Page) { c.Assert(p.Title(), qt.Equals, "T22_-1") @@ -278,7 +273,6 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} isAncestor, err = nilp.IsAncestor(l1) c.Assert(err, qt.IsNil) c.Assert(isAncestor, qt.Equals, false) - }}, {"perm a,link", func(c *qt.C, p page.Page) { c.Assert(p.Title(), qt.Equals, "T9_-1") @@ -290,7 +284,6 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} last := p.Pages()[3] c.Assert(last.RelPermalink(), qt.Equals, "/perm-a/link/t1_5/") - }}, } @@ -335,7 +328,6 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} c.Assert(sectionWithSpace.RelPermalink(), qt.Equals, "/spaces-in-section/") th.assertFileContent("public/l1/l2/page/2/index.html", "L1/l2-IsActive: true", "PAG|T2_3|true") - } func TestNextInSectionNested(t *testing.T) { @@ -380,5 +372,4 @@ Next: {{ with .NextInSection }}{{ .RelPermalink }}{{ end }}| "Prev: /blog/cool/cool2/|", "Next: |") b.AssertFileContent("public/blog/cool/cool2/index.html", "Prev: |", "Next: /blog/cool/cool1/|") - } diff --git a/hugolib/site_stats_test.go b/hugolib/site_stats_test.go index 9c7bb240d..df1f64840 100644 --- a/hugolib/site_stats_test.go +++ b/hugolib/site_stats_test.go @@ -84,7 +84,8 @@ aliases: [/Ali%d] stats := []*helpers.ProcessingStats{ h.Sites[0].PathSpec.ProcessingStats, - h.Sites[1].PathSpec.ProcessingStats} + h.Sites[1].PathSpec.ProcessingStats, + } stats[0].Table(ioutil.Discard) stats[1].Table(ioutil.Discard) @@ -94,5 +95,4 @@ aliases: [/Ali%d] helpers.ProcessingStatsTable(&buff, stats...) c.Assert(buff.String(), qt.Contains, "Pages | 19 | 6") - } diff --git a/hugolib/site_test.go b/hugolib/site_test.go index a2b3a0451..922563420 100644 --- a/hugolib/site_test.go +++ b/hugolib/site_test.go @@ -47,7 +47,6 @@ func TestRenderWithInvalidTemplate(t *testing.T) { withTemplate := createWithTemplateFromNameValues("missing", templateMissingFunc) buildSingleSiteExpected(t, true, false, deps.DepsCfg{Fs: fs, Cfg: cfg, WithTemplate: withTemplate}, BuildCfg{}) - } func TestDraftAndFutureRender(t *testing.T) { @@ -70,7 +69,6 @@ func TestDraftAndFutureRender(t *testing.T) { for _, src := range sources { writeSource(t, fs, filepath.Join("content", src[0]), src[1]) - } return buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) @@ -105,7 +103,6 @@ func TestDraftAndFutureRender(t *testing.T) { if len(s.RegularPages()) != 4 { t.Fatal("Drafts or Future posts not included as expected") } - } func TestFutureExpirationRender(t *testing.T) { @@ -121,7 +118,6 @@ func TestFutureExpirationRender(t *testing.T) { for _, src := range sources { writeSource(t, fs, filepath.Join("content", src[0]), src[1]) - } return buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) @@ -174,7 +170,6 @@ func TestPageWithUnderScoreIndexInFilename(t *testing.T) { s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) c.Assert(len(s.RegularPages()), qt.Equals, 1) - } // Issue #957 @@ -188,7 +183,6 @@ func TestCrossrefs(t *testing.T) { } func doTestCrossrefs(t *testing.T, relative, uglyURLs bool) { - c := qt.New(t) baseURL := "http://foo/bar" @@ -257,7 +251,8 @@ THE END.`, refShortcode), deps.DepsCfg{ Fs: fs, Cfg: cfg, - WithTemplate: createWithTemplateFromNameValues("_default/single.html", "{{.Content}}")}, + WithTemplate: createWithTemplateFromNameValues("_default/single.html", "{{.Content}}"), + }, BuildCfg{}) c.Assert(len(s.RegularPages()), qt.Equals, 4) @@ -276,9 +271,7 @@ THE END.`, refShortcode), for _, test := range tests { th.assertFileContent(test.doc, test.expected) - } - } // Issue #939 @@ -291,7 +284,6 @@ func TestShouldAlwaysHaveUglyURLs(t *testing.T) { } func doTestShouldAlwaysHaveUglyURLs(t *testing.T, uglyURLs bool) { - cfg, fs := newTestCfg() c := qt.New(t) @@ -299,7 +291,8 @@ func doTestShouldAlwaysHaveUglyURLs(t *testing.T, uglyURLs bool) { cfg.Set("baseURL", "http://auth/bub") cfg.Set("blackfriday", map[string]interface{}{ - "plainIDAnchors": true}) + "plainIDAnchors": true, + }) cfg.Set("uglyURLs", uglyURLs) @@ -351,7 +344,6 @@ func doTestShouldAlwaysHaveUglyURLs(t *testing.T, uglyURLs bool) { t.Errorf("%s content expected:\n%q\ngot:\n%q", test.doc, test.expected, content) } } - } // Issue #3355 @@ -418,7 +410,6 @@ Main section page: {{ .RelPermalink }} } else { b.AssertFileContent("public/index.html", "mainSections: [blog]", "Main section page: /blog/page3/") } - }) } } @@ -501,7 +492,6 @@ func doTestSectionNaming(t *testing.T, canonify, uglify, pluralize bool) { th.assertFileContent(filepath.Join("public", test.doc), test.expected) } - } func TestAbsURLify(t *testing.T) { @@ -521,7 +511,6 @@ func TestAbsURLify(t *testing.T) { for _, src := range sources { writeSource(t, fs, filepath.Join("content", src[0]), src[1]) - } writeSource(t, fs, filepath.Join("layouts", "blue/single.html"), templateWithURLAbs) @@ -608,7 +597,6 @@ func TestOrderedPages(t *testing.T) { for _, src := range weightedSources { writeSource(t, fs, filepath.Join("content", src[0]), src[1]) - } s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) @@ -895,7 +883,6 @@ func setupLinkingMockSite(t *testing.T) *Site { map[string]interface{}{}) writeSourcesToSource(t, "content", fs, sources...) return buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) - } func TestRefLinking(t *testing.T) { @@ -945,14 +932,13 @@ func TestRefLinking(t *testing.T) { // try to confuse parsing {"embedded.dot.md", "", true, "/level2/level3/embedded.dot/"}, - //test empty link, as well as fragment only link + // test empty link, as well as fragment only link {"", "", true, ""}, } { - t.Run(fmt.Sprint(i), func(t *testing.T) { checkLinkCase(site, test.link, currentPage, test.relative, test.outputFormat, test.expected, t, i) - //make sure fragment links are also handled + // make sure fragment links are also handled checkLinkCase(site, test.link+"#intro", currentPage, test.relative, test.outputFormat, test.expected+"#intro", t, i) }) } @@ -983,11 +969,9 @@ func TestRefIssues(t *testing.T) { b.AssertFileContent("public/post/b1/index.html", `Content: <p>Ref: http://example.com/post/b2/</p>`) b.AssertFileContent("public/post/nested-a/content-a/index.html", `Content: http://example.com/post/nested-b/content-b/`) - } func TestClassCollector(t *testing.T) { - for _, minify := range []bool{false, true} { t.Run(fmt.Sprintf("minify-%t", minify), func(t *testing.T) { statsFilename := "hugo_stats.json" @@ -1053,9 +1037,7 @@ Some text. } } `) - }) - } } @@ -1102,7 +1084,6 @@ ABC. `) for _, lang := range []string{"en", "nb", "no", "sv"} { - for i := 100; i <= 999; i++ { b.WithContent(fmt.Sprintf("p%d.%s.md", i, lang), fmt.Sprintf("---\ntitle: p%s%d\n---", lang, i)) } @@ -1126,5 +1107,4 @@ ABC. b.Assert(els.Tags, qt.HasLen, 9) b.Assert(els.IDs, qt.HasLen, 1) } - } diff --git a/hugolib/site_url_test.go b/hugolib/site_url_test.go index c51285eb4..d668095b9 100644 --- a/hugolib/site_url_test.go +++ b/hugolib/site_url_test.go @@ -15,13 +15,12 @@ package hugolib import ( "fmt" + "html/template" "path/filepath" "testing" "github.com/gohugoio/hugo/resources/page" - "html/template" - qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/deps" ) @@ -52,7 +51,8 @@ func TestShouldNotAddTrailingSlashToBaseURL(t *testing.T) { {"http://base.com/", "http://base.com/"}, {"http://base.com/sub/", "http://base.com/sub/"}, {"http://base.com/sub", "http://base.com/sub"}, - {"http://base.com", "http://base.com"}} { + {"http://base.com", "http://base.com"}, + } { cfg, fs := newTestCfg() cfg.Set("baseURL", this.in) @@ -184,5 +184,4 @@ Do not go gentle into that good night. c.Assert(sect1.RelPermalink(), qt.Equals, "/ss1/") th.assertFileContent(filepath.Join("public", "ss1", "index.html"), "P1|URL: /ss1/|Next: /ss1/page/2/") th.assertFileContent(filepath.Join("public", "ss1", "page", "2", "index.html"), "P2|URL: /ss1/page/2/|Next: /ss1/page/3/") - } diff --git a/hugolib/sitemap_test.go b/hugolib/sitemap_test.go index 27fbf11d8..7302f6e62 100644 --- a/hugolib/sitemap_test.go +++ b/hugolib/sitemap_test.go @@ -14,9 +14,8 @@ package hugolib import ( - "testing" - "reflect" + "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" @@ -43,7 +42,6 @@ func TestSitemapOutput(t *testing.T) { } func doTestSitemapOutput(t *testing.T, internal bool) { - c := qt.New(t) cfg, fs := newTestCfg() cfg.Set("baseURL", "http://auth/bub/") @@ -82,7 +80,6 @@ func doTestSitemapOutput(t *testing.T, internal bool) { content := readDestination(th, th.Fs, outputSitemap) c.Assert(content, qt.Not(qt.Contains), "404") - } func TestParseSitemap(t *testing.T) { @@ -99,12 +96,10 @@ func TestParseSitemap(t *testing.T) { if !reflect.DeepEqual(expected, result) { t.Errorf("Got \n%v expected \n%v", result, expected) } - } // https://github.com/gohugoio/hugo/issues/5910 func TestSitemapOutputFormats(t *testing.T) { - b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithContent("blog/html-amp.md", ` diff --git a/hugolib/taxonomy_test.go b/hugolib/taxonomy_test.go index 4eeb92e06..dba4f4856 100644 --- a/hugolib/taxonomy_test.go +++ b/hugolib/taxonomy_test.go @@ -16,13 +16,12 @@ package hugolib import ( "fmt" "path/filepath" - - "github.com/gohugoio/hugo/resources/page" - "reflect" "strings" "testing" + "github.com/gohugoio/hugo/resources/page" + qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/deps" @@ -73,7 +72,6 @@ func TestTaxonomiesWithAndWithoutContentFile(t *testing.T) { } func doTestTaxonomiesWithAndWithoutContentFile(t *testing.T, uglyURLs bool) { - siteConfig := ` baseURL = "http://example.com/blog" uglyURLs = %t @@ -202,7 +200,6 @@ permalinkeds: // Issue #2977 b.AssertFileContent(pathFunc("public/empties/index.html"), "Taxonomy Term Page", "Empties") - } // https://github.com/gohugoio/hugo/issues/5513 @@ -285,7 +282,6 @@ title: "This is S3s" b.AssertFileContent("public/news/categories/index.html", "Taxonomy Term Page 1|News/Categories|Hello|https://example.com/news/categories/|") b.AssertFileContent("public/t1/t2/t3s/index.html", "Taxonomy Term Page 1|T1/T2/T3s|Hello|https://example.com/t1/t2/t3s/|") b.AssertFileContent("public/s1/s2/s3s/index.html", "Taxonomy Term Page 1|This is S3s|Hello|https://example.com/s1/s2/s3s/|") - } // https://github.com/gohugoio/hugo/issues/5719 @@ -329,7 +325,6 @@ Content. b.AssertFileContent("public/index.html", `<li><a href="http://example.com/tags/hugo-rocks/">Hugo Rocks!</a> 10</li>`) b.AssertFileContent("public/categories/index.html", `<li><a href="http://example.com/categories/this-is-cool/">This is Cool</a> 10</li>`) b.AssertFileContent("public/tags/index.html", `<li><a href="http://example.com/tags/rocks-i-say/">Rocks I say!</a> 10</li>`) - } // Issue 6213 @@ -361,7 +356,6 @@ categories: ["regular"] dra, _ := s.getPageNew(nil, "categories/draft") b.Assert(reg, qt.Not(qt.IsNil)) b.Assert(dra, qt.IsNil) - } func TestTaxonomiesIndexDraft(t *testing.T) { @@ -398,7 +392,6 @@ Content. b.AssertFileContentFn("public/index.html", func(s string) bool { return !strings.Contains(s, "categories") }) - } // https://github.com/gohugoio/hugo/issues/6927 @@ -442,7 +435,6 @@ NO HOME FOR YOU b.Assert(b.CheckExists("public/index.html"), qt.Equals, false) b.Assert(b.CheckExists("public/categories/index.html"), qt.Equals, false) b.Assert(b.CheckExists("public/posts/index.html"), qt.Equals, false) - } // https://github.com/gohugoio/hugo/issues/6173 @@ -470,7 +462,6 @@ categories: ["funny"] b.AssertFileContent("public/categories/index.html", `Resource: /categories/data.json|application/json`) b.AssertFileContent("public/categories/funny/index.html", `Resource: /categories/funny/funnydata.json|application/json`) - } func TestTaxonomiesRemoveOne(t *testing.T) { @@ -528,7 +519,6 @@ Len funny: 2 Cats:|/p2/| Funny:|/p1/| Funny:|/p2/|`) - } //https://github.com/gohugoio/hugo/issues/6590 @@ -579,7 +569,6 @@ Len categories.funny: 2 categories.funny:|/| categories.funny:|/blog/p1/| `) - } func TestTaxonomiesPageCollections(t *testing.T) { @@ -653,7 +642,6 @@ Category Paginator /categories/birds/|/categories/cats/|/categories/dogs/|/categ b.AssertFileContent("public/404.html", "\n404 Terms: :END\n\t") b.AssertFileContent("public/categories/funny/index.xml", `<link>http://example.com/section/p1/</link>`) b.AssertFileContent("public/categories/index.xml", `<link>http://example.com/categories/funny/</link>`) - } func TestTaxonomiesDirectoryOverlaps(t *testing.T) { @@ -705,5 +693,4 @@ abcdefgs: {{ template "print-page" $abcdefgs }}|IsAncestor: {{ $abcdefgs.IsAnces abc: /abcdefgs/abc/|abc|term|Parent: /abcdefgs/|CurrentSection: /abcdefgs/|FirstSection: /|IsAncestor: false|IsDescendant: true abcdefgs: /abcdefgs/|Abcdefgs|taxonomy|Parent: /|CurrentSection: /|FirstSection: /|IsAncestor: true|IsDescendant: false `) - } diff --git a/hugolib/template_test.go b/hugolib/template_test.go index 39f1b9e2e..769bcd4e6 100644 --- a/hugolib/template_test.go +++ b/hugolib/template_test.go @@ -51,7 +51,6 @@ func TestTemplateLookupOrder(t *testing.T) { func(t *testing.T) { writeSource(t, fs, filepath.Join("layouts", "section", "sect1-baseof.html"), `Base: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("layouts", "section", "sect1.html"), `{{define "main"}}sect{{ end }}`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "sect1", "index.html"), "Base: sect") @@ -62,7 +61,6 @@ func TestTemplateLookupOrder(t *testing.T) { func(t *testing.T) { writeSource(t, fs, filepath.Join("layouts", "baseof.html"), `Base: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("layouts", "index.html"), `{{define "main"}}index{{ end }}`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "index.html"), "Base: index") @@ -73,7 +71,6 @@ func TestTemplateLookupOrder(t *testing.T) { func(t *testing.T) { writeSource(t, fs, filepath.Join("layouts", "_default", "list-baseof.html"), `Base: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("layouts", "_default", "list.html"), `{{define "main"}}list{{ end }}`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "sect1", "index.html"), "Base: list") @@ -84,7 +81,6 @@ func TestTemplateLookupOrder(t *testing.T) { func(t *testing.T) { writeSource(t, fs, filepath.Join("layouts", "_default", "baseof.html"), `Base: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("layouts", "_default", "list.html"), `{{define "main"}}list{{ end }}`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "sect1", "index.html"), "Base: list") @@ -97,7 +93,6 @@ func TestTemplateLookupOrder(t *testing.T) { writeSource(t, fs, filepath.Join("layouts", "section", "sect1-baseof.html"), `Base: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("themes", "mytheme", "layouts", "section", "sect-baseof.html"), `Base Theme: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("layouts", "section", "sect1.html"), `{{define "main"}}sect{{ end }}`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "sect1", "index.html"), "Base: sect") @@ -109,7 +104,6 @@ func TestTemplateLookupOrder(t *testing.T) { cfg.Set("theme", "mytheme") writeSource(t, fs, filepath.Join("themes", "mytheme", "layouts", "section", "sect1-baseof.html"), `Base Theme: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("layouts", "section", "sect1.html"), `{{define "main"}}sect{{ end }}`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "sect1", "index.html"), "Base Theme: sect") @@ -123,7 +117,6 @@ func TestTemplateLookupOrder(t *testing.T) { writeSource(t, fs, filepath.Join("themes", "mytheme", "layouts", "_default", "baseof.html"), `Base Theme: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("themes", "mytheme", "layouts", "_default", "list.html"), `{{define "main"}}list{{ end }}`) writeSource(t, fs, filepath.Join("themes", "mytheme", "layouts", "index.html"), `{{define "main"}}index{{ end }}`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "sect1", "index.html"), "Base: list") @@ -136,7 +129,6 @@ func TestTemplateLookupOrder(t *testing.T) { cfg.Set("theme", "mytheme") writeSource(t, fs, filepath.Join("themes", "mytheme", "layouts", "_default", "baseof.html"), `Base Theme: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("themes", "mytheme", "layouts", "_default", "list.html"), `{{define "main"}}list{{ end }}`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "sect1", "index.html"), "Base Theme: list") @@ -158,7 +150,6 @@ func TestTemplateLookupOrder(t *testing.T) { // sect2 with list template in /section writeSource(t, fs, filepath.Join("themes", "mytheme", "layouts", "section", "sect2.html"), `sect2 list`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "sect1", "index.html"), "sect list") @@ -170,7 +161,6 @@ func TestTemplateLookupOrder(t *testing.T) { // Issue #2995 "Test section list and single template selection with base template", func(t *testing.T) { - writeSource(t, fs, filepath.Join("layouts", "_default", "baseof.html"), `Base Default: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("layouts", "sect1", "baseof.html"), `Base Sect1: {{block "main" .}}block{{end}}`) writeSource(t, fs, filepath.Join("layouts", "section", "sect2-baseof.html"), `Base Sect2: {{block "main" .}}block{{end}}`) @@ -183,7 +173,6 @@ func TestTemplateLookupOrder(t *testing.T) { // sect2 with list template in /section writeSource(t, fs, filepath.Join("layouts", "section", "sect2.html"), `{{define "main"}}sect2 list{{ end }}`) - }, func(t *testing.T) { th.assertFileContent(filepath.Join("public", "sect1", "index.html"), "Base Sect1", "sect1 list") @@ -214,7 +203,7 @@ Some content this.setup(t) buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) - //helpers.PrintFs(s.BaseFs.Layouts.Fs, "", os.Stdout) + // helpers.PrintFs(s.BaseFs.Layouts.Fs, "", os.Stdout) this.assert(t) }) @@ -223,7 +212,6 @@ Some content // https://github.com/gohugoio/hugo/issues/4895 func TestTemplateBOM(t *testing.T) { - b := newTestSitesBuilder(t).WithSimpleConfigFile() bom := "\ufeff" @@ -242,7 +230,6 @@ Page Content b.CreateSites().Build(BuildCfg{}) b.AssertFileContent("public/page/index.html", "Base: Hi!?") - } func TestTemplateManyBaseTemplates(t *testing.T) { @@ -278,7 +265,6 @@ Base %d: {{ block "main" . }}FOO{{ end }} id := i + 1 b.AssertFileContent(fmt.Sprintf("public/page%d/index.html", id), fmt.Sprintf(`Base %d: %d`, id, id)) } - } // https://github.com/gohugoio/hugo/issues/6790 @@ -315,7 +301,6 @@ title: The Page b.AssertFileContent("public/blog/p1/index.html", `single`) b.AssertFileContent("public/blog/index.html", `list`) - } // https://github.com/gohugoio/hugo/issues/6816 @@ -336,7 +321,6 @@ func TestTemplateBaseWithComment(t *testing.T) { b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `Base: Bonjour`) - } func TestTemplateLookupSite(t *testing.T) { @@ -389,13 +373,10 @@ title: My Page b.AssertFileContent("public/fr/index.html", `Baseof fr: Main Home Fr`) b.AssertFileContent("public/en/mysection/index.html", `Baseof mysection: Main Default List`) b.AssertFileContent("public/en/mysection/p1/index.html", `Baseof mysection: Main Default Single`) - }) - } func TestTemplateFuncs(t *testing.T) { - b := newTestSitesBuilder(t).WithDefaultMultiSiteConfig() homeTpl := `Site: {{ site.Language.Lang }} / {{ .Site.Language.Lang }} / {{ site.BaseURL }} @@ -419,11 +400,9 @@ Hugo: {{ hugo.Generator }} "Sites: en", "Hugo: <meta name=\"generator\" content=\"Hugo", ) - } func TestPartialWithReturn(t *testing.T) { - c := qt.New(t) newBuilder := func(t testing.TB) *sitesBuilder { @@ -450,7 +429,6 @@ func TestPartialWithReturn(t *testing.T) { ) return b - } c.Run("Return", func(c *qt.C) { @@ -478,7 +456,6 @@ adder: 70: 70 complex: 80: 80 `, ) - }) c.Run("Zero argument", func(c *qt.C) { @@ -495,9 +472,7 @@ add42: fail: {{ partial "add42.tpl" 0 }} e := b.CreateSites().BuildE(BuildCfg{}) b.Assert(e, qt.Not(qt.IsNil)) - }) - } func TestPartialCached(t *testing.T) { @@ -600,7 +575,6 @@ title: P1 idset := make(map[identity.Identity]bool) collectIdentities(idset, templ.(tpl.Info)) b.Assert(idset, qt.HasLen, 11) - } func TestTemplateGoIssues(t *testing.T) { @@ -636,7 +610,6 @@ func ident(level int) string { } func TestPartialInline(t *testing.T) { - b := newTestSitesBuilder(t) b.WithContent("p1.md", "") @@ -668,11 +641,9 @@ P2: {{ $p2 }} P1: Inline: p1 P2: 32`, ) - } func TestPartialInlineBase(t *testing.T) { - b := newTestSitesBuilder(t) b.WithContent("p1.md", "") @@ -712,12 +683,10 @@ P2: 32 P3: Inline: p3 `, ) - } // https://github.com/gohugoio/hugo/issues/7478 func TestBaseWithAndWithoutDefine(t *testing.T) { - b := newTestSitesBuilder(t) b.WithContent("p1.md", "---\ntitle: P\n---\nContent") @@ -755,5 +724,4 @@ This is home main This is single main `, ) - } diff --git a/hugolib/testhelpers_test.go b/hugolib/testhelpers_test.go index 5b825cd1e..726930721 100644 --- a/hugolib/testhelpers_test.go +++ b/hugolib/testhelpers_test.go @@ -1,14 +1,20 @@ package hugolib import ( + "bytes" + "fmt" "image/jpeg" "io" "math/rand" + "os" "path/filepath" + "regexp" "runtime" "sort" "strconv" + "strings" "testing" + "text/template" "time" "unicode/utf8" @@ -22,12 +28,6 @@ import ( "github.com/gohugoio/hugo/parser" "github.com/pkg/errors" - "bytes" - "fmt" - "regexp" - "strings" - "text/template" - "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/config" @@ -41,8 +41,6 @@ import ( "github.com/gohugoio/hugo/tpl" "github.com/spf13/viper" - "os" - "github.com/gohugoio/hugo/resources/resource" qt "github.com/frankban/quicktest" @@ -122,8 +120,10 @@ func newTestSitesBuilder(t testing.TB) *sitesBuilder { Separator: " ", } - return &sitesBuilder{T: t, C: qt.New(t), Fs: fs, configFormat: "toml", - dumper: litterOptions, rnd: rand.New(rand.NewSource(time.Now().Unix()))} + return &sitesBuilder{ + T: t, C: qt.New(t), Fs: fs, configFormat: "toml", + dumper: litterOptions, rnd: rand.New(rand.NewSource(time.Now().Unix())), + } } func newTestSitesBuilderFromDepsCfg(t testing.TB, d deps.DepsCfg) *sitesBuilder { @@ -141,7 +141,6 @@ func newTestSitesBuilderFromDepsCfg(t testing.TB, d deps.DepsCfg) *sitesBuilder b.WithWorkingDir(workingDir) return b.WithViper(d.Cfg.(*viper.Viper)) - } func (s *sitesBuilder) Running() *sitesBuilder { @@ -289,7 +288,7 @@ func (s *sitesBuilder) WithSimpleConfigFileAndSettings(settings interface{}) *si } func (s *sitesBuilder) WithDefaultMultiSiteConfig() *sitesBuilder { - var defaultMultiSiteConfig = ` + defaultMultiSiteConfig := ` baseURL = "http://example.com/blog" paginate = 1 @@ -347,7 +346,6 @@ lag = "lag" ` + commonConfigSections return s.WithConfigFile("toml", defaultMultiSiteConfig) - } func (s *sitesBuilder) WithSunset(in string) { @@ -450,7 +448,7 @@ func (s *sitesBuilder) writeFilePairs(folder string, files []filenameContent) *s // That file system is backed by a map so not sure how this helps, but some // randomness in tests doesn't hurt. // TODO(bep) this turns out to be more confusing than helpful. - //s.rnd.Shuffle(len(files), func(i, j int) { files[i], files[j] = files[j], files[i] }) + // s.rnd.Shuffle(len(files), func(i, j int) { files[i], files[j] = files[j], files[i] }) for _, fc := range files { target := folder @@ -487,11 +485,10 @@ func (s *sitesBuilder) LoadConfig() error { Fs: s.Fs.Source, Logger: s.logger, Environ: s.environ, - Filename: "config." + s.configFormat}, func(cfg config.Provider) error { - + Filename: "config." + s.configFormat, + }, func(cfg config.Provider) error { return nil }) - if err != nil { return err } @@ -572,7 +569,6 @@ func (s *sitesBuilder) BuildFail(cfg BuildCfg) *sitesBuilder { } func (s *sitesBuilder) changeEvents() []fsnotify.Event { - var events []fsnotify.Event for _, v := range s.changedFiles { @@ -620,7 +616,6 @@ func (s *sitesBuilder) build(cfg BuildCfg, shouldFail bool) *sitesBuilder { } func (s *sitesBuilder) addDefaults() { - var ( contentTemplate = `--- title: doc1 @@ -846,7 +841,6 @@ func (th testHelper) replaceDefaultContentLanguageValue(value string) string { if !defaultInSubDir { value = strings.Replace(value, replace, "", 1) - } return value } @@ -864,7 +858,6 @@ func newTestCfgBasic() (*viper.Viper, *hugofs.Fs) { fs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(mm), v) return v, fs - } func newTestCfg(withConfig ...func(cfg config.Provider) error) (*viper.Viper, *hugofs.Fs) { @@ -888,7 +881,6 @@ func newTestCfg(withConfig ...func(cfg config.Provider) error) (*viper.Viper, *h fs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(mm), v) return v, fs - } func newTestSitesFromConfig(t testing.TB, afs afero.Fs, tomlConfig string, layoutPathContentPairs ...string) (testHelper, *HugoSites) { @@ -919,7 +911,6 @@ func newTestSitesFromConfig(t testing.TB, afs afero.Fs, tomlConfig string, layou } func createWithTemplateFromNameValues(additionalTemplates ...string) func(templ tpl.TemplateManager) error { - return func(templ tpl.TemplateManager) error { for i := 0; i < len(additionalTemplates); i += 2 { err := templ.AddTemplate(additionalTemplates[i], additionalTemplates[i+1]) @@ -1059,7 +1050,6 @@ func skipSymlink(t *testing.T) { if runtime.GOOS == "windows" && os.Getenv("CI") == "" { t.Skip("skip symlink test on local Windows (needs admin)") } - } func captureStderr(f func() error) (string, error) { diff --git a/identity/identity.go b/identity/identity.go index b002f34f0..052740675 100644 --- a/identity/identity.go +++ b/identity/identity.go @@ -26,7 +26,6 @@ func NewPathIdentity(typ, pat string) PathIdentity { type Identities map[Identity]Provider func (ids Identities) search(depth int, id Identity) Provider { - if v, found := ids[id.GetIdentity()]; found { return v } diff --git a/identity/identity_test.go b/identity/identity_test.go index c315df1e7..baf2628bb 100644 --- a/identity/identity_test.go +++ b/identity/identity_test.go @@ -33,14 +33,12 @@ func TestIdentityManager(t *testing.T) { } func BenchmarkIdentityManager(b *testing.B) { - createIds := func(num int) []Identity { ids := make([]Identity, num) for i := 0; i < num; i++ { ids[i] = testIdentity{name: fmt.Sprintf("id%d", i)} } return ids - } b.Run("Add", func(b *testing.B) { @@ -75,9 +73,7 @@ func BenchmarkIdentityManager(b *testing.B) { id := im.Search(testIdentity{name: name}) c.Assert(id.GetIdentity().Name(), qt.Equals, name) } - }) - } type testIdentity struct { diff --git a/langs/config.go b/langs/config.go index 3afd15df0..3b1da89ec 100644 --- a/langs/config.go +++ b/langs/config.go @@ -35,7 +35,6 @@ type LanguagesConfig struct { } func LoadLanguageSettings(cfg config.Provider, oldLangs Languages) (c LanguagesConfig, err error) { - defaultLang := strings.ToLower(cfg.GetString("defaultContentLanguage")) if defaultLang == "" { defaultLang = "en" @@ -160,7 +159,6 @@ func LoadLanguageSettings(cfg config.Provider, oldLangs Languages) (c LanguagesC return c, errors.New("baseURL must be set on all or none of the languages") } } - } return c, nil @@ -172,7 +170,6 @@ func toSortedLanguages(cfg config.Provider, l map[string]interface{}) (Languages for lang, langConf := range l { langsMap, err := maps.ToStringMapE(langConf) - if err != nil { return nil, fmt.Errorf("Language config is not a map: %T", langConf) } diff --git a/langs/i18n/i18n.go b/langs/i18n/i18n.go index 31cb5d732..dab620be6 100644 --- a/langs/i18n/i18n.go +++ b/langs/i18n/i18n.go @@ -27,9 +27,7 @@ import ( type translateFunc func(translationID string, templateData interface{}) string -var ( - i18nWarningLogger = helpers.NewDistinctFeedbackLogger() -) +var i18nWarningLogger = helpers.NewDistinctFeedbackLogger() // Translator handles i18n translations. type Translator struct { @@ -60,7 +58,6 @@ func (t Translator) Func(lang string) translateFunc { return func(translationID string, args interface{}) string { return "" } - } func (t Translator) initFuncs(bndl *i18n.Bundle) { @@ -72,7 +69,6 @@ func (t Translator) initFuncs(bndl *i18n.Bundle) { currentLangKey := strings.ToLower(strings.TrimPrefix(currentLangStr, artificialLangTagPrefix)) localizer := i18n.NewLocalizer(bndl, currentLangStr) t.translateFuncs[currentLangKey] = func(translationID string, templateData interface{}) string { - var pluralCount interface{} if templateData != nil { diff --git a/langs/i18n/i18n_test.go b/langs/i18n/i18n_test.go index fa78f708c..7b5a10d67 100644 --- a/langs/i18n/i18n_test.go +++ b/langs/i18n/i18n_test.go @@ -244,7 +244,6 @@ func doTestI18nTranslate(t testing.TB, test i18nTest, cfg config.Provider) strin tp := prepareTranslationProvider(t, test, cfg) f := tp.t.Func(test.lang) return f(test.id, test.args) - } func prepareTranslationProvider(t testing.TB, test i18nTest, cfg config.Provider) *TranslationProvider { @@ -298,7 +297,6 @@ func getConfig() *viper.Viper { v.Set("allModules", modules.Modules{mod}) return v - } func TestI18nTranslate(t *testing.T) { @@ -339,5 +337,4 @@ func BenchmarkI18nTranslate(b *testing.B) { } }) } - } diff --git a/langs/i18n/translationProvider.go b/langs/i18n/translationProvider.go index 07bd9219a..302ca84c6 100644 --- a/langs/i18n/translationProvider.go +++ b/langs/i18n/translationProvider.go @@ -73,7 +73,6 @@ func (tp *TranslationProvider) Update(d *deps.Deps) error { d.Translate = tp.t.Func(d.Language.Lang) return nil - } const artificialLangTagPrefix = "art-x-" @@ -138,5 +137,4 @@ func errWithFileContext(inerr error, r source.File) error { herrors.SimpleLineMatcher) return err - } diff --git a/langs/language.go b/langs/language.go index 874bd3020..9fa22b05a 100644 --- a/langs/language.go +++ b/langs/language.go @@ -122,7 +122,6 @@ func (l Languages) Less(i, j int) bool { } return wj == 0 || wi < wj - } func (l Languages) Swap(i, j int) { l[i], l[j] = l[j], l[i] } @@ -256,5 +255,4 @@ func (l *Language) IsSet(key string) bool { } } return l.Cfg.IsSet(key) - } diff --git a/lazy/init.go b/lazy/init.go index 7f6c5b08c..e2e70072e 100644 --- a/lazy/init.go +++ b/lazy/init.go @@ -111,7 +111,6 @@ func (ini *Init) Do() (interface{}, error) { ini.wait() return ini.out, ini.err - } // TODO(bep) investigate if we can use sync.Cond for this. @@ -189,7 +188,6 @@ func (ini *Init) withTimeout(timeout time.Duration, f func(ctx context.Context) case ve := <-c: return ve.v, ve.err } - } type verr struct { diff --git a/lazy/init_test.go b/lazy/init_test.go index 772081b56..2051f6b1a 100644 --- a/lazy/init_test.go +++ b/lazy/init_test.go @@ -98,7 +98,6 @@ func TestInit(t *testing.T) { } _, err = branch1_2.Do() c.Assert(err, qt.IsNil) - }(i) wg.Wait() @@ -106,7 +105,6 @@ func TestInit(t *testing.T) { c.Assert(result, qt.Equals, "root(1)|root(2)|branch_1|branch_1_1|branch_1_2|branch_1_2_1|") } - } func TestInitAddWithTimeout(t *testing.T) { @@ -142,7 +140,6 @@ func TestInitAddWithTimeoutTimeout(t *testing.T) { c.Assert(err.Error(), qt.Contains, "timed out") time.Sleep(1 * time.Second) - } func TestInitAddWithTimeoutError(t *testing.T) { @@ -204,7 +201,6 @@ func TestInitBranchOrder(t *testing.T) { // V1 is A ab := state.V1 + "B" state.Add2(ab) - })) } diff --git a/lazy/once.go b/lazy/once.go index c434bfa0b..bdce12c33 100644 --- a/lazy/once.go +++ b/lazy/once.go @@ -51,7 +51,6 @@ func (t *onceMore) Do(f func()) { } defer atomic.StoreUint32(&t.done, 1) f() - } func (t *onceMore) InProgress() bool { diff --git a/livereload/livereload.go b/livereload/livereload.go index 92214b1f1..145cc25ea 100644 --- a/livereload/livereload.go +++ b/livereload/livereload.go @@ -77,7 +77,8 @@ var upgrader = &websocket.Upgrader{ return h1 == h2 }, - ReadBufferSize: 1024, WriteBufferSize: 1024} + ReadBufferSize: 1024, WriteBufferSize: 1024, +} // Handler is a HandlerFunc handling the livereload // Websocket interaction. diff --git a/magefile.go b/magefile.go index 02e49b66e..16f630abc 100644 --- a/magefile.go +++ b/magefile.go @@ -45,7 +45,6 @@ func init() { func runWith(env map[string]string, cmd string, inArgs ...interface{}) error { s := argsToStrings(inArgs...) return sh.RunWith(env, cmd, s...) - } // Build hugo binary @@ -29,5 +29,4 @@ func main() { } os.Exit(-1) } - } diff --git a/markup/asciidocext/convert.go b/markup/asciidocext/convert.go index a92b6f9e3..e2e5b7865 100644 --- a/markup/asciidocext/convert.go +++ b/markup/asciidocext/convert.go @@ -96,7 +96,7 @@ func (a *asciidocConverter) getAsciidocContent(src []byte, ctx converter.Documen } func (a *asciidocConverter) parseArgs(ctx converter.DocumentContext) []string { - var cfg = a.cfg.MarkupConfig.AsciidocExt + cfg := a.cfg.MarkupConfig.AsciidocExt args := []string{} args = a.appendArg(args, "-b", cfg.Backend, asciidocext_config.CliDefault.Backend, asciidocext_config.AllowedBackend) @@ -137,7 +137,6 @@ func (a *asciidocConverter) parseArgs(ctx converter.DocumentContext) []string { file := filepath.Base(ctx.Filename) if a.cfg.Cfg.GetBool("uglyUrls") || file == "_index.adoc" || file == "index.adoc" { outDir, err = filepath.Abs(filepath.Dir(filepath.Join(destinationDir, ctx.DocumentName))) - } else { postDir := "" page, ok := ctx.Document.(pageSubset) diff --git a/markup/asciidocext/convert_test.go b/markup/asciidocext/convert_test.go index 0e7c93c45..fa3aef404 100644 --- a/markup/asciidocext/convert_test.go +++ b/markup/asciidocext/convert_test.go @@ -246,7 +246,6 @@ func TestAsciidoctorAttributes(t *testing.T) { c.Assert(args[2], qt.Equals, "-a") c.Assert(expectedValues[args[3]], qt.Equals, true) c.Assert(args[4], qt.Equals, "--no-header-footer") - } func TestConvert(t *testing.T) { diff --git a/markup/blackfriday/convert.go b/markup/blackfriday/convert.go index d844c5554..b786e29de 100644 --- a/markup/blackfriday/convert.go +++ b/markup/blackfriday/convert.go @@ -52,7 +52,6 @@ func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) cfg: cfg, }, nil }), nil - } type blackfridayConverter struct { @@ -125,7 +124,6 @@ func (c *blackfridayConverter) getHTMLRenderer(renderTOC bool) blackfriday.Rende } func getFlags(renderTOC bool, cfg blackfriday_config.Config) int { - var flags int if renderTOC { diff --git a/markup/blackfriday/convert_test.go b/markup/blackfriday/convert_test.go index d2d8d927e..414905a76 100644 --- a/markup/blackfriday/convert_test.go +++ b/markup/blackfriday/convert_test.go @@ -129,7 +129,7 @@ func TestGetAllFlags(t *testing.T) { actualFlags := getFlags(false, b) var expectedFlags int - //OR-ing flags together... + // OR-ing flags together... for _, d := range allFlags { expectedFlags |= d.testFlag } diff --git a/markup/converter/converter.go b/markup/converter/converter.go index 231527441..d7e3d4639 100644 --- a/markup/converter/converter.go +++ b/markup/converter/converter.go @@ -130,6 +130,4 @@ type RenderContext struct { RenderHooks *hooks.Renderers } -var ( - FeatureRenderHooks = identity.NewPathIdentity("markup", "renderingHooks") -) +var FeatureRenderHooks = identity.NewPathIdentity("markup", "renderingHooks") diff --git a/markup/goldmark/autoid.go b/markup/goldmark/autoid.go index 1ca1ba5e0..04313269c 100644 --- a/markup/goldmark/autoid.go +++ b/markup/goldmark/autoid.go @@ -125,7 +125,6 @@ func (ids *idFactory) Generate(value []byte, kind ast.NodeKind) []byte { } ids.vals[buf.String()] = struct{}{} - }) } diff --git a/markup/goldmark/autoid_test.go b/markup/goldmark/autoid_test.go index 7acae9f47..0bdb63c12 100644 --- a/markup/goldmark/autoid_test.go +++ b/markup/goldmark/autoid_test.go @@ -91,7 +91,6 @@ func TestSanitizeAnchorNameAsciiOnly(t *testing.T) { c.Assert(sanitizeAnchorNameString("god is神真美好 good", goldmark_config.AutoHeadingIDTypeGitHubAscii), qt.Equals, "god-is-good") c.Assert(sanitizeAnchorNameString("Resumé", goldmark_config.AutoHeadingIDTypeGitHubAscii), qt.Equals, "resume") - } func TestSanitizeAnchorNameBlackfriday(t *testing.T) { @@ -106,7 +105,6 @@ func BenchmarkSanitizeAnchorName(b *testing.B) { result := sanitizeAnchorName(input, goldmark_config.AutoHeadingIDTypeGitHub) if len(result) != 24 { b.Fatalf("got %d", len(result)) - } } } @@ -118,7 +116,6 @@ func BenchmarkSanitizeAnchorNameAsciiOnly(b *testing.B) { result := sanitizeAnchorName(input, goldmark_config.AutoHeadingIDTypeGitHubAscii) if len(result) != 12 { b.Fatalf("got %d", len(result)) - } } } @@ -130,7 +127,6 @@ func BenchmarkSanitizeAnchorNameBlackfriday(b *testing.B) { result := sanitizeAnchorName(input, goldmark_config.AutoHeadingIDTypeBlackfriday) if len(result) != 24 { b.Fatalf("got %d", len(result)) - } } } diff --git a/markup/goldmark/convert.go b/markup/goldmark/convert.go index 2a66cc184..50e7bcb8a 100644 --- a/markup/goldmark/convert.go +++ b/markup/goldmark/convert.go @@ -62,9 +62,7 @@ func (p provide) New(cfg converter.ProviderConfig) (converter.Provider, error) { }), nil } -var ( - _ converter.AnchorNameSanitizer = (*goldmarkConverter)(nil) -) +var _ converter.AnchorNameSanitizer = (*goldmarkConverter)(nil) type goldmarkConverter struct { md goldmark.Markdown @@ -156,7 +154,6 @@ func newMarkdown(pcfg converter.ProviderConfig) goldmark.Markdown { ) return md - } var _ identity.IdentitiesProvider = (*converterResult)(nil) @@ -267,7 +264,6 @@ func (c *goldmarkConverter) Convert(ctx converter.RenderContext) (result convert ids: rcx.ids.GetIdentities(), toc: pctx.TableOfContents(), }, nil - } var featureSet = map[identity.Identity]bool{ @@ -329,7 +325,6 @@ func newHighlighting(cfg highlight.Config) goldmark.Extender { } w.WriteString("</div>") - }), ) } diff --git a/markup/goldmark/convert_test.go b/markup/goldmark/convert_test.go index 984adef0d..f105afdc4 100644 --- a/markup/goldmark/convert_test.go +++ b/markup/goldmark/convert_test.go @@ -31,7 +31,6 @@ import ( ) func convert(c *qt.C, mconf markup_config.Config, content string) converter.Result { - p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: mconf, @@ -163,7 +162,6 @@ description c.Assert(ok, qt.Equals, true) tocHTML := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(tocHTML, qt.Contains, "TableOfContents") - } func TestConvertAutoIDAsciiOnly(t *testing.T) { @@ -212,7 +210,6 @@ func TestConvertIssues(t *testing.T) { 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) { @@ -257,7 +254,6 @@ LINE5 </code></pre></div>`) result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre><code class=\"language-unknown\" data-lang=\"unknown\">echo "Hugo Rocks!"\n</code></pre>") - }) c.Run("Highlight lines, default config", func(c *qt.C) { diff --git a/markup/goldmark/render_hooks.go b/markup/goldmark/render_hooks.go index c541cbba4..f17e4e139 100644 --- a/markup/goldmark/render_hooks.go +++ b/markup/goldmark/render_hooks.go @@ -115,7 +115,6 @@ func (r *hookedRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) // https://github.com/yuin/goldmark/blob/b611cd333a492416b56aa8d94b04a67bf0096ab2/renderer/html/html.go#L404 func (r *hookedRenderer) RenderAttributes(w util.BufWriter, node ast.Node) { - for _, attr := range node.Attributes() { _, _ = w.WriteString(" ") _, _ = w.Write(attr.Name) @@ -189,7 +188,6 @@ func (r *hookedRenderer) renderImage(w util.BufWriter, source []byte, node ast.N ctx.AddIdentity(h.ImageRenderer) return ast.WalkContinue, err - } // Fall back to the default Goldmark render funcs. Method below borrowed from: diff --git a/markup/goldmark/toc_test.go b/markup/goldmark/toc_test.go index 464441335..f8fcf79d4 100644 --- a/markup/goldmark/toc_test.go +++ b/markup/goldmark/toc_test.go @@ -53,7 +53,8 @@ And then some. p, err := Provider.New( converter.ProviderConfig{ MarkupConfig: markup_config.Default, - Logger: loggers.NewErrorLogger()}) + Logger: loggers.NewErrorLogger(), + }) c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) diff --git a/markup/highlight/config.go b/markup/highlight/config.go index a7c5ab4cb..1bee58dc5 100644 --- a/markup/highlight/config.go +++ b/markup/highlight/config.go @@ -71,7 +71,7 @@ func (cfg Config) ToHTMLOptions() []html.Option { if cfg.LineAnchors != "" { lineAnchors = cfg.LineAnchors + "-" } - var options = []html.Option{ + options := []html.Option{ html.TabWidth(cfg.TabWidth), html.WithLineNumbers(cfg.LineNos), html.BaseLineNumber(cfg.LineNoStart), @@ -126,7 +126,6 @@ func ApplyLegacyConfig(cfg config.Provider, conf *Config) error { } return nil - } func parseOptions(in string) (map[string]interface{}, error) { @@ -199,5 +198,4 @@ func hlLinesToRanges(startLine int, s string) ([][2]int, error) { ranges = append(ranges, r) } return ranges, nil - } diff --git a/markup/highlight/config_test.go b/markup/highlight/config_test.go index 0d4bb2f97..3c3747622 100644 --- a/markup/highlight/config_test.go +++ b/markup/highlight/config_test.go @@ -40,7 +40,6 @@ func TestConfig(t *testing.T) { c.Assert(cfg.CodeFences, qt.Equals, false) c.Assert(cfg.LineNos, qt.Equals, true) c.Assert(cfg.LineNumbersInTable, qt.Equals, false) - }) c.Run("parseOptions", func(c *qt.C) { @@ -54,6 +53,5 @@ func TestConfig(t *testing.T) { c.Assert(cfg.LineNumbersInTable, qt.Equals, false) c.Assert(cfg.LineNoStart, qt.Equals, 32) c.Assert(cfg.Hl_Lines, qt.Equals, "3-8 10-20") - }) } diff --git a/markup/highlight/highlight_test.go b/markup/highlight/highlight_test.go index 228d5e8c9..eb8ba3e96 100644 --- a/markup/highlight/highlight_test.go +++ b/markup/highlight/highlight_test.go @@ -46,7 +46,6 @@ User-Agent: foo c.Assert(result, qt.Equals, `<div class="highlight"><pre class="chroma"><code class="language-bash" data-lang="bash"><span class="nb">echo</span> <span class="s2">"Hugo Rocks!"</span></code></pre></div>`) result, _ = h.Highlight(`echo "Hugo Rocks!"`, "unknown", "") c.Assert(result, qt.Equals, `<pre><code class="language-unknown" data-lang="unknown">echo "Hugo Rocks!"</code></pre>`) - }) c.Run("Highlight lines, default config", func(c *qt.C) { @@ -147,5 +146,4 @@ User-Agent: foo c.Assert(result, qt.Contains, "hello") c.Assert(result, qt.Contains, "}") }) - } diff --git a/markup/internal/external.go b/markup/internal/external.go index fc7fddb23..e8f86ae94 100644 --- a/markup/internal/external.go +++ b/markup/internal/external.go @@ -12,7 +12,6 @@ func ExternallyRenderContent( cfg converter.ProviderConfig, ctx converter.DocumentContext, content []byte, path string, args []string) []byte { - logger := cfg.Logger cmd := exec.Command(path, args...) cmd.Stdin = bytes.NewReader(content) diff --git a/markup/markup.go b/markup/markup.go index dd4148128..31fa6b0f7 100644 --- a/markup/markup.go +++ b/markup/markup.go @@ -97,7 +97,7 @@ func NewConverterProvider(cfg converter.ProviderConfig) (ConverterProvider, erro type ConverterProvider interface { Get(name string) converter.Provider - //Default() converter.Provider + // Default() converter.Provider GetMarkupConfig() markup_config.Config Highlight(code, lang, optsStr string) (string, error) } diff --git a/markup/markup_config/config.go b/markup/markup_config/config.go index a42556c2b..376350c95 100644 --- a/markup/markup_config/config.go +++ b/markup/markup_config/config.go @@ -83,7 +83,6 @@ func applyLegacyConfig(cfg config.Provider, conf *Config) error { } return nil - } var Default = Config{ diff --git a/markup/markup_config/config_test.go b/markup/markup_config/config_test.go index fac4948d6..89da62bab 100644 --- a/markup/markup_config/config_test.go +++ b/markup/markup_config/config_test.go @@ -73,5 +73,4 @@ func TestConfig(t *testing.T) { c.Assert(conf.Highlight.CodeFences, qt.Equals, true) c.Assert(conf.Highlight.GuessSyntax, qt.Equals, true) }) - } diff --git a/markup/markup_test.go b/markup/markup_test.go index 314a941de..6e7fe2059 100644 --- a/markup/markup_test.go +++ b/markup/markup_test.go @@ -47,5 +47,4 @@ func TestConverterRegistry(t *testing.T) { checkName("pandoc") checkName("org") checkName("blackfriday") - } diff --git a/markup/mmark/convert.go b/markup/mmark/convert.go index 0682ad276..b4cc8b096 100644 --- a/markup/mmark/convert.go +++ b/markup/mmark/convert.go @@ -51,7 +51,6 @@ func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) cfg: cfg, }, nil }), nil - } type mmarkConverter struct { @@ -74,7 +73,6 @@ func getHTMLRenderer( ctx converter.DocumentContext, cfg blackfriday_config.Config, pcfg converter.ProviderConfig) mmark.Renderer { - var ( flags int documentID string @@ -99,7 +97,6 @@ func getHTMLRenderer( Config: pcfg, Renderer: mmark.HtmlRendererWithParameters(htmlFlags, "", "", renderParameters), } - } func getMmarkExtensions(cfg blackfriday_config.Config) int { diff --git a/markup/mmark/convert_test.go b/markup/mmark/convert_test.go index 3945f80da..01d3e8cbb 100644 --- a/markup/mmark/convert_test.go +++ b/markup/mmark/convert_test.go @@ -29,7 +29,7 @@ import ( func TestGetMmarkExtensions(t *testing.T) { b := blackfriday_config.Default - //TODO: This is doing the same just with different marks... + // TODO: This is doing the same just with different marks... type data struct { testFlag int } diff --git a/markup/pandoc/convert.go b/markup/pandoc/convert.go index 074e97d96..bbf619ce6 100644 --- a/markup/pandoc/convert.go +++ b/markup/pandoc/convert.go @@ -36,7 +36,6 @@ func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) cfg: cfg, }, nil }), nil - } type pandocConverter struct { diff --git a/markup/rst/convert.go b/markup/rst/convert.go index cbc15c81a..c397bf5fe 100644 --- a/markup/rst/convert.go +++ b/markup/rst/convert.go @@ -81,7 +81,7 @@ func (c *rstConverter) getRstContent(src []byte, ctx converter.DocumentContext) // TODO(bep) check if rst2html has a body only option. bodyStart := bytes.Index(result, []byte("<body>\n")) if bodyStart < 0 { - bodyStart = -7 //compensate for length + bodyStart = -7 // compensate for length } bodyEnd := bytes.Index(result, []byte("\n</body>")) diff --git a/markup/tableofcontents/tableofcontents.go b/markup/tableofcontents/tableofcontents.go index 9f1124233..b7e630d6f 100644 --- a/markup/tableofcontents/tableofcontents.go +++ b/markup/tableofcontents/tableofcontents.go @@ -131,8 +131,8 @@ func (b *tocBuilder) writeHeaders(level, indent int, h Headers) { b.s.WriteString("\n") b.indent(indent) } - } + func (b *tocBuilder) writeHeader(level, indent int, h Header) { b.indent(indent) b.s.WriteString("<li>") diff --git a/markup/tableofcontents/tableofcontents_test.go b/markup/tableofcontents/tableofcontents_test.go index 8e5a47c52..753408ef9 100644 --- a/markup/tableofcontents/tableofcontents_test.go +++ b/markup/tableofcontents/tableofcontents_test.go @@ -152,5 +152,4 @@ func TestTocMissingParent(t *testing.T) { </li> </ol> </nav>`, qt.Commentf(got)) - } diff --git a/media/mediaType_test.go b/media/mediaType_test.go index ee7d4407a..4526c1e06 100644 --- a/media/mediaType_test.go +++ b/media/mediaType_test.go @@ -62,7 +62,6 @@ func TestDefaultTypes(t *testing.T) { } c.Assert(len(DefaultTypes), qt.Equals, 26) - } func TestGetByType(t *testing.T) { @@ -147,13 +146,12 @@ func TestFromExtensionMultipleSuffixes(t *testing.T) { c.Assert(tp.String(), qt.Equals, "image/svg+xml") c.Assert(found, qt.Equals, true) c.Assert(tp.FullSuffix(), qt.Equals, ".svg") - } func TestDecodeTypes(t *testing.T) { c := qt.New(t) - var tests = []struct { + tests := []struct { name string maps []map[string]interface{} shouldError bool @@ -164,7 +162,10 @@ func TestDecodeTypes(t *testing.T) { []map[string]interface{}{ { "application/json": map[string]interface{}{ - "suffixes": []string{"jasn"}}}}, + "suffixes": []string{"jasn"}, + }, + }, + }, false, func(t *testing.T, name string, tt Types) { c.Assert(len(tt), qt.Equals, len(DefaultTypes)) @@ -172,7 +173,8 @@ func TestDecodeTypes(t *testing.T) { c.Assert(found, qt.Equals, true) c.Assert(json.String(), qt.Equals, "application/json") c.Assert(json.FullSuffix(), qt.Equals, ".jasn") - }}, + }, + }, { "MIME suffix in key, multiple file suffixes, custom delimiter", []map[string]interface{}{ @@ -180,7 +182,9 @@ func TestDecodeTypes(t *testing.T) { "application/hugo+hg": map[string]interface{}{ "suffixes": []string{"hg1", "hg2"}, "Delimiter": "_", - }}}, + }, + }, + }, false, func(t *testing.T, name string, tt Types) { c.Assert(len(tt), qt.Equals, len(DefaultTypes)+1) @@ -193,14 +197,17 @@ func TestDecodeTypes(t *testing.T) { hg, found = tt.GetByType("application/hugo+hg") c.Assert(found, qt.Equals, true) - - }}, + }, + }, { "Add custom media type", []map[string]interface{}{ { "text/hugo+hgo": map[string]interface{}{ - "Suffixes": []string{"hgo2"}}}}, + "Suffixes": []string{"hgo2"}, + }, + }, + }, false, func(t *testing.T, name string, tt Types) { c.Assert(len(tt), qt.Equals, len(DefaultTypes)+1) @@ -212,7 +219,8 @@ func TestDecodeTypes(t *testing.T) { hugo, found := tt.GetBySuffix("hgo2") c.Assert(found, qt.Equals, true) c.Assert(hugo.String(), qt.Equals, "text/hugo+hgo") - }}, + }, + }, } for _, test := range tests { diff --git a/metrics/metrics.go b/metrics/metrics.go index 30a69be4b..f48ee33e0 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -15,21 +15,20 @@ package metrics import ( - "reflect" - - "github.com/gohugoio/hugo/helpers" - - "github.com/gohugoio/hugo/common/types" - "fmt" "io" "math" + "reflect" "sort" "strconv" "strings" "sync" "time" + "github.com/gohugoio/hugo/helpers" + + "github.com/gohugoio/hugo/common/types" + "github.com/gohugoio/hugo/compare" ) @@ -182,7 +181,6 @@ func (s *Store) WriteMetrics(w io.Writer) { fmt.Fprintf(w, " %13s %12s %12s %5d %s\n", v.sum, v.avg, v.max, v.count, v.key) } } - } // A result represents the calculated results for a given metric. @@ -243,7 +241,6 @@ func howSimilar(a, b interface{}) int { return 100 } return 0 - } // howSimilar is a naive diff implementation that returns diff --git a/metrics/metrics_test.go b/metrics/metrics_test.go index 057d58662..d28efa25e 100644 --- a/metrics/metrics_test.go +++ b/metrics/metrics_test.go @@ -43,7 +43,6 @@ func TestSimilarPercentage(t *testing.T) { c.Assert(howSimilar(template.HTML("Hugo Rules"), template.HTML("Hugo Rules")), qt.Equals, 100) c.Assert(howSimilar(map[string]interface{}{"a": 32, "b": 33}, map[string]interface{}{"a": 32, "b": 33}), qt.Equals, 100) c.Assert(howSimilar(map[string]interface{}{"a": 32, "b": 33}, map[string]interface{}{"a": 32, "b": 34}), qt.Equals, 0) - } type testStruct struct { @@ -56,7 +55,6 @@ func TestSimilarPercentageNonString(t *testing.T) { c.Assert(howSimilar(page.Pages{}, page.Pages{}), qt.Equals, 90) c.Assert(howSimilar(testStruct{Name: "A"}, testStruct{Name: "B"}), qt.Equals, 0) c.Assert(howSimilar(testStruct{Name: "A"}, testStruct{Name: "A"}), qt.Equals, 100) - } func BenchmarkHowSimilar(b *testing.B) { diff --git a/minifiers/config_test.go b/minifiers/config_test.go index f90bad994..851863842 100644 --- a/minifiers/config_test.go +++ b/minifiers/config_test.go @@ -61,5 +61,4 @@ func TestConfigLegacy(t *testing.T) { conf, err := decodeConfig(v) c.Assert(err, qt.IsNil) c.Assert(conf.MinifyOutput, qt.Equals, true) - } diff --git a/minifiers/minifiers_test.go b/minifiers/minifiers_test.go index fb222fd6d..c3922b06d 100644 --- a/minifiers/minifiers_test.go +++ b/minifiers/minifiers_test.go @@ -72,7 +72,6 @@ func TestNew(t *testing.T) { c.Assert(m.Minify(test.tp, &b, strings.NewReader(test.rawString)), qt.IsNil) c.Assert(b.String(), qt.Equals, test.expectedMinString) } - } func TestConfigureMinify(t *testing.T) { @@ -145,7 +144,6 @@ func TestJSONRoundTrip(t *testing.T) { c.Assert(json.Unmarshal(b.Bytes(), &m2), qt.IsNil) c.Assert(m1, qt.DeepEquals, m2) } - } func TestBugs(t *testing.T) { @@ -166,5 +164,4 @@ func TestBugs(t *testing.T) { c.Assert(m.Minify(test.tp, &b, strings.NewReader(test.rawString)), qt.IsNil) c.Assert(b.String(), qt.Equals, test.expectedMinString) } - } diff --git a/modules/client.go b/modules/client.go index 7d2175c94..88c1e933e 100644 --- a/modules/client.go +++ b/modules/client.go @@ -25,6 +25,8 @@ import ( "os/exec" "path/filepath" "regexp" + "strings" + "time" hglob "github.com/gohugoio/hugo/hugofs/glob" @@ -36,9 +38,6 @@ import ( "github.com/gohugoio/hugo/common/loggers" - "strings" - "time" - "github.com/gohugoio/hugo/config" "github.com/rogpeppe/go-internal/module" @@ -49,9 +48,7 @@ import ( "github.com/spf13/afero" ) -var ( - fileSeparator = string(os.PathSeparator) -) +var fileSeparator = string(os.PathSeparator) const ( goBinaryStatusOK goBinaryStatus = iota @@ -93,7 +90,6 @@ func NewClient(cfg ClientConfig) *Client { if cfg.CacheDir != "" { // Module cache stored below $GOPATH/pkg config.SetEnvVars(&env, "GOPATH", cfg.CacheDir) - } logger := cfg.Logger @@ -113,7 +109,8 @@ func NewClient(cfg ClientConfig) *Client { noVendor: noVendor, moduleConfig: mcfg, environ: env, - GoModulesFilename: goModFilename} + GoModulesFilename: goModFilename, + } } // Client contains most of the API provided by this package. @@ -165,7 +162,6 @@ func (c *Client) Graph(w io.Writer) error { // Local dir. dep += " => " + replace.Dir() } - } fmt.Fprintln(w, prefix+dep) } @@ -357,7 +353,6 @@ var verifyErrorDirRe = regexp.MustCompile(`dir has been modified \((.*?)\)`) func (c *Client) Verify(clean bool) error { // TODO1 add path to mod clean err := c.runVerify() - if err != nil { if clean { m := verifyErrorDirRe.FindAllStringSubmatch(err.Error(), -1) @@ -450,7 +445,6 @@ func (c *Client) listGoMods() (goModules, error) { } return modules, err - } func (c *Client) rewriteGoMod(name string, isGoMod map[string]bool) error { @@ -515,7 +509,6 @@ func (c *Client) rewriteGoModRewrite(name string, isGoMod map[string]bool) ([]by } return b.Bytes(), nil - } func (c *Client) rmVendorDir(vendorDir string) error { @@ -539,7 +532,6 @@ func (c *Client) runGo( ctx context.Context, stdout io.Writer, args ...string) error { - if c.goBinaryStatus != 0 { return nil } diff --git a/modules/client_test.go b/modules/client_test.go index 7cc1058fc..c7a07fb87 100644 --- a/modules/client_test.go +++ b/modules/client_test.go @@ -30,7 +30,6 @@ import ( ) func TestClient(t *testing.T) { - modName := "hugo-modules-basic-test" modPath := "github.com/gohugoio/tests/" + modName expect := `github.com/gohugoio/tests/hugo-modules-basic-test github.com/gohugoio/hugoTestModules1_darwin/[email protected] @@ -41,7 +40,6 @@ github.com/gohugoio/hugoTestModules1_darwin/[email protected] github.com/gohugoio/h c := qt.New(t) newClient := func(c *qt.C, withConfig func(cfg *ClientConfig)) (*Client, func()) { - workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, modName) c.Assert(err, qt.IsNil) themesDir := filepath.Join(workingDir, "themes") @@ -55,7 +53,7 @@ github.com/gohugoio/hugoTestModules1_darwin/[email protected] github.com/gohugoio/h } withConfig(&ccfg) - ccfg.ModuleConfig.Imports = []Import{Import{Path: "github.com/gohugoio/hugoTestModules1_darwin/modh2_2"}} + ccfg.ModuleConfig.Imports = []Import{{Path: "github.com/gohugoio/hugoTestModules1_darwin/modh2_2"}} client := NewClient(ccfg) return client, clean @@ -98,7 +96,6 @@ project github.com/gohugoio/hugoTestModules1_darwin/[email protected]+vendor // Test Tidy c.Assert(client.Tidy(), qt.IsNil) - }) c.Run("IgnoreVendor", func(c *qt.C) { @@ -165,15 +162,12 @@ project github.com/gohugoio/hugoTestModules1_darwin/[email protected]+vendor dirname, err = client.createThemeDirname(absDir, false) fmt.Println(dirname) c.Assert(err, qt.Not(qt.IsNil)) - }) - } var globAll, _ = glob.GetGlob("**") func TestGetModlineSplitter(t *testing.T) { - c := qt.New(t) gomodSplitter := getModlineSplitter(true) @@ -184,5 +178,4 @@ func TestGetModlineSplitter(t *testing.T) { gosumSplitter := getModlineSplitter(false) c.Assert(gosumSplitter("github.com/BurntSushi/toml v0.3.1"), qt.DeepEquals, []string{"github.com/BurntSushi/toml", "v0.3.1"}) - } diff --git a/modules/collect.go b/modules/collect.go index e00fa540f..179b9d1fb 100644 --- a/modules/collect.go +++ b/modules/collect.go @@ -110,7 +110,6 @@ func (h *Client) collect(tidy bool) (ModulesConfig, *collector) { AllModules: c.modules, GoModulesFilename: c.GoModulesFilename, }, c - } type ModulesConfig struct { @@ -325,7 +324,6 @@ func (c *collector) add(owner *moduleAdapter, moduleImport Import, disabled bool c.modules = append(c.modules, ma) return ma, nil - } func (c *collector) addAndRecurse(owner *moduleAdapter, disabled bool) error { @@ -363,7 +361,6 @@ func (c *collector) applyMounts(moduleImport Import, mod *moduleAdapter) error { if len(mounts) == 0 { // Mounts not defined by the import. mounts = modConfig.Mounts - } if !mod.projectMod && len(mounts) == 0 { @@ -397,7 +394,6 @@ func (c *collector) applyMounts(moduleImport Import, mod *moduleAdapter) error { } func (c *collector) applyThemeConfig(tc *moduleAdapter) error { - var ( configFilename string cfg config.Provider @@ -477,7 +473,6 @@ func (c *collector) applyThemeConfig(tc *moduleAdapter) error { tc.config = config return nil - } func (c *collector) collect() { @@ -502,7 +497,6 @@ func (c *collector) collect() { // Add the project mod on top. c.modules = append(Modules{projectMod}, c.modules...) - } func (c *collector) isVendored(dir string) bool { @@ -515,7 +509,6 @@ func (c *collector) collectModulesTXT(owner Module) error { filename := filepath.Join(vendorDir, vendorModulesFilename) f, err := c.fs.Open(filename) - if err != nil { if os.IsNotExist(err) { return nil @@ -656,7 +649,6 @@ func (c *collector) wrapModuleNotFound(err error) error { } return err - } type vendoredModule struct { @@ -679,7 +671,6 @@ func createProjectModule(gomod *goModule, workingDir string, conf Config) *modul projectMod: true, config: conf, } - } // In the first iteration of Hugo Modules, we do not support multiple diff --git a/modules/collect_test.go b/modules/collect_test.go index 7f320f40a..9487c0a0e 100644 --- a/modules/collect_test.go +++ b/modules/collect_test.go @@ -34,21 +34,18 @@ func TestPathKey(t *testing.T) { } { c.Assert(pathKey(test.in), qt.Equals, test.expect) } - } func TestFilterUnwantedMounts(t *testing.T) { - mounts := []Mount{ - Mount{Source: "a", Target: "b", Lang: "en"}, - Mount{Source: "a", Target: "b", Lang: "en"}, - Mount{Source: "b", Target: "c", Lang: "en"}, + {Source: "a", Target: "b", Lang: "en"}, + {Source: "a", Target: "b", Lang: "en"}, + {Source: "b", Target: "c", Lang: "en"}, } filtered := filterUnwantedMounts(mounts) c := qt.New(t) c.Assert(len(filtered), qt.Equals, 2) - c.Assert(filtered, qt.DeepEquals, []Mount{Mount{Source: "a", Target: "b", Lang: "en"}, Mount{Source: "b", Target: "c", Lang: "en"}}) - + c.Assert(filtered, qt.DeepEquals, []Mount{{Source: "a", Target: "b", Lang: "en"}, {Source: "b", Target: "c", Lang: "en"}}) } diff --git a/modules/config.go b/modules/config.go index 1ce8c9f02..d56f38343 100644 --- a/modules/config.go +++ b/modules/config.go @@ -113,10 +113,11 @@ func ApplyProjectConfigDefaults(cfg config.Provider, mod Module) error { source := cfg.GetString(d.key) componentsConfigured[d.component] = true - return []Mount{Mount{ + return []Mount{{ // No lang set for layouts etc. Source: source, - Target: d.component}} + Target: d.component, + }} } return nil @@ -166,7 +167,6 @@ func ApplyProjectConfigDefaults(cfg config.Provider, mod Module) error { var mounts []Mount for _, dirKey := range dirKeys { if componentsConfigured[dirKey.component] { - continue } @@ -240,7 +240,6 @@ func decodeConfig(cfg config.Provider, pathReplacements map[string]string) (Conf c.Imports[i] = imp } } - } for i, mnt := range c.Mounts { @@ -393,11 +392,9 @@ func getStaticDirs(cfg config.Provider) []string { } func getStringOrStringSlice(cfg config.Provider, key string, id int) []string { - if id >= 0 { key = fmt.Sprintf("%s%d", key, id) } return config.GetStringSlicePreserveString(cfg, key) - } diff --git a/modules/config_test.go b/modules/config_test.go index dd9dbc22f..458240b60 100644 --- a/modules/config_test.go +++ b/modules/config_test.go @@ -120,7 +120,6 @@ path="github.com/bep/mycomponent" } }) - } func TestDecodeConfigBothOldAndNewProvided(t *testing.T) { @@ -141,7 +140,6 @@ path="a" c.Assert(err, qt.IsNil) c.Assert(len(modCfg.Imports), qt.Equals, 3) c.Assert(modCfg.Imports[0].Path, qt.Equals, "a") - } // Test old style theme import. diff --git a/modules/npm/package_builder.go b/modules/npm/package_builder.go index c0a5b0dad..f407a92bd 100644 --- a/modules/npm/package_builder.go +++ b/modules/npm/package_builder.go @@ -45,7 +45,6 @@ const ( ) func Pack(fs afero.Fs, fis []hugofs.FileMetaInfo) error { - var b *packageBuilder // Have a package.hugo.json? @@ -140,7 +139,6 @@ func Pack(fs afero.Fs, fis []hugofs.FileMetaInfo) error { } return nil - } func newPackageBuilder(source string, first io.Reader) *packageBuilder { @@ -220,7 +218,6 @@ func (b *packageBuilder) addm(source string, m map[string]interface{}) { } } } - } func (b *packageBuilder) unmarshal(r io.Reader) map[string]interface{} { diff --git a/navigation/menu.go b/navigation/menu.go index 498078e34..1fb970c7c 100644 --- a/navigation/menu.go +++ b/navigation/menu.go @@ -14,14 +14,14 @@ package navigation import ( - "github.com/gohugoio/hugo/common/maps" - "github.com/gohugoio/hugo/common/types" - "github.com/gohugoio/hugo/compare" - "html/template" "sort" "strings" + "github.com/gohugoio/hugo/common/maps" + "github.com/gohugoio/hugo/common/types" + "github.com/gohugoio/hugo/compare" + "github.com/spf13/cast" ) diff --git a/navigation/pagemenus.go b/navigation/pagemenus.go index 352a91557..1dfa71255 100644 --- a/navigation/pagemenus.go +++ b/navigation/pagemenus.go @@ -94,7 +94,6 @@ func PageMenusFromPage(p Page) (PageMenus, error) { } return pm, nil - } func NewMenuQueryProvider( @@ -102,7 +101,6 @@ func NewMenuQueryProvider( pagem PageMenusGetter, sitem MenusGetter, p Page) MenuQueryProvider { - return &pageMenus{ p: p, pagem: pagem, @@ -119,7 +117,6 @@ type pageMenus struct { } func (pm *pageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { - // page is labeled as "shadow-member" of the menu with the same identifier as the section if pm.setionPagesMenu != "" { section := pm.p.Section() @@ -136,7 +133,6 @@ func (pm *pageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { menus := pm.pagem.Menus() if m, ok := menus[menuID]; ok { - for _, child := range me.Children { if child.IsEqual(m) { return true @@ -165,7 +161,6 @@ func (pm *pageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { } return false - } func (pm *pageMenus) IsMenuCurrent(menuID string, inme *MenuEntry) bool { diff --git a/output/docshelper.go b/output/docshelper.go index 450c323d1..42b871ab5 100644 --- a/output/docshelper.go +++ b/output/docshelper.go @@ -23,7 +23,6 @@ func init() { } func createLayoutExamples() interface{} { - type Example struct { Example string Kind string @@ -78,11 +77,11 @@ func createLayoutExamples() interface{} { Kind: example.d.Kind, OutputFormat: example.f.Name, Suffix: example.f.MediaType.Suffix(), - Layouts: makeLayoutsPresentable(layouts)}) + Layouts: makeLayoutsPresentable(layouts), + }) } return basicExamples - } func makeLayoutsPresentable(l []string) []string { diff --git a/output/layout_test.go b/output/layout_test.go index 853b2475a..f98eea960 100644 --- a/output/layout_test.go +++ b/output/layout_test.go @@ -65,7 +65,9 @@ func TestLayout(t *testing.T) { expect []string }{ { - "Home", LayoutDescriptor{Kind: "home"}, "", ampType, + "Home", + LayoutDescriptor{Kind: "home"}, + "", ampType, []string{ "index.amp.html", "home.amp.html", @@ -82,7 +84,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home baseof", LayoutDescriptor{Kind: "home", Baseof: true}, "", ampType, + "Home baseof", + LayoutDescriptor{Kind: "home", Baseof: true}, + "", ampType, []string{ "index-baseof.amp.html", "home-baseof.amp.html", @@ -103,7 +107,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, HTML", LayoutDescriptor{Kind: "home"}, "", htmlFormat, + "Home, HTML", + LayoutDescriptor{Kind: "home"}, + "", htmlFormat, // We will eventually get to index.html. This looks stuttery, but makes the lookup logic easy to understand. []string{ "index.html.html", @@ -121,7 +127,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, HTML, baseof", LayoutDescriptor{Kind: "home", Baseof: true}, "", htmlFormat, + "Home, HTML, baseof", + LayoutDescriptor{Kind: "home", Baseof: true}, + "", htmlFormat, []string{ "index-baseof.html.html", "home-baseof.html.html", @@ -142,7 +150,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, french language", LayoutDescriptor{Kind: "home", Lang: "fr"}, "", ampType, + "Home, french language", + LayoutDescriptor{Kind: "home", Lang: "fr"}, + "", ampType, []string{ "index.fr.amp.html", "home.fr.amp.html", @@ -171,7 +181,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, no ext or delim", LayoutDescriptor{Kind: "home"}, "", noExtDelimFormat, + "Home, no ext or delim", + LayoutDescriptor{Kind: "home"}, + "", noExtDelimFormat, []string{ "index.nem", "home.nem", @@ -182,7 +194,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, no ext", LayoutDescriptor{Kind: "home"}, "", noExt, + "Home, no ext", + LayoutDescriptor{Kind: "home"}, + "", noExt, []string{ "index.nex", "home.nex", @@ -193,11 +207,15 @@ func TestLayout(t *testing.T) { }, }, { - "Page, no ext or delim", LayoutDescriptor{Kind: "page"}, "", noExtDelimFormat, + "Page, no ext or delim", + LayoutDescriptor{Kind: "page"}, + "", noExtDelimFormat, []string{"_default/single.nem"}, }, { - "Section", LayoutDescriptor{Kind: "section", Section: "sect1"}, "", ampType, + "Section", + LayoutDescriptor{Kind: "section", Section: "sect1"}, + "", ampType, []string{ "sect1/sect1.amp.html", "sect1/section.amp.html", @@ -220,7 +238,9 @@ func TestLayout(t *testing.T) { }, }, { - "Section, baseof", LayoutDescriptor{Kind: "section", Section: "sect1", Baseof: true}, "", ampType, + "Section, baseof", + LayoutDescriptor{Kind: "section", Section: "sect1", Baseof: true}, + "", ampType, []string{ "sect1/sect1-baseof.amp.html", "sect1/section-baseof.amp.html", @@ -249,7 +269,9 @@ func TestLayout(t *testing.T) { }, }, { - "Section, baseof, French, AMP", LayoutDescriptor{Kind: "section", Section: "sect1", Lang: "fr", Baseof: true}, "", ampType, + "Section, baseof, French, AMP", + LayoutDescriptor{Kind: "section", Section: "sect1", Lang: "fr", Baseof: true}, + "", ampType, []string{ "sect1/sect1-baseof.fr.amp.html", "sect1/section-baseof.fr.amp.html", @@ -302,7 +324,9 @@ func TestLayout(t *testing.T) { }, }, { - "Section with layout", LayoutDescriptor{Kind: "section", Section: "sect1", Layout: "mylayout"}, "", ampType, + "Section with layout", + LayoutDescriptor{Kind: "section", Section: "sect1", Layout: "mylayout"}, + "", ampType, []string{ "sect1/mylayout.amp.html", "sect1/sect1.amp.html", @@ -331,7 +355,9 @@ func TestLayout(t *testing.T) { }, }, { - "Term, French, AMP", LayoutDescriptor{Kind: "term", Section: "tags", Lang: "fr"}, "", ampType, + "Term, French, AMP", + LayoutDescriptor{Kind: "term", Section: "tags", Lang: "fr"}, + "", ampType, []string{ "term/term.fr.amp.html", "term/tags.fr.amp.html", @@ -400,7 +426,9 @@ func TestLayout(t *testing.T) { }, }, { - "Term, baseof, French, AMP", LayoutDescriptor{Kind: "term", Section: "tags", Lang: "fr", Baseof: true}, "", ampType, + "Term, baseof, French, AMP", + LayoutDescriptor{Kind: "term", Section: "tags", Lang: "fr", Baseof: true}, + "", ampType, []string{ "term/term-baseof.fr.amp.html", "term/tags-baseof.fr.amp.html", @@ -485,7 +513,9 @@ func TestLayout(t *testing.T) { }, }, { - "Term", LayoutDescriptor{Kind: "term", Section: "tags"}, "", ampType, + "Term", + LayoutDescriptor{Kind: "term", Section: "tags"}, + "", ampType, []string{ "term/term.amp.html", "term/tags.amp.html", @@ -522,7 +552,9 @@ func TestLayout(t *testing.T) { }, }, { - "Taxonomy", LayoutDescriptor{Kind: "taxonomy", Section: "categories"}, "", ampType, + "Taxonomy", + LayoutDescriptor{Kind: "taxonomy", Section: "categories"}, + "", ampType, []string{ "categories/categories.terms.amp.html", "categories/terms.amp.html", @@ -551,14 +583,18 @@ func TestLayout(t *testing.T) { }, }, { - "Page", LayoutDescriptor{Kind: "page"}, "", ampType, + "Page", + LayoutDescriptor{Kind: "page"}, + "", ampType, []string{ "_default/single.amp.html", "_default/single.html", }, }, { - "Page, baseof", LayoutDescriptor{Kind: "page", Baseof: true}, "", ampType, + "Page, baseof", + LayoutDescriptor{Kind: "page", Baseof: true}, + "", ampType, []string{ "_default/single-baseof.amp.html", "_default/baseof.amp.html", @@ -567,7 +603,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page with layout", LayoutDescriptor{Kind: "page", Layout: "mylayout"}, "", ampType, + "Page with layout", + LayoutDescriptor{Kind: "page", Layout: "mylayout"}, + "", ampType, []string{ "_default/mylayout.amp.html", "_default/single.amp.html", @@ -576,7 +614,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page with layout, baseof", LayoutDescriptor{Kind: "page", Layout: "mylayout", Baseof: true}, "", ampType, + "Page with layout, baseof", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Baseof: true}, + "", ampType, []string{ "_default/mylayout-baseof.amp.html", "_default/single-baseof.amp.html", @@ -587,7 +627,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page with layout and type", LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype"}, "", ampType, + "Page with layout and type", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype"}, + "", ampType, []string{ "myttype/mylayout.amp.html", "myttype/single.amp.html", @@ -600,7 +642,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page baseof with layout and type", LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype", Baseof: true}, "", ampType, + "Page baseof with layout and type", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype", Baseof: true}, + "", ampType, []string{ "myttype/mylayout-baseof.amp.html", "myttype/single-baseof.amp.html", @@ -617,7 +661,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page baseof with layout and type in French", LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype", Lang: "fr", Baseof: true}, "", ampType, + "Page baseof with layout and type in French", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype", Lang: "fr", Baseof: true}, + "", ampType, []string{ "myttype/mylayout-baseof.fr.amp.html", "myttype/single-baseof.fr.amp.html", @@ -646,7 +692,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page with layout and type with subtype", LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype/mysubtype"}, "", ampType, + "Page with layout and type with subtype", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype/mysubtype"}, + "", ampType, []string{ "myttype/mysubtype/mylayout.amp.html", "myttype/mysubtype/single.amp.html", @@ -660,7 +708,9 @@ func TestLayout(t *testing.T) { }, // RSS { - "RSS Home", LayoutDescriptor{Kind: "home"}, "", RSSFormat, + "RSS Home", + LayoutDescriptor{Kind: "home"}, + "", RSSFormat, []string{ "index.rss.xml", "home.rss.xml", @@ -680,7 +730,9 @@ func TestLayout(t *testing.T) { }, }, { - "RSS Home, baseof", LayoutDescriptor{Kind: "home", Baseof: true}, "", RSSFormat, + "RSS Home, baseof", + LayoutDescriptor{Kind: "home", Baseof: true}, + "", RSSFormat, []string{ "index-baseof.rss.xml", "home-baseof.rss.xml", @@ -701,7 +753,9 @@ func TestLayout(t *testing.T) { }, }, { - "RSS Section", LayoutDescriptor{Kind: "section", Section: "sect1"}, "", RSSFormat, + "RSS Section", + LayoutDescriptor{Kind: "section", Section: "sect1"}, + "", RSSFormat, []string{ "sect1/sect1.rss.xml", "sect1/section.rss.xml", @@ -728,7 +782,9 @@ func TestLayout(t *testing.T) { }, }, { - "RSS Term", LayoutDescriptor{Kind: "term", Section: "tag"}, "", RSSFormat, + "RSS Term", + LayoutDescriptor{Kind: "term", Section: "tag"}, + "", RSSFormat, []string{ "term/term.rss.xml", "term/tag.rss.xml", @@ -770,7 +826,9 @@ func TestLayout(t *testing.T) { }, }, { - "RSS Taxonomy", LayoutDescriptor{Kind: "taxonomy", Section: "tag"}, "", RSSFormat, + "RSS Taxonomy", + LayoutDescriptor{Kind: "taxonomy", Section: "tag"}, + "", RSSFormat, []string{ "tag/tag.terms.rss.xml", "tag/terms.rss.xml", @@ -803,7 +861,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home plain text", LayoutDescriptor{Kind: "home"}, "", JSONFormat, + "Home plain text", + LayoutDescriptor{Kind: "home"}, + "", JSONFormat, []string{ "index.json.json", "home.json.json", @@ -820,14 +880,18 @@ func TestLayout(t *testing.T) { }, }, { - "Page plain text", LayoutDescriptor{Kind: "page"}, "", JSONFormat, + "Page plain text", + LayoutDescriptor{Kind: "page"}, + "", JSONFormat, []string{ "_default/single.json.json", "_default/single.json", }, }, { - "Reserved section, shortcodes", LayoutDescriptor{Kind: "section", Section: "shortcodes", Type: "shortcodes"}, "", ampType, + "Reserved section, shortcodes", + LayoutDescriptor{Kind: "section", Section: "shortcodes", Type: "shortcodes"}, + "", ampType, []string{ "section/shortcodes.amp.html", "section/section.amp.html", @@ -844,7 +908,9 @@ func TestLayout(t *testing.T) { }, }, { - "Reserved section, partials", LayoutDescriptor{Kind: "section", Section: "partials", Type: "partials"}, "", ampType, + "Reserved section, partials", + LayoutDescriptor{Kind: "section", Section: "partials", Type: "partials"}, + "", ampType, []string{ "section/partials.amp.html", "section/section.amp.html", @@ -862,14 +928,18 @@ func TestLayout(t *testing.T) { }, // This is currently always HTML only { - "404, HTML", LayoutDescriptor{Kind: "404"}, "", htmlFormat, + "404, HTML", + LayoutDescriptor{Kind: "404"}, + "", htmlFormat, []string{ "404.html.html", "404.html", }, }, { - "404, HTML baseof", LayoutDescriptor{Kind: "404", Baseof: true}, "", htmlFormat, + "404, HTML baseof", + LayoutDescriptor{Kind: "404", Baseof: true}, + "", htmlFormat, []string{ "404-baseof.html.html", "baseof.html.html", @@ -882,7 +952,9 @@ func TestLayout(t *testing.T) { }, }, { - "Content hook", LayoutDescriptor{Kind: "render-link", RenderingHook: true, Layout: "mylayout", Section: "blog"}, "", ampType, + "Content hook", + LayoutDescriptor{Kind: "render-link", RenderingHook: true, Layout: "mylayout", Section: "blog"}, + "", ampType, []string{ "blog/_markup/render-link.amp.html", "blog/_markup/render-link.html", diff --git a/output/outputFormat.go b/output/outputFormat.go index c9c108ac5..ee5881e2a 100644 --- a/output/outputFormat.go +++ b/output/outputFormat.go @@ -16,11 +16,10 @@ package output import ( "encoding/json" "fmt" + "reflect" "sort" "strings" - "reflect" - "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/media" @@ -200,7 +199,6 @@ func (formats Formats) Less(i, j int) bool { } return fi.Weight > 0 && fi.Weight < fj.Weight - } // GetBySuffix gets a output format given as suffix, e.g. "html". diff --git a/output/outputFormat_test.go b/output/outputFormat_test.go index 2b10c5a9e..d91f1e410 100644 --- a/output/outputFormat_test.go +++ b/output/outputFormat_test.go @@ -77,7 +77,6 @@ func TestDefaultTypes(t *testing.T) { c.Assert(RSSFormat.IsPlainText, qt.Equals, false) c.Assert(RSSFormat.NoUgly, qt.Equals, true) c.Assert(CalendarFormat.IsHTML, qt.Equals, false) - } func TestGetFormatByName(t *testing.T) { @@ -144,7 +143,6 @@ func TestGetFormatByFilename(t *testing.T) { c.Assert(f, eq, noExt) _, found = formats.FromFilename("my.css") c.Assert(found, qt.Equals, false) - } func TestDecodeFormats(t *testing.T) { @@ -152,7 +150,7 @@ func TestDecodeFormats(t *testing.T) { mediaTypes := media.Types{media.JSONType, media.XMLType} - var tests = []struct { + tests := []struct { name string maps []map[string]interface{} shouldError bool @@ -164,7 +162,10 @@ func TestDecodeFormats(t *testing.T) { { "JsON": map[string]interface{}{ "baseName": "myindex", - "isPlainText": "false"}}}, + "isPlainText": "false", + }, + }, + }, false, func(t *testing.T, name string, f Formats) { msg := qt.Commentf(name) @@ -173,8 +174,8 @@ func TestDecodeFormats(t *testing.T) { c.Assert(json.BaseName, qt.Equals, "myindex") c.Assert(json.MediaType, eq, media.JSONType) c.Assert(json.IsPlainText, qt.Equals, false) - - }}, + }, + }, { "Add XML format with string as mediatype", []map[string]interface{}{ @@ -182,7 +183,9 @@ func TestDecodeFormats(t *testing.T) { "MYXMLFORMAT": map[string]interface{}{ "baseName": "myxml", "mediaType": "application/xml", - }}}, + }, + }, + }, false, func(t *testing.T, name string, f Formats) { c.Assert(len(f), qt.Equals, len(DefaultFormats)+1) @@ -194,8 +197,8 @@ func TestDecodeFormats(t *testing.T) { // Verify that we haven't changed the DefaultFormats slice. json, _ := f.GetByName("JSON") c.Assert(json.BaseName, qt.Equals, "index") - - }}, + }, + }, { "Add format unknown mediatype", []map[string]interface{}{ @@ -203,11 +206,13 @@ func TestDecodeFormats(t *testing.T) { "MYINVALID": map[string]interface{}{ "baseName": "mymy", "mediaType": "application/hugo", - }}}, + }, + }, + }, true, func(t *testing.T, name string, f Formats) { - - }}, + }, + }, { "Add and redefine XML format", []map[string]interface{}{ @@ -215,11 +220,13 @@ func TestDecodeFormats(t *testing.T) { "MYOTHERXMLFORMAT": map[string]interface{}{ "baseName": "myotherxml", "mediaType": media.XMLType, - }}, + }, + }, { "MYOTHERXMLFORMAT": map[string]interface{}{ "baseName": "myredefined", - }}, + }, + }, }, false, func(t *testing.T, name string, f Formats) { @@ -228,7 +235,8 @@ func TestDecodeFormats(t *testing.T) { c.Assert(found, qt.Equals, true) c.Assert(xml.BaseName, qt.Equals, "myredefined") c.Assert(xml.MediaType, eq, media.XMLType) - }}, + }, + }, } for _, test := range tests { @@ -263,5 +271,4 @@ func TestSort(t *testing.T) { c.Assert(formats[0].Name, qt.Equals, "JSON") c.Assert(formats[1].Name, qt.Equals, "HTML") c.Assert(formats[2].Name, qt.Equals, "AMP") - } diff --git a/parser/lowercase_camel_json.go b/parser/lowercase_camel_json.go index 6994d1215..fb283a1c4 100644 --- a/parser/lowercase_camel_json.go +++ b/parser/lowercase_camel_json.go @@ -22,8 +22,10 @@ import ( ) // Regexp definitions -var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) -var wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`) +var ( + keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) + wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`) +) // Code adapted from https://gist.github.com/piersy/b9934790a8892db1a603820c0c23e4a7 type LowerCaseCamelJSONMarshaller struct { @@ -36,7 +38,6 @@ func (c LowerCaseCamelJSONMarshaller) MarshalJSON() ([]byte, error) { converted := keyMatchRegex.ReplaceAllFunc( marshalled, func(match []byte) []byte { - // Attributes on the form XML, JSON etc. if bytes.Equal(match, bytes.ToUpper(match)) { return bytes.ToLower(match) diff --git a/parser/metadecoders/decoder.go b/parser/metadecoders/decoder.go index 2624ad16f..7fc8330af 100644 --- a/parser/metadecoders/decoder.go +++ b/parser/metadecoders/decoder.go @@ -119,7 +119,6 @@ func (d Decoder) Unmarshal(data []byte, f Format) (interface{}, error) { default: return make(map[string]interface{}), nil } - } var v interface{} err := d.UnmarshalTo(data, f, &v) @@ -129,7 +128,6 @@ func (d Decoder) Unmarshal(data []byte, f Format) (interface{}, error) { // UnmarshalTo unmarshals data in format f into v. func (d Decoder) UnmarshalTo(data []byte, f Format, v interface{}) error { - var err error switch f { @@ -181,7 +179,6 @@ func (d Decoder) UnmarshalTo(data []byte, f Format, v interface{}) error { } return toFileError(f, errors.Wrap(err, "unmarshal failed")) - } func (d Decoder) unmarshalCSV(data []byte, v interface{}) error { @@ -203,7 +200,6 @@ func (d Decoder) unmarshalCSV(data []byte, v interface{}) error { } return nil - } func parseORGDate(s string) string { @@ -255,7 +251,6 @@ func toFileError(f Format, err error) error { // // Inspired by https://github.com/stripe/stripe-mock, MIT licensed func stringifyMapKeys(in interface{}) (interface{}, bool) { - switch in := in.(type) { case []interface{}: for i, v := range in { diff --git a/parser/metadecoders/decoder_test.go b/parser/metadecoders/decoder_test.go index d11d578ba..e0990a5f7 100644 --- a/parser/metadecoders/decoder_test.go +++ b/parser/metadecoders/decoder_test.go @@ -87,7 +87,6 @@ func TestUnmarshalToInterface(t *testing.T) { } } - } func TestUnmarshalStringTo(t *testing.T) { diff --git a/parser/metadecoders/format.go b/parser/metadecoders/format.go index 9e9cc2e1f..d2b35223d 100644 --- a/parser/metadecoders/format.go +++ b/parser/metadecoders/format.go @@ -39,7 +39,6 @@ func FormatFromString(formatStr string) Format { if strings.Contains(formatStr, ".") { // Assume a filename formatStr = strings.TrimPrefix(filepath.Ext(formatStr), ".") - } switch formatStr { case "yaml", "yml": @@ -55,7 +54,6 @@ func FormatFromString(formatStr string) Format { } return "" - } // FormatFromMediaType gets the Format given a MIME type, empty string diff --git a/parser/pageparser/item_test.go b/parser/pageparser/item_test.go index a30860f17..cd01202c6 100644 --- a/parser/pageparser/item_test.go +++ b/parser/pageparser/item_test.go @@ -31,5 +31,4 @@ func TestItemValTyped(t *testing.T) { c.Assert(Item{Val: []byte("true")}.ValTyped(), qt.Equals, true) c.Assert(Item{Val: []byte("false")}.ValTyped(), qt.Equals, false) c.Assert(Item{Val: []byte("trues")}.ValTyped(), qt.Equals, "trues") - } diff --git a/parser/pageparser/pagelexer.go b/parser/pageparser/pagelexer.go index 7092b7b2b..c360642c4 100644 --- a/parser/pageparser/pagelexer.go +++ b/parser/pageparser/pagelexer.go @@ -59,7 +59,6 @@ func (l *pageLexer) Iterator() *Iterator { func (l *pageLexer) Input() []byte { return l.input - } type Config struct { @@ -286,7 +285,6 @@ func (s *sectionHandlers) skip() int { } func createSectionHandlers(l *pageLexer) *sectionHandlers { - shortCodeHandler := §ionHandler{ l: l, skipFunc: func(l *pageLexer) int { @@ -327,7 +325,6 @@ func createSectionHandlers(l *pageLexer) *sectionHandlers { skipFunc: func(l *pageLexer) int { if l.summaryDividerChecked || l.summaryDivider == nil { return -1 - } return l.index(l.summaryDivider) }, @@ -343,7 +340,6 @@ func createSectionHandlers(l *pageLexer) *sectionHandlers { l.emit(TypeLeadSummaryDivider) return origin, true - }, } @@ -425,7 +421,6 @@ func (s *sectionHandler) skip() int { } func lexMainSection(l *pageLexer) stateFunc { - if l.isEOF() { return lexDone } @@ -451,11 +446,9 @@ func lexMainSection(l *pageLexer) stateFunc { l.pos = len(l.input) return lexDone - } func lexDone(l *pageLexer) stateFunc { - // Done! if l.pos > l.start { l.emit(tText) diff --git a/parser/pageparser/pagelexer_intro.go b/parser/pageparser/pagelexer_intro.go index 45ad4f26a..961528ef2 100644 --- a/parser/pageparser/pagelexer_intro.go +++ b/parser/pageparser/pagelexer_intro.go @@ -147,12 +147,10 @@ LOOP: l.emit(TypeFrontMatterORG) return lexMainSection - } // Handle YAML or TOML front matter. func (l *pageLexer) lexFrontMatterSection(tp ItemType, delimr rune, name string, delim []byte) stateFunc { - for i := 0; i < 2; i++ { if r := l.next(); r != delimr { return l.errorf("invalid %s delimiter", name) diff --git a/parser/pageparser/pagelexer_shortcode.go b/parser/pageparser/pagelexer_shortcode.go index e8e3490aa..774a8f690 100644 --- a/parser/pageparser/pagelexer_shortcode.go +++ b/parser/pageparser/pagelexer_shortcode.go @@ -84,7 +84,6 @@ func lexShortcodeRightDelim(l *pageLexer) stateFunc { // 5. `param` // 6. param=`123` func lexShortcodeParam(l *pageLexer, escapedQuoteStart bool) stateFunc { - first := true nextEq := false @@ -138,7 +137,6 @@ func lexShortcodeParam(l *pageLexer, escapedQuoteStart bool) stateFunc { l.emit(tScParam) return lexInsideShortcode - } func lexShortcodeParamVal(l *pageLexer) stateFunc { @@ -356,7 +354,6 @@ func (l *pageLexer) currentLeftShortcodeDelim() []byte { return leftDelimScWithMarkup } return leftDelimScNoMarkup - } func (l *pageLexer) currentRightShortcodeDelim() []byte { diff --git a/parser/pageparser/pagelexer_test.go b/parser/pageparser/pagelexer_test.go index 3bc3bf6ad..00669c27b 100644 --- a/parser/pageparser/pagelexer_test.go +++ b/parser/pageparser/pagelexer_test.go @@ -25,5 +25,4 @@ func TestMinIndex(t *testing.T) { c.Assert(minIndex(4, 0, -2, 2, 5), qt.Equals, 0) c.Assert(minIndex(), qt.Equals, -1) c.Assert(minIndex(-2, -3), qt.Equals, -1) - } diff --git a/parser/pageparser/pageparser.go b/parser/pageparser/pageparser.go index 3d17aa8e0..19d068ece 100644 --- a/parser/pageparser/pageparser.go +++ b/parser/pageparser/pageparser.go @@ -71,7 +71,6 @@ func ParseFrontMatterAndContent(r io.Reader) (ContentFrontMatter, error) { frontMatterSource = item.Val } return true - } iter.PeekWalk(walkFn) diff --git a/parser/pageparser/pageparser_intro_test.go b/parser/pageparser/pageparser_intro_test.go index e776cb3ee..1b903d546 100644 --- a/parser/pageparser/pageparser_intro_test.go +++ b/parser/pageparser/pageparser_intro_test.go @@ -106,7 +106,6 @@ func collect(input []byte, skipFrontMatter bool, stateStart stateFunc) (items [] var cfg Config return collectWithConfig(input, skipFrontMatter, stateStart, cfg) - } // no positional checking, for now ... diff --git a/parser/pageparser/pageparser_main_test.go b/parser/pageparser/pageparser_main_test.go index 008c88c51..8fed2bffa 100644 --- a/parser/pageparser/pageparser_main_test.go +++ b/parser/pageparser/pageparser_main_test.go @@ -21,7 +21,7 @@ import ( func TestMain(t *testing.T) { t.Parallel() - var mainTests = []lexerTest{ + mainTests := []lexerTest{ {"emoji #1", "Some text with :emoji:", []Item{nti(tText, "Some text with "), nti(TypeEmoji, ":emoji:"), tstEOF}}, {"emoji #2", "Some text with :emoji: and some text.", []Item{nti(tText, "Some text with "), nti(TypeEmoji, ":emoji:"), nti(tText, " and some text."), tstEOF}}, {"looks like an emoji #1", "Some text and then :emoji", []Item{nti(tText, "Some text and then "), nti(tText, ":"), nti(tText, "emoji"), tstEOF}}, diff --git a/parser/pageparser/pageparser_shortcode_test.go b/parser/pageparser/pageparser_shortcode_test.go index b8bf5f727..54580217c 100644 --- a/parser/pageparser/pageparser_shortcode_test.go +++ b/parser/pageparser/pageparser_shortcode_test.go @@ -51,8 +51,10 @@ var shortCodeLexerTests = []lexerTest{ {"simple with markup", `{{% sc1 %}}`, []Item{tstLeftMD, tstSC1, tstRightMD, tstEOF}}, {"with spaces", `{{< sc1 >}}`, []Item{tstLeftNoMD, tstSC1, tstRightNoMD, tstEOF}}, - {"mismatched rightDelim", `{{< sc1 %}}`, []Item{tstLeftNoMD, tstSC1, - nti(tError, "unrecognized character in shortcode action: U+0025 '%'. Note: Parameters with non-alphanumeric args must be quoted")}}, + {"mismatched rightDelim", `{{< sc1 %}}`, []Item{ + tstLeftNoMD, tstSC1, + nti(tError, "unrecognized character in shortcode action: U+0025 '%'. Note: Parameters with non-alphanumeric args must be quoted"), + }}, {"inner, markup", `{{% sc1 %}} inner {{% /sc1 %}}`, []Item{ tstLeftMD, tstSC1, @@ -65,57 +67,77 @@ var shortCodeLexerTests = []lexerTest{ tstEOF, }}, {"close, but no open", `{{< /sc1 >}}`, []Item{ - tstLeftNoMD, nti(tError, "got closing shortcode, but none is open")}}, + tstLeftNoMD, nti(tError, "got closing shortcode, but none is open"), + }}, {"close wrong", `{{< sc1 >}}{{< /another >}}`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, tstLeftNoMD, tstSCClose, - nti(tError, "closing tag for shortcode 'another' does not match start tag")}}, + nti(tError, "closing tag for shortcode 'another' does not match start tag"), + }}, {"close, but no open, more", `{{< sc1 >}}{{< /sc1 >}}{{< /another >}}`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, tstLeftNoMD, tstSCClose, tstSC1, tstRightNoMD, tstLeftNoMD, tstSCClose, - nti(tError, "closing tag for shortcode 'another' does not match start tag")}}, + nti(tError, "closing tag for shortcode 'another' does not match start tag"), + }}, {"close with extra keyword", `{{< sc1 >}}{{< /sc1 keyword>}}`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, tstLeftNoMD, tstSCClose, tstSC1, - nti(tError, "unclosed shortcode")}}, + nti(tError, "unclosed shortcode"), + }}, {"float param, positional", `{{< sc1 3.14 >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "3.14"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "3.14"), tstRightNoMD, tstEOF, + }}, {"float param, named", `{{< sc1 param1=3.14 >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "3.14"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "3.14"), tstRightNoMD, tstEOF, + }}, {"named param, raw string", `{{< sc1 param1=` + "`" + "Hello World" + "`" + " >}}", []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "Hello World"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "Hello World"), tstRightNoMD, tstEOF, + }}, {"float param, named, space before", `{{< sc1 param1= 3.14 >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "3.14"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "3.14"), tstRightNoMD, tstEOF, + }}, {"Youtube id", `{{< sc1 -ziL-Q_456igdO-4 >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "-ziL-Q_456igdO-4"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "-ziL-Q_456igdO-4"), tstRightNoMD, tstEOF, + }}, {"non-alphanumerics param quoted", `{{< sc1 "-ziL-.%QigdO-4" >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "-ziL-.%QigdO-4"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "-ziL-.%QigdO-4"), tstRightNoMD, tstEOF, + }}, {"raw string", `{{< sc1` + "`" + "Hello World" + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), tstRightNoMD, tstEOF, + }}, {"raw string with newline", `{{< sc1` + "`" + `Hello World` + "`" + ` >}}`, []Item{ tstLeftNoMD, tstSC1, nti(tScParam, `Hello - World`), tstRightNoMD, tstEOF}}, + World`), tstRightNoMD, tstEOF, + }}, {"raw string with escape character", `{{< sc1` + "`" + `Hello \b World` + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, `Hello \b World`), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, `Hello \b World`), tstRightNoMD, tstEOF, + }}, {"two params", `{{< sc1 param1 param2 >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstParam2, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstParam2, tstRightNoMD, tstEOF, + }}, // issue #934 {"self-closing", `{{< sc1 />}}`, []Item{ - tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, tstEOF, + }}, // Issue 2498 {"multiple self-closing", `{{< sc1 />}}{{< sc1 />}}`, []Item{ tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, - tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, tstEOF, + }}, {"self-closing with param", `{{< sc1 param1 />}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, tstEOF, + }}, {"multiple self-closing with param", `{{< sc1 param1 />}}{{< sc1 param1 />}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, - tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, tstEOF, + }}, {"multiple different self-closing with param", `{{< sc1 param1 />}}{{< sc2 param1 />}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, - tstLeftNoMD, tstSC2, tstParam1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC2, tstParam1, tstSCClose, tstRightNoMD, tstEOF, + }}, {"nested simple", `{{< sc1 >}}{{< sc2 >}}{{< /sc1 >}}`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, tstLeftNoMD, tstSC2, tstRightNoMD, - tstLeftNoMD, tstSCClose, tstSC1, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSCClose, tstSC1, tstRightNoMD, tstEOF, + }}, {"nested complex", `{{< sc1 >}}ab{{% sc2 param1 %}}cd{{< sc3 >}}ef{{< /sc3 >}}gh{{% /sc2 %}}ij{{< /sc1 >}}kl`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, nti(tText, "ab"), @@ -132,64 +154,93 @@ var shortCodeLexerTests = []lexerTest{ }}, {"two quoted params", `{{< sc1 "param nr. 1" "param nr. 2" >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "param nr. 1"), nti(tScParam, "param nr. 2"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "param nr. 1"), nti(tScParam, "param nr. 2"), tstRightNoMD, tstEOF, + }}, {"two named params", `{{< sc1 param1="Hello World" param2="p2Val">}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstVal, tstParam2, nti(tScParamVal, "p2Val"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstVal, tstParam2, nti(tScParamVal, "p2Val"), tstRightNoMD, tstEOF, + }}, {"escaped quotes", `{{< sc1 param1=\"Hello World\" >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstVal, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstVal, tstRightNoMD, tstEOF, + }}, {"escaped quotes, positional param", `{{< sc1 \"param1\" >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstRightNoMD, tstEOF, + }}, {"escaped quotes inside escaped quotes", `{{< sc1 param1=\"Hello \"escaped\" World\" >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, - nti(tScParamVal, `Hello `), nti(tError, `got positional parameter 'escaped'. Cannot mix named and positional parameters`)}}, - {"escaped quotes inside nonescaped quotes", - `{{< sc1 param1="Hello \"escaped\" World" >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, `Hello "escaped" World`), tstRightNoMD, tstEOF}}, - {"escaped quotes inside nonescaped quotes in positional param", - `{{< sc1 "Hello \"escaped\" World" >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, `Hello "escaped" World`), tstRightNoMD, tstEOF}}, + nti(tScParamVal, `Hello `), nti(tError, `got positional parameter 'escaped'. Cannot mix named and positional parameters`), + }}, + { + "escaped quotes inside nonescaped quotes", + `{{< sc1 param1="Hello \"escaped\" World" >}}`, + []Item{ + tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, `Hello "escaped" World`), tstRightNoMD, tstEOF, + }, + }, + { + "escaped quotes inside nonescaped quotes in positional param", + `{{< sc1 "Hello \"escaped\" World" >}}`, + []Item{ + tstLeftNoMD, tstSC1, nti(tScParam, `Hello "escaped" World`), tstRightNoMD, tstEOF, + }, + }, {"escaped raw string, named param", `{{< sc1 param1=` + `\` + "`" + "Hello World" + `\` + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tError, "unrecognized escape character")}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tError, "unrecognized escape character"), + }}, {"escaped raw string, positional param", `{{< sc1 param1 ` + `\` + "`" + "Hello World" + `\` + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tError, "unrecognized escape character")}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tError, "unrecognized escape character"), + }}, {"two raw string params", `{{< sc1` + "`" + "Hello World" + "`" + "`" + "Second Param" + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), nti(tScParam, "Second Param"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), nti(tScParam, "Second Param"), tstRightNoMD, tstEOF, + }}, {"unterminated quote", `{{< sc1 param2="Hello World>}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam2, nti(tError, "unterminated quoted string in shortcode parameter-argument: 'Hello World>}}'")}}, + tstLeftNoMD, tstSC1, tstParam2, nti(tError, "unterminated quoted string in shortcode parameter-argument: 'Hello World>}}'"), + }}, {"unterminated raw string", `{{< sc1` + "`" + "Hello World" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tError, "unterminated raw string in shortcode parameter-argument: 'Hello World >}}'")}}, + tstLeftNoMD, tstSC1, nti(tError, "unterminated raw string in shortcode parameter-argument: 'Hello World >}}'"), + }}, {"unterminated raw string in second argument", `{{< sc1` + "`" + "Hello World" + "`" + "`" + "Second Param" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), nti(tError, "unterminated raw string in shortcode parameter-argument: 'Second Param >}}'")}}, + tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), nti(tError, "unterminated raw string in shortcode parameter-argument: 'Second Param >}}'"), + }}, {"one named param, one not", `{{< sc1 param1="Hello World" p2 >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstVal, - nti(tError, "got positional parameter 'p2'. Cannot mix named and positional parameters")}}, + nti(tError, "got positional parameter 'p2'. Cannot mix named and positional parameters"), + }}, {"one named param, one quoted positional param, both raw strings", `{{< sc1 param1=` + "`" + "Hello World" + "`" + "`" + "Second Param" + "`" + ` >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstVal, - nti(tError, "got quoted positional parameter. Cannot mix named and positional parameters")}}, + nti(tError, "got quoted positional parameter. Cannot mix named and positional parameters"), + }}, {"one named param, one quoted positional param", `{{< sc1 param1="Hello World" "And Universe" >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstVal, - nti(tError, "got quoted positional parameter. Cannot mix named and positional parameters")}}, + nti(tError, "got quoted positional parameter. Cannot mix named and positional parameters"), + }}, {"one quoted positional param, one named param", `{{< sc1 "param1" param2="And Universe" >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, - nti(tError, "got named parameter 'param2'. Cannot mix named and positional parameters")}}, + nti(tError, "got named parameter 'param2'. Cannot mix named and positional parameters"), + }}, {"ono positional param, one not", `{{< sc1 param1 param2="Hello World">}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, - nti(tError, "got named parameter 'param2'. Cannot mix named and positional parameters")}}, + nti(tError, "got named parameter 'param2'. Cannot mix named and positional parameters"), + }}, {"commented out", `{{</* sc1 */>}}`, []Item{ - nti(tText, "{{<"), nti(tText, " sc1 "), nti(tText, ">}}"), tstEOF}}, + nti(tText, "{{<"), nti(tText, " sc1 "), nti(tText, ">}}"), tstEOF, + }}, {"commented out, with asterisk inside", `{{</* sc1 "**/*.pdf" */>}}`, []Item{ - nti(tText, "{{<"), nti(tText, " sc1 \"**/*.pdf\" "), nti(tText, ">}}"), tstEOF}}, + nti(tText, "{{<"), nti(tText, " sc1 \"**/*.pdf\" "), nti(tText, ">}}"), tstEOF, + }}, {"commented out, missing close", `{{</* sc1 >}}`, []Item{ - nti(tError, "comment must be closed")}}, + nti(tError, "comment must be closed"), + }}, {"commented out, misplaced close", `{{</* sc1 >}}*/`, []Item{ - nti(tError, "comment must be closed")}}, + nti(tError, "comment must be closed"), + }}, // Inline shortcodes {"basic inline", `{{< sc1.inline >}}Hello World{{< /sc1.inline >}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstEOF}}, {"basic inline with space", `{{< sc1.inline >}}Hello World{{< / sc1.inline >}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstEOF}}, {"inline self closing", `{{< sc1.inline >}}Hello World{{< /sc1.inline >}}Hello World{{< sc1.inline />}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSC1Inline, tstSCClose, tstRightNoMD, tstEOF}}, {"inline self closing, then a new inline", `{{< sc1.inline >}}Hello World{{< /sc1.inline >}}Hello World{{< sc1.inline />}}{{< sc2.inline >}}Hello World{{< /sc2.inline >}}`, []Item{ tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSC1Inline, tstSCClose, tstRightNoMD, - tstLeftNoMD, tstSC2Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC2Inline, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC2Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC2Inline, tstRightNoMD, tstEOF, + }}, {"inline with template syntax", `{{< sc1.inline >}}{{ .Get 0 }}{{ .Get 1 }}{{< /sc1.inline >}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, nti(tText, "{{ .Get 0 }}"), nti(tText, "{{ .Get 1 }}"), tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstEOF}}, {"inline with nested shortcode (not supported)", `{{< sc1.inline >}}Hello World{{< sc1 >}}{{< /sc1.inline >}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, nti(tError, "inline shortcodes do not support nesting")}}, {"inline case mismatch", `{{< sc1.Inline >}}Hello World{{< /sc1.Inline >}}`, []Item{tstLeftNoMD, nti(tError, "period in shortcode name only allowed for inline identifiers")}}, diff --git a/publisher/htmlElementsCollector.go b/publisher/htmlElementsCollector.go index b9b0f4e11..82846e3d0 100644 --- a/publisher/htmlElementsCollector.go +++ b/publisher/htmlElementsCollector.go @@ -14,15 +14,14 @@ package publisher import ( - "regexp" - - "github.com/gohugoio/hugo/helpers" - "golang.org/x/net/html" - "bytes" + "regexp" "sort" "strings" "sync" + + "github.com/gohugoio/hugo/helpers" + "golang.org/x/net/html" ) func newHTMLElementsCollector() *htmlElementsCollector { @@ -52,7 +51,6 @@ func (h *HTMLElements) Merge(other HTMLElements) { h.Tags = helpers.UniqueStringsReuse(h.Tags) h.Classes = helpers.UniqueStringsReuse(h.Classes) h.IDs = helpers.UniqueStringsReuse(h.IDs) - } func (h *HTMLElements) Sort() { @@ -153,7 +151,6 @@ func (c *cssClassCollectorWriter) insertStandinHTMLElement(el string) (string, s } newv := strings.Replace(el, tag, "div", 1) return newv, strings.ToLower(tag) - } func (c *cssClassCollectorWriter) endCollecting(drop bool) { @@ -196,7 +193,6 @@ type htmlElementsCollector struct { } func (c *htmlElementsCollector) getHTMLElements() HTMLElements { - var ( classes []string ids []string diff --git a/publisher/htmlElementsCollector_test.go b/publisher/htmlElementsCollector_test.go index ab1529288..2c2fd3733 100644 --- a/publisher/htmlElementsCollector_test.go +++ b/publisher/htmlElementsCollector_test.go @@ -68,9 +68,11 @@ func TestClassCollector(t *testing.T) { </div> </body>`, f("body div", "class1 class2 class3", "")}, - {"Alpine bind 2", `<div x-bind:class="{ 'bg-black': filter.checked }" + { + "Alpine bind 2", `<div x-bind:class="{ 'bg-black': filter.checked }" class="inline-block mr-1 mb-2 rounded bg-gray-300 px-2 py-2">FOO</div>`, - f("div", "bg-black bg-gray-300 inline-block mb-2 mr-1 px-2 py-2 rounded", "")}, + f("div", "bg-black bg-gray-300 inline-block mb-2 mr-1 px-2 py-2 rounded", ""), + }, {"Alpine bind 3", `<div x-bind:class="{ 'text-gray-800': !checked, 'text-white': checked }"></div>`, f("div", "text-gray-800 text-white", "")}, {"Alpine bind 4", `<div x-bind:class="{ 'text-gray-800': !checked, @@ -97,7 +99,6 @@ func TestClassCollector(t *testing.T) { c.Assert(got, qt.DeepEquals, test.expect) }) } - } func BenchmarkClassCollectorWriter(b *testing.B) { diff --git a/publisher/publisher.go b/publisher/publisher.go index ac2151529..fc1fc0799 100644 --- a/publisher/publisher.go +++ b/publisher/publisher.go @@ -186,5 +186,4 @@ func (p DestinationPublisher) createTransformerChain(f Descriptor) transform.Cha } return transformers - } diff --git a/related/inverted_index.go b/related/inverted_index.go index 79dd4577c..2e0ea295d 100644 --- a/related/inverted_index.go +++ b/related/inverted_index.go @@ -180,7 +180,6 @@ func (idx *InvertedIndex) Add(docs ...Document) error { } return err - } // queryElement holds the index name and keywords that can be used to compose a diff --git a/related/inverted_index_test.go b/related/inverted_index_test.go index 576928aea..fdef06b13 100644 --- a/related/inverted_index_test.go +++ b/related/inverted_index_test.go @@ -86,7 +86,6 @@ func (d *testDoc) PublishDate() time.Time { } func TestSearch(t *testing.T) { - config := Config{ Threshold: 90, IncludeNewer: false, @@ -97,7 +96,7 @@ func TestSearch(t *testing.T) { } idx := NewInvertedIndex(config) - //idx.debug = true + // idx.debug = true docs := []Document{ newTestDoc("tags", "a", "b", "c", "d"), @@ -119,7 +118,6 @@ func TestSearch(t *testing.T) { set2, found := idx.index["keywords"] c.Assert(found, qt.Equals, true) c.Assert(len(set2), qt.Equals, 2) - }) t.Run("search-tags", func(t *testing.T) { @@ -198,7 +196,6 @@ func TestSearch(t *testing.T) { c.Assert(m[i].Name(), qt.Equals, fmt.Sprintf("doc%d", i)) } }) - } func TestToKeywordsToLower(t *testing.T) { @@ -213,11 +210,9 @@ func TestToKeywordsToLower(t *testing.T) { StringKeyword("b"), StringKeyword("c"), }) - } func BenchmarkRelatedNewIndex(b *testing.B) { - pages := make([]*testDoc, 100) numkeywords := 30 allKeywords := make([]string, numkeywords) @@ -272,11 +267,9 @@ func BenchmarkRelatedNewIndex(b *testing.B) { idx.Add(docs...) } }) - } func BenchmarkRelatedMatchesIn(b *testing.B) { - q1 := newQueryElement("tags", StringsToKeywords("keyword2", "keyword5", "keyword32", "asdf")...) q2 := newQueryElement("keywords", StringsToKeywords("keyword3", "keyword4")...) diff --git a/releaser/git.go b/releaser/git.go index 19cf072ee..7d2d43e2a 100644 --- a/releaser/git.go +++ b/releaser/git.go @@ -85,7 +85,7 @@ func gitInfosToChangeLog(infos, docInfos gitInfos) *changeLog { for _, info := range infos { los := strings.ToLower(info.Subject) isFix := strings.Contains(los, "fix") - var category = otherChanges + category := otherChanges // TODO(bep) improve if regexp.MustCompile("(?i)deprecate").MatchString(los) { @@ -176,7 +176,6 @@ func (c countribCount) AuthorLink() string { } return c.Author[:strings.Index(c.Author, "@")] - } type contribCounts []countribCount @@ -298,7 +297,6 @@ func gitShort(args ...string) (output string, err error) { func tagExists(tag string) (bool, error) { out, err := git("tag", "-l", tag) - if err != nil { return false, err } diff --git a/releaser/git_test.go b/releaser/git_test.go index 1c5f78886..21d261a62 100644 --- a/releaser/git_test.go +++ b/releaser/git_test.go @@ -45,7 +45,6 @@ See #456 c.Assert(len(issues), qt.Equals, 4) c.Assert(issues[0], qt.Equals, 123) c.Assert(issues[2], qt.Equals, 543) - } func TestGitVersionTagBefore(t *testing.T) { @@ -66,7 +65,6 @@ func TestTagExists(t *testing.T) { b2, err := tagExists("adfagdsfg") c.Assert(err, qt.IsNil) c.Assert(b2, qt.Equals, false) - } func skipIfCI(t *testing.T) { diff --git a/releaser/github.go b/releaser/github.go index ba019ccad..4ec722baf 100644 --- a/releaser/github.go +++ b/releaser/github.go @@ -112,7 +112,6 @@ func (g *gitHubAPI) fetchRepo() (gitHubRepo, error) { repo.Contributors = contributors return repo, err - } func doGitHubRequest(req *http.Request, v interface{}) error { diff --git a/releaser/releasenotes_writer.go b/releaser/releasenotes_writer.go index de7bb3d35..1dd910940 100644 --- a/releaser/releasenotes_writer.go +++ b/releaser/releasenotes_writer.go @@ -175,7 +175,6 @@ func writeReleaseNotes(version string, infosMain, infosDocs gitInfos, to io.Writ } return nil - } func fetchThemeCount() (int, error) { @@ -235,16 +234,12 @@ func (r *ReleaseHandler) releaseNotesState(version string) (releaseNotesState, e } return releaseNotesNone, nil - } func (r *ReleaseHandler) writeReleaseNotesToTemp(version string, isPatch bool, infosMain, infosDocs gitInfos) (string, error) { - docsTempPath, name := getReleaseNotesDocsTempDirAndName(version, isPatch) - var ( - w io.WriteCloser - ) + var w io.WriteCloser if !r.try { os.Mkdir(docsTempPath, os.ModePerm) @@ -269,7 +264,6 @@ func (r *ReleaseHandler) writeReleaseNotesToTemp(version string, isPatch bool, i } return name, nil - } func (r *ReleaseHandler) writeReleaseNotesToDocs(title, description, sourceFilename string) (string, error) { @@ -324,5 +318,4 @@ categories: ["Releases"]%s } return targetFullFilename, nil - } diff --git a/releaser/releasenotes_writer_test.go b/releaser/releasenotes_writer_test.go index 5013c6522..bffcb1ccb 100644 --- a/releaser/releasenotes_writer_test.go +++ b/releaser/releasenotes_writer_test.go @@ -41,5 +41,4 @@ func _TestReleaseNotesWriter(t *testing.T) { c.Assert(writeReleaseNotes("0.21", infos, infos, &b), qt.IsNil) fmt.Println(b.String()) - } diff --git a/resources/image.go b/resources/image.go index e999c5d96..ac0a0cc97 100644 --- a/resources/image.go +++ b/resources/image.go @@ -76,13 +76,10 @@ func (i *imageResource) Exif() *exif.Exif { } func (i *imageResource) getExif() *exif.Exif { - i.metaInit.Do(func() { - supportsExif := i.Format == images.JPEG || i.Format == images.TIFF if !supportsExif { return - } key := i.getImageMetaCacheTargetPath() @@ -104,7 +101,6 @@ func (i *imageResource) getExif() *exif.Exif { } create := func(info filecache.ItemInfo, w io.WriteCloser) (err error) { - f, err := i.root.ReadSeekCloser() if err != nil { i.metaInitErr = err @@ -123,11 +119,9 @@ func (i *imageResource) getExif() *exif.Exif { // Also write it to cache enc := json.NewEncoder(w) return enc.Encode(i.meta) - } _, i.metaInitErr = i.getSpec().imageCache.fileCache.ReadOrCreate(key, read, create) - }) if i.metaInitErr != nil { @@ -296,7 +290,6 @@ func (i *imageResource) doWithImageConfig(conf images.ImageConfig, f func(src im return ci, converted, nil }) - if err != nil { if i.root != nil && i.root.getFileInfo() != nil { return nil, errors.Wrapf(err, "image %q", i.root.getFileInfo().Meta().Filename()) diff --git a/resources/image_test.go b/resources/image_test.go index 1be9a5f8d..542ecb9b9 100644 --- a/resources/image_test.go +++ b/resources/image_test.go @@ -413,11 +413,9 @@ func TestImageExif(t *testing.T) { 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) @@ -431,7 +429,6 @@ func BenchmarkImageExif(b *testing.B) { 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) { @@ -443,7 +440,6 @@ func BenchmarkImageExif(b *testing.B) { for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } - }) b.Run("Cold cache, 10", func(b *testing.B) { @@ -457,7 +453,6 @@ func BenchmarkImageExif(b *testing.B) { getAndCheckExif(c, images[i]) } } - }) b.Run("Warm cache", func(b *testing.B) { @@ -475,9 +470,7 @@ func BenchmarkImageExif(b *testing.B) { for i := 0; i < b.N; i++ { getAndCheckExif(c, images[i]) } - }) - } // usesFMA indicates whether "fused multiply and add" (FMA) instruction is @@ -680,7 +673,6 @@ func TestImageOperationsGolden(t *testing.T) { f1.Close() f2.Close() } - } func BenchmarkResizeParallel(b *testing.B) { diff --git a/resources/images/color.go b/resources/images/color.go index b17173e26..0a0db9fe0 100644 --- a/resources/images/color.go +++ b/resources/images/color.go @@ -81,5 +81,4 @@ func hexStringToColor(s string) (color.Color, error) { } return color.RGBA{b[0], b[1], b[2], b[3]}, nil - } diff --git a/resources/images/color_test.go b/resources/images/color_test.go index 3ef9f76cc..0a1718180 100644 --- a/resources/images/color_test.go +++ b/resources/images/color_test.go @@ -74,7 +74,6 @@ func TestAddColorToPalette(t *testing.T) { c.Assert(AddColorToPalette(white, palette), qt.HasLen, 2) c.Assert(AddColorToPalette(blue1, palette), qt.HasLen, 3) c.Assert(AddColorToPalette(blue2, palette), qt.HasLen, 3) - } func TestReplaceColorInPalette(t *testing.T) { diff --git a/resources/images/config_test.go b/resources/images/config_test.go index f60cce9ef..2a0de9ec0 100644 --- a/resources/images/config_test.go +++ b/resources/images/config_test.go @@ -77,7 +77,6 @@ func TestDecodeConfig(t *testing.T) { imaging = imagingConfig.Cfg c.Assert(imaging.Exif.DisableLatLong, qt.Equals, true) c.Assert(imaging.Exif.ExcludeFields, qt.Equals, "GPS|Exif|Exposure[M|P|B]|Contrast|Resolution|Sharp|JPEG|Metering|Sensing|Saturation|ColorSpace|Flash|WhiteBalance") - } func TestDecodeImageConfig(t *testing.T) { diff --git a/resources/images/exif/exif.go b/resources/images/exif/exif.go index b5161f770..720d200c9 100644 --- a/resources/images/exif/exif.go +++ b/resources/images/exif/exif.go @@ -93,7 +93,6 @@ func compileRegexp(expression string) (*regexp.Regexp, error) { } return regexp.Compile(expression) - } func NewDecoder(options ...func(*Decoder) error) (*Decoder, error) { @@ -118,7 +117,6 @@ func (d *Decoder) Decode(r io.Reader) (ex *Exif, err error) { x, err = _exif.Decode(r) if err != nil { if err.Error() == "EOF" { - // Found no Exif return nil, nil } @@ -190,7 +188,6 @@ func decodeTag(x *_exif.Exif, f _exif.FieldName, t *tiff.Tag) (interface{}, erro } return rv, nil - } // Code borrowed from exif.DateTime and adjusted. @@ -202,7 +199,6 @@ func tryParseDate(x *_exif.Exif, s string) (time.Time, error) { timeZone = tz } return time.ParseInLocation(exifTimeLayout, dateStr, timeZone) - } type exifWalker struct { diff --git a/resources/images/exif/exif_test.go b/resources/images/exif/exif_test.go index c3cfad1cc..12e3b7f71 100644 --- a/resources/images/exif/exif_test.go +++ b/resources/images/exif/exif_test.go @@ -60,7 +60,6 @@ func TestExif(t *testing.T) { err = json.Unmarshal(data, x2) c.Assert(x2, eq, x) - } func TestExifPNG(t *testing.T) { diff --git a/resources/images/filters_test.go b/resources/images/filters_test.go index 1243e483b..84c8b540d 100644 --- a/resources/images/filters_test.go +++ b/resources/images/filters_test.go @@ -30,5 +30,4 @@ func TestFilterHash(t *testing.T) { c.Assert(helpers.HashString(f.Grayscale()), qt.Not(qt.Equals), helpers.HashString(f.Invert())) c.Assert(helpers.HashString(f.Gamma(32)), qt.Not(qt.Equals), helpers.HashString(f.Gamma(33))) c.Assert(helpers.HashString(f.Gamma(32)), qt.Equals, helpers.HashString(f.Gamma(32))) - } diff --git a/resources/images/image.go b/resources/images/image.go index a13c1a59e..88eed2f7e 100644 --- a/resources/images/image.go +++ b/resources/images/image.go @@ -92,7 +92,6 @@ func (i *Image) EncodeTo(conf ImageConfig, img image.Image, w io.Writer) error { default: return errors.New("format not supported") } - } // Height returns i's height. @@ -165,7 +164,6 @@ func NewImageProcessor(cfg ImagingConfig) (*ImageProcessor, error) { exif.ExcludeFields(e.ExcludeFields), exif.IncludeFields(e.IncludeFields), ) - if err != nil { return nil, err } @@ -174,7 +172,6 @@ func NewImageProcessor(cfg ImagingConfig) (*ImageProcessor, error) { Cfg: cfg, exifDecoder: exifDecoder, }, nil - } type ImageProcessor struct { diff --git a/resources/images/smartcrop.go b/resources/images/smartcrop.go index e0181b671..76f547ef0 100644 --- a/resources/images/smartcrop.go +++ b/resources/images/smartcrop.go @@ -70,5 +70,4 @@ func (p *ImageProcessor) smartCrop(img image.Image, width, height int, filter gi } return img.Bounds().Intersect(rect), nil - } diff --git a/resources/internal/key.go b/resources/internal/key.go index d67d4a7e1..ba13bd2f8 100644 --- a/resources/internal/key.go +++ b/resources/internal/key.go @@ -39,5 +39,4 @@ func (k ResourceTransformationKey) Value() string { } return k.Name + "_" + helpers.HashString(k.elements...) - } diff --git a/resources/jsconfig/jsconfig.go b/resources/jsconfig/jsconfig.go index 9b399bfe7..1fd6d6103 100644 --- a/resources/jsconfig/jsconfig.go +++ b/resources/jsconfig/jsconfig.go @@ -69,7 +69,6 @@ func (b *Builder) AddSourceRoot(root string) { b.sourceRootsMu.Lock() b.sourceRoots[root] = true b.sourceRootsMu.Unlock() - } // CompilerOptions holds compilerOptions for jsonconfig.json. diff --git a/resources/page/page_data_test.go b/resources/page/page_data_test.go index f161fad3c..c7d764d8a 100644 --- a/resources/page/page_data_test.go +++ b/resources/page/page_data_test.go @@ -16,7 +16,6 @@ package page import ( "bytes" "testing" - "text/template" qt "github.com/frankban/quicktest" @@ -53,5 +52,4 @@ func TestPageData(t *testing.T) { c.Assert(templ.Execute(&buff, data), qt.IsNil) c.Assert(buff.String(), qt.Contains, "Pages(2)") - } diff --git a/resources/page/page_generate/generate_page_wrappers.go b/resources/page/page_generate/generate_page_wrappers.go index 4c63962fa..ff3744c20 100644 --- a/resources/page/page_generate/generate_page_wrappers.go +++ b/resources/page/page_generate/generate_page_wrappers.go @@ -56,7 +56,6 @@ var ( func Generate(c *codegen.Inspector) error { if err := generateMarshalJSON(c); err != nil { return errors.Wrap(err, "failed to generate JSON marshaler") - } if err := generateDeprecatedWrappers(c); err != nil { @@ -73,7 +72,6 @@ func Generate(c *codegen.Inspector) error { func generateMarshalJSON(c *codegen.Inspector) error { filename := filepath.Join(c.ProjectRootDir, packageDir, "page_marshaljson.autogen.go") f, err := os.Create(filename) - if err != nil { return err } diff --git a/resources/page/page_kinds_test.go b/resources/page/page_kinds_test.go index 8ad3493ee..357be6739 100644 --- a/resources/page/page_kinds_test.go +++ b/resources/page/page_kinds_test.go @@ -34,5 +34,4 @@ func TestKind(t *testing.T) { c.Assert(GetKind("Page"), qt.Equals, KindPage) c.Assert(GetKind("Home"), qt.Equals, KindHome) c.Assert(GetKind("SEction"), qt.Equals, KindSection) - } diff --git a/resources/page/page_marshaljson.autogen.go b/resources/page/page_marshaljson.autogen.go index 2286f1e63..ace475909 100644 --- a/resources/page/page_marshaljson.autogen.go +++ b/resources/page/page_marshaljson.autogen.go @@ -17,6 +17,9 @@ package page import ( "encoding/json" + "html/template" + "time" + "github.com/bep/gitmap" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config" @@ -26,8 +29,6 @@ import ( "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/navigation" "github.com/gohugoio/hugo/source" - "html/template" - "time" ) func MarshalPageToJSON(p Page) ([]byte, error) { diff --git a/resources/page/page_matcher.go b/resources/page/page_matcher.go index 881f76e33..7d3db373b 100644 --- a/resources/page/page_matcher.go +++ b/resources/page/page_matcher.go @@ -41,7 +41,6 @@ type PageMatcher struct { // Matches returns whether p matches this matcher. func (m PageMatcher) Matches(p Page) bool { - if m.Kind != "" { g, err := glob.GetGlob(m.Kind) if err == nil && !g.Match(p.Kind()) { @@ -87,5 +86,4 @@ func DecodePageMatcher(m interface{}, v *PageMatcher) error { v.Path = filepath.ToSlash(strings.ToLower(v.Path)) return nil - } diff --git a/resources/page/page_matcher_test.go b/resources/page/page_matcher_test.go index 24b304772..745a6aa32 100644 --- a/resources/page/page_matcher_test.go +++ b/resources/page/page_matcher_test.go @@ -50,7 +50,6 @@ func TestPageMatcher(t *testing.T) { c.Assert(m.Matches(p1), qt.Equals, true) c.Assert(m.Matches(p2), qt.Equals, false) c.Assert(m.Matches(p3), qt.Equals, true) - }) c.Run("Decode", func(c *qt.C) { @@ -59,5 +58,4 @@ func TestPageMatcher(t *testing.T) { c.Assert(DecodePageMatcher(map[string]interface{}{"kind": "home", "path": filepath.FromSlash("/a/b/**")}, &v), qt.IsNil) c.Assert(v, qt.Equals, PageMatcher{Kind: "home", Path: "/a/b/**"}) }) - } diff --git a/resources/page/page_nop.go b/resources/page/page_nop.go index 293b399c7..94515d27d 100644 --- a/resources/page/page_nop.go +++ b/resources/page/page_nop.go @@ -66,8 +66,8 @@ func (p *nopPage) RSSLink() template.URL { func (p *nopPage) Author() Author { return Author{} - } + func (p *nopPage) Authors() AuthorList { return nil } @@ -119,6 +119,7 @@ func (p *nopPage) Description() string { func (p *nopPage) RefFrom(argsm map[string]interface{}, source interface{}) (string, error) { return "", nil } + func (p *nopPage) RelRefFrom(argsm map[string]interface{}, source interface{}) (string, error) { return "", nil } @@ -356,6 +357,7 @@ func (p *nopPage) PublishDate() (t time.Time) { func (p *nopPage) PrevInSection() Page { return nil } + func (p *nopPage) NextInSection() Page { return nil } diff --git a/resources/page/page_paths.go b/resources/page/page_paths.go index 6ef9bced6..fc576f05a 100644 --- a/resources/page/page_paths.go +++ b/resources/page/page_paths.go @@ -16,7 +16,6 @@ package page import ( "path" "path/filepath" - "strings" "github.com/gohugoio/hugo/helpers" @@ -112,7 +111,6 @@ func isHtmlIndex(s string) bool { } func CreateTargetPaths(d TargetPathDescriptor) (tp TargetPaths) { - if d.Type.Name == "" { panic("CreateTargetPath: missing type") } @@ -205,7 +203,6 @@ func CreateTargetPaths(d TargetPathDescriptor) (tp TargetPaths) { if d.ExpandedPermalink != "" { pagePath = pjoin(pagePath, d.ExpandedPermalink) - } else { if d.Dir != "" { pagePath = pjoin(pagePath, d.Dir) @@ -273,7 +270,6 @@ func CreateTargetPaths(d TargetPathDescriptor) (tp TargetPaths) { pagePath = path.Join(pagePath, addSuffix(base, d.Type.MediaType.FullSuffix())) } else { pagePath = addSuffix(pagePath, d.Type.MediaType.FullSuffix()) - } if !isHtmlIndex(pagePath) { diff --git a/resources/page/page_paths_test.go b/resources/page/page_paths_test.go index 53f8b80ef..ab7164f46 100644 --- a/resources/page/page_paths_test.go +++ b/resources/page/page_paths_test.go @@ -14,19 +14,17 @@ package page import ( + "fmt" "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/media" - "fmt" - "github.com/gohugoio/hugo/output" ) func TestPageTargetPath(t *testing.T) { - pathSpec := newTestPathSpec() noExtNoDelimMediaType := media.TextType @@ -57,24 +55,29 @@ func TestPageTargetPath(t *testing.T) { Kind: KindSection, Sections: []string{"sect1"}, BaseName: "_index", - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/sect1/index.html", SubResourceBaseTarget: "/sect1", Link: "/sect1/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/sect1/index.html", SubResourceBaseTarget: "/sect1", Link: "/sect1/"}}, {"HTML taxonomy term", TargetPathDescriptor{ Kind: KindTerm, Sections: []string{"tags", "hugo"}, BaseName: "_index", - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/tags/hugo/index.html", SubResourceBaseTarget: "/tags/hugo", Link: "/tags/hugo/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/tags/hugo/index.html", SubResourceBaseTarget: "/tags/hugo", Link: "/tags/hugo/"}}, {"HTML taxonomy", TargetPathDescriptor{ Kind: KindTaxonomy, Sections: []string{"tags"}, BaseName: "_index", - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/tags/index.html", SubResourceBaseTarget: "/tags", Link: "/tags/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/tags/index.html", SubResourceBaseTarget: "/tags", Link: "/tags/"}}, { "HTML page", TargetPathDescriptor{ Kind: KindPage, Dir: "/a/b", BaseName: "mypage", Sections: []string{"a"}, - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/a/b/mypage/index.html", SubResourceBaseTarget: "/a/b/mypage", Link: "/a/b/mypage/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/a/b/mypage/index.html", SubResourceBaseTarget: "/a/b/mypage", Link: "/a/b/mypage/"}, + }, { "HTML page with index as base", TargetPathDescriptor{ @@ -82,93 +85,117 @@ func TestPageTargetPath(t *testing.T) { Dir: "/a/b", BaseName: "index", Sections: []string{"a"}, - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/a/b/index.html", SubResourceBaseTarget: "/a/b", Link: "/a/b/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/a/b/index.html", SubResourceBaseTarget: "/a/b", Link: "/a/b/"}, + }, { "HTML page with special chars", TargetPathDescriptor{ Kind: KindPage, Dir: "/a/b", BaseName: "My Page!", - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/a/b/my-page/index.html", SubResourceBaseTarget: "/a/b/my-page", Link: "/a/b/my-page/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/a/b/my-page/index.html", SubResourceBaseTarget: "/a/b/my-page", Link: "/a/b/my-page/"}, + }, {"RSS home", TargetPathDescriptor{Kind: "rss", Type: output.RSSFormat}, TargetPaths{TargetFilename: "/index.xml", SubResourceBaseTarget: "", Link: "/index.xml"}}, {"RSS section list", TargetPathDescriptor{ Kind: "rss", Sections: []string{"sect1"}, - Type: output.RSSFormat}, TargetPaths{TargetFilename: "/sect1/index.xml", SubResourceBaseTarget: "/sect1", Link: "/sect1/index.xml"}}, + Type: output.RSSFormat, + }, TargetPaths{TargetFilename: "/sect1/index.xml", SubResourceBaseTarget: "/sect1", Link: "/sect1/index.xml"}}, { "AMP page", TargetPathDescriptor{ Kind: KindPage, Dir: "/a/b/c", BaseName: "myamp", - Type: output.AMPFormat}, TargetPaths{TargetFilename: "/amp/a/b/c/myamp/index.html", SubResourceBaseTarget: "/amp/a/b/c/myamp", Link: "/amp/a/b/c/myamp/"}}, + Type: output.AMPFormat, + }, TargetPaths{TargetFilename: "/amp/a/b/c/myamp/index.html", SubResourceBaseTarget: "/amp/a/b/c/myamp", Link: "/amp/a/b/c/myamp/"}, + }, { "AMP page with URL with suffix", TargetPathDescriptor{ Kind: KindPage, Dir: "/sect/", BaseName: "mypage", URL: "/some/other/url.xhtml", - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/some/other/url.xhtml", SubResourceBaseTarget: "/some/other", Link: "/some/other/url.xhtml"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/some/other/url.xhtml", SubResourceBaseTarget: "/some/other", Link: "/some/other/url.xhtml"}, + }, { "JSON page with URL without suffix", TargetPathDescriptor{ Kind: KindPage, Dir: "/sect/", BaseName: "mypage", URL: "/some/other/path/", - Type: output.JSONFormat}, TargetPaths{TargetFilename: "/some/other/path/index.json", SubResourceBaseTarget: "/some/other/path", Link: "/some/other/path/index.json"}}, + Type: output.JSONFormat, + }, TargetPaths{TargetFilename: "/some/other/path/index.json", SubResourceBaseTarget: "/some/other/path", Link: "/some/other/path/index.json"}, + }, { "JSON page with URL without suffix and no trailing slash", TargetPathDescriptor{ Kind: KindPage, Dir: "/sect/", BaseName: "mypage", URL: "/some/other/path", - Type: output.JSONFormat}, TargetPaths{TargetFilename: "/some/other/path/index.json", SubResourceBaseTarget: "/some/other/path", Link: "/some/other/path/index.json"}}, + Type: output.JSONFormat, + }, TargetPaths{TargetFilename: "/some/other/path/index.json", SubResourceBaseTarget: "/some/other/path", Link: "/some/other/path/index.json"}, + }, { "HTML page with URL without suffix and no trailing slash", TargetPathDescriptor{ Kind: KindPage, Dir: "/sect/", BaseName: "mypage", URL: "/some/other/path", - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/some/other/path/index.html", SubResourceBaseTarget: "/some/other/path", Link: "/some/other/path/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/some/other/path/index.html", SubResourceBaseTarget: "/some/other/path", Link: "/some/other/path/"}, + }, { "HTML page with URL containing double hyphen", TargetPathDescriptor{ Kind: KindPage, Dir: "/sect/", BaseName: "mypage", URL: "/some/other--url/", - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/some/other--url/index.html", SubResourceBaseTarget: "/some/other--url", Link: "/some/other--url/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/some/other--url/index.html", SubResourceBaseTarget: "/some/other--url", Link: "/some/other--url/"}, + }, { "HTML page with expanded permalink", TargetPathDescriptor{ Kind: KindPage, Dir: "/a/b", BaseName: "mypage", ExpandedPermalink: "/2017/10/my-title/", - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/2017/10/my-title/index.html", SubResourceBaseTarget: "/2017/10/my-title", Link: "/2017/10/my-title/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/2017/10/my-title/index.html", SubResourceBaseTarget: "/2017/10/my-title", Link: "/2017/10/my-title/"}, + }, { "Paginated HTML home", TargetPathDescriptor{ Kind: KindHome, BaseName: "_index", Type: output.HTMLFormat, - Addends: "page/3"}, TargetPaths{TargetFilename: "/page/3/index.html", SubResourceBaseTarget: "/page/3", Link: "/page/3/"}}, + Addends: "page/3", + }, TargetPaths{TargetFilename: "/page/3/index.html", SubResourceBaseTarget: "/page/3", Link: "/page/3/"}, + }, { "Paginated Taxonomy terms list", TargetPathDescriptor{ Kind: KindTerm, BaseName: "_index", Sections: []string{"tags", "hugo"}, Type: output.HTMLFormat, - Addends: "page/3"}, TargetPaths{TargetFilename: "/tags/hugo/page/3/index.html", SubResourceBaseTarget: "/tags/hugo/page/3", Link: "/tags/hugo/page/3/"}}, + Addends: "page/3", + }, TargetPaths{TargetFilename: "/tags/hugo/page/3/index.html", SubResourceBaseTarget: "/tags/hugo/page/3", Link: "/tags/hugo/page/3/"}, + }, { "Regular page with addend", TargetPathDescriptor{ Kind: KindPage, Dir: "/a/b", BaseName: "mypage", Addends: "c/d/e", - Type: output.HTMLFormat}, TargetPaths{TargetFilename: "/a/b/mypage/c/d/e/index.html", SubResourceBaseTarget: "/a/b/mypage/c/d/e", Link: "/a/b/mypage/c/d/e/"}}, + Type: output.HTMLFormat, + }, TargetPaths{TargetFilename: "/a/b/mypage/c/d/e/index.html", SubResourceBaseTarget: "/a/b/mypage/c/d/e", Link: "/a/b/mypage/c/d/e/"}, + }, } for i, test := range tests { t.Run(fmt.Sprintf("langPrefixPath=%s,langPrefixLink=%s,uglyURLs=%t,name=%s", langPrefixPath, langPrefixLink, uglyURLs, test.name), func(t *testing.T) { - test.d.ForcePrefix = true test.d.PathSpec = pathSpec test.d.UglyURLs = uglyURLs @@ -206,12 +233,10 @@ func TestPageTargetPath(t *testing.T) { if !eqTargetPaths(pagePath, expected) { t.Fatalf("[%d] [%s] targetPath expected\n%#v, got:\n%#v", i, test.name, expected, pagePath) - } }) } } - } } } @@ -223,10 +248,16 @@ func TestPageTargetPathPrefix(t *testing.T) { d TargetPathDescriptor expected TargetPaths }{ - {"URL set, prefix both, no force", TargetPathDescriptor{Kind: KindPage, Type: output.JSONFormat, URL: "/mydir/my.json", ForcePrefix: false, PrefixFilePath: "pf", PrefixLink: "pl"}, - TargetPaths{TargetFilename: "/mydir/my.json", SubResourceBaseTarget: "/mydir", SubResourceBaseLink: "/mydir", Link: "/mydir/my.json"}}, - {"URL set, prefix both, force", TargetPathDescriptor{Kind: KindPage, Type: output.JSONFormat, URL: "/mydir/my.json", ForcePrefix: true, PrefixFilePath: "pf", PrefixLink: "pl"}, - TargetPaths{TargetFilename: "/pf/mydir/my.json", SubResourceBaseTarget: "/pf/mydir", SubResourceBaseLink: "/pl/mydir", Link: "/pl/mydir/my.json"}}, + { + "URL set, prefix both, no force", + TargetPathDescriptor{Kind: KindPage, Type: output.JSONFormat, URL: "/mydir/my.json", ForcePrefix: false, PrefixFilePath: "pf", PrefixLink: "pl"}, + TargetPaths{TargetFilename: "/mydir/my.json", SubResourceBaseTarget: "/mydir", SubResourceBaseLink: "/mydir", Link: "/mydir/my.json"}, + }, + { + "URL set, prefix both, force", + TargetPathDescriptor{Kind: KindPage, Type: output.JSONFormat, URL: "/mydir/my.json", ForcePrefix: true, PrefixFilePath: "pf", PrefixLink: "pl"}, + TargetPaths{TargetFilename: "/pf/mydir/my.json", SubResourceBaseTarget: "/pf/mydir", SubResourceBaseLink: "/pl/mydir", Link: "/pl/mydir/my.json"}, + }, } for i, test := range tests { @@ -244,11 +275,9 @@ func TestPageTargetPathPrefix(t *testing.T) { } }) } - } func eqTargetPaths(p1, p2 TargetPaths) bool { - if p1.Link != p2.Link { return false } diff --git a/resources/page/page_wrappers.autogen.go b/resources/page/page_wrappers.autogen.go index bc2cf968c..eefbbe2c1 100644 --- a/resources/page/page_wrappers.autogen.go +++ b/resources/page/page_wrappers.autogen.go @@ -16,10 +16,11 @@ package page import ( + "html/template" + "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" - "html/template" ) // NewDeprecatedWarningPage adds deprecation warnings to the given implementation. @@ -35,62 +36,77 @@ func (p *pageDeprecated) Filename() string { helpers.Deprecated("Page.Filename", "Use .File.Filename", false) return p.p.Filename() } + func (p *pageDeprecated) Dir() string { helpers.Deprecated("Page.Dir", "Use .File.Dir", false) return p.p.Dir() } + func (p *pageDeprecated) IsDraft() bool { helpers.Deprecated("Page.IsDraft", "Use .Draft.", false) return p.p.IsDraft() } + func (p *pageDeprecated) Extension() string { helpers.Deprecated("Page.Extension", "Use .File.Extension", false) return p.p.Extension() } + func (p *pageDeprecated) Hugo() hugo.Info { helpers.Deprecated("Page.Hugo", "Use the global hugo function.", false) return p.p.Hugo() } + func (p *pageDeprecated) Ext() string { helpers.Deprecated("Page.Ext", "Use .File.Ext", false) return p.p.Ext() } + func (p *pageDeprecated) LanguagePrefix() string { helpers.Deprecated("Page.LanguagePrefix", "Use .Site.LanguagePrefix.", false) return p.p.LanguagePrefix() } + func (p *pageDeprecated) GetParam(arg0 string) interface{} { helpers.Deprecated("Page.GetParam", "Use .Param or .Params.myParam.", false) return p.p.GetParam(arg0) } + func (p *pageDeprecated) LogicalName() string { helpers.Deprecated("Page.LogicalName", "Use .File.LogicalName", false) return p.p.LogicalName() } + func (p *pageDeprecated) BaseFileName() string { helpers.Deprecated("Page.BaseFileName", "Use .File.BaseFileName", false) return p.p.BaseFileName() } + func (p *pageDeprecated) RSSLink() template.URL { helpers.Deprecated("Page.RSSLink", "Use the Output Format's link, e.g. something like: \n {{ with .OutputFormats.Get \"RSS\" }}{{ .RelPermalink }}{{ end }}", false) return p.p.RSSLink() } + func (p *pageDeprecated) TranslationBaseName() string { helpers.Deprecated("Page.TranslationBaseName", "Use .File.TranslationBaseName", false) return p.p.TranslationBaseName() } + func (p *pageDeprecated) URL() string { helpers.Deprecated("Page.URL", "Use .Permalink or .RelPermalink. If what you want is the front matter URL value, use .Params.url", false) return p.p.URL() } + func (p *pageDeprecated) ContentBaseName() string { helpers.Deprecated("Page.ContentBaseName", "Use .File.ContentBaseName", false) return p.p.ContentBaseName() } + func (p *pageDeprecated) UniqueID() string { helpers.Deprecated("Page.UniqueID", "Use .File.UniqueID", false) return p.p.UniqueID() } + func (p *pageDeprecated) FileInfo() hugofs.FileMetaInfo { helpers.Deprecated("Page.FileInfo", "Use .File.FileInfo", false) return p.p.FileInfo() diff --git a/resources/page/pagegroup.go b/resources/page/pagegroup.go index fcae9add7..07ccbfedd 100644 --- a/resources/page/pagegroup.go +++ b/resources/page/pagegroup.go @@ -355,7 +355,6 @@ func (p PageGroup) ProbablyEq(other interface{}) bool { } return p.Pages.ProbablyEq(otherP.Pages) - } // Slice is not meant to be used externally. It's a bridge function @@ -406,7 +405,6 @@ func (psg PagesGroup) ProbablyEq(other interface{}) bool { } return true - } // ToPagesGroup tries to convert seq into a PagesGroup. diff --git a/resources/page/pagegroup_test.go b/resources/page/pagegroup_test.go index d4a3f36a6..218bd841d 100644 --- a/resources/page/pagegroup_test.go +++ b/resources/page/pagegroup_test.go @@ -216,7 +216,6 @@ func TestGroupByParamCalledWithCapitalLetterString(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(groups[0].Key, qt.Equals, testStr) - } func TestGroupByParamCalledWithSomeUnavailableParams(t *testing.T) { diff --git a/resources/page/pagemeta/page_frontmatter.go b/resources/page/pagemeta/page_frontmatter.go index 5033d70b7..a32fc5884 100644 --- a/resources/page/pagemeta/page_frontmatter.go +++ b/resources/page/pagemeta/page_frontmatter.go @@ -70,14 +70,12 @@ type FrontMatterDescriptor struct { PageURLs *URLPath } -var ( - dateFieldAliases = map[string][]string{ - fmDate: {}, - fmLastmod: {"modified"}, - fmPubDate: {"pubdate", "published"}, - fmExpiryDate: {"unpublishdate"}, - } -) +var dateFieldAliases = map[string][]string{ + fmDate: {}, + fmLastmod: {"modified"}, + fmPubDate: {"pubdate", "published"}, + fmExpiryDate: {"unpublishdate"}, +} // HandleDates updates all the dates given the current configuration and the // supplied front matter params. Note that this requires all lower-case keys @@ -263,7 +261,6 @@ func toLowerSlice(in interface{}) []string { // NewFrontmatterHandler creates a new FrontMatterHandler with the given logger and configuration. // If no logger is provided, one will be created. func NewFrontmatterHandler(logger loggers.Logger, cfg config.Provider) (FrontMatterHandler, error) { - if logger == nil { logger = loggers.NewErrorLogger() } @@ -359,7 +356,6 @@ func (f FrontMatterHandler) createDateHandler(identifiers []string, setter func( } return f.newChainedFrontMatterFieldHandler(handlers...), nil - } type frontmatterFieldHandlers int diff --git a/resources/page/pagemeta/page_frontmatter_test.go b/resources/page/pagemeta/page_frontmatter_test.go index f96d186da..7c4c77a91 100644 --- a/resources/page/pagemeta/page_frontmatter_test.go +++ b/resources/page/pagemeta/page_frontmatter_test.go @@ -25,7 +25,6 @@ import ( ) func TestDateAndSlugFromBaseFilename(t *testing.T) { - t.Parallel() c := qt.New(t) @@ -111,7 +110,6 @@ func TestFrontMatterNewConfig(t *testing.T) { c.Assert(fc.lastmod, qt.DeepEquals, []string{"d2", ":git", "lastmod", "modified", "date", "publishdate", "pubdate", "published"}) c.Assert(fc.expiryDate, qt.DeepEquals, []string{"d3", "expirydate", "unpublishdate"}) c.Assert(fc.publishDate, qt.DeepEquals, []string{"d4", "publishdate", "pubdate", "published", "date"}) - } func TestFrontMatterDatesHandlers(t *testing.T) { @@ -199,7 +197,6 @@ func TestFrontMatterDatesCustomConfig(t *testing.T) { c.Assert(handler.IsDateKey("mydate"), qt.Equals, true) c.Assert(handler.IsDateKey("publishdate"), qt.Equals, true) c.Assert(handler.IsDateKey("pubdate"), qt.Equals, true) - } func TestFrontMatterDatesDefaultKeyword(t *testing.T) { @@ -230,7 +227,6 @@ func TestFrontMatterDatesDefaultKeyword(t *testing.T) { c.Assert(d.Dates.FLastmod.Day(), qt.Equals, 2) c.Assert(d.Dates.FPublishDate.Day(), qt.Equals, 4) c.Assert(d.Dates.FExpiryDate.IsZero(), qt.Equals, true) - } func TestExpandDefaultValues(t *testing.T) { @@ -238,7 +234,6 @@ func TestExpandDefaultValues(t *testing.T) { c.Assert(expandDefaultValues([]string{"a", ":default", "d"}, []string{"b", "c"}), qt.DeepEquals, []string{"a", "b", "c", "d"}) c.Assert(expandDefaultValues([]string{"a", "b", "c"}, []string{"a", "b", "c"}), qt.DeepEquals, []string{"a", "b", "c"}) c.Assert(expandDefaultValues([]string{":default", "a", ":default", "d"}, []string{"b", "c"}), qt.DeepEquals, []string{"b", "c", "a", "b", "c", "d"}) - } func TestFrontMatterDateFieldHandler(t *testing.T) { diff --git a/resources/page/pagemeta/pagemeta_test.go b/resources/page/pagemeta/pagemeta_test.go index c251e7dab..d09b38e27 100644 --- a/resources/page/pagemeta/pagemeta_test.go +++ b/resources/page/pagemeta/pagemeta_test.go @@ -46,7 +46,8 @@ publishResources = true` List: Always, PublishResources: true, set: true, - }}, + }, + }, {[]interface{}{"true", "false"}, BuildConfig{ Render: Always, List: Never, @@ -88,5 +89,4 @@ publishResources = true` c.Assert(bcfg, eq, test.expect) } - } diff --git a/resources/page/pages_cache.go b/resources/page/pages_cache.go index e82d9a8cf..9435cb308 100644 --- a/resources/page/pages_cache.go +++ b/resources/page/pages_cache.go @@ -106,7 +106,6 @@ func (c *pageCache) getP(key string, apply func(p *Pages), pageLists ...Pages) ( } return pagesCopy, false - } // pagesEqual returns whether p1 and p2 are equal. diff --git a/resources/page/pages_language_merge.go b/resources/page/pages_language_merge.go index 11393a754..dd18b64a2 100644 --- a/resources/page/pages_language_merge.go +++ b/resources/page/pages_language_merge.go @@ -17,9 +17,7 @@ import ( "fmt" ) -var ( - _ pagesLanguageMerger = (*Pages)(nil) -) +var _ pagesLanguageMerger = (*Pages)(nil) type pagesLanguageMerger interface { MergeByLanguage(other Pages) Pages diff --git a/resources/page/pages_prev_next.go b/resources/page/pages_prev_next.go index dd767c667..f30a55da5 100644 --- a/resources/page/pages_prev_next.go +++ b/resources/page/pages_prev_next.go @@ -31,5 +31,4 @@ func (p Pages) Prev(cur Page) Page { } return p[x+1] - } diff --git a/resources/page/pages_prev_next_test.go b/resources/page/pages_prev_next_test.go index 689e102c2..0ee1564cd 100644 --- a/resources/page/pages_prev_next_test.go +++ b/resources/page/pages_prev_next_test.go @@ -78,7 +78,6 @@ func TestWeightedPagesPrev(t *testing.T) { c.Assert(w.Prev(w[0].Page), qt.Equals, w[1].Page) c.Assert(w.Prev(w[1].Page), qt.Equals, w[2].Page) c.Assert(w.Prev(w[4].Page), qt.IsNil) - } func TestWeightedPagesNext(t *testing.T) { @@ -89,5 +88,4 @@ func TestWeightedPagesNext(t *testing.T) { c.Assert(w.Next(w[0].Page), qt.IsNil) c.Assert(w.Next(w[1].Page), qt.Equals, w[0].Page) c.Assert(w.Next(w[4].Page), qt.Equals, w[3].Page) - } diff --git a/resources/page/pages_related.go b/resources/page/pages_related.go index 1a4386135..026026572 100644 --- a/resources/page/pages_related.go +++ b/resources/page/pages_related.go @@ -58,7 +58,6 @@ func (p Pages) Related(doc related.Document) (Pages, error) { } return result, nil - } // RelatedIndices searches the given indices with the search keywords from the @@ -79,7 +78,6 @@ func (p Pages) RelatedIndices(doc related.Document, indices ...interface{}) (Pag } return result, nil - } // RelatedTo searches the given indices with the corresponding values. @@ -89,14 +87,12 @@ func (p Pages) RelatedTo(args ...types.KeyValues) (Pages, error) { } return p.search(args...) - } func (p Pages) search(args ...types.KeyValues) (Pages, error) { return p.withInvertedIndex(func(idx *related.InvertedIndex) ([]related.Document, error) { return idx.SearchKeyValues(args...) }) - } func (p Pages) searchDoc(doc related.Document, indices ...string) (Pages, error) { diff --git a/resources/page/pages_sort.go b/resources/page/pages_sort.go index 85817ffda..644f67e1e 100644 --- a/resources/page/pages_sort.go +++ b/resources/page/pages_sort.go @@ -96,7 +96,6 @@ var ( } lessPageLanguage = func(p1, p2 Page) bool { - if p1.Language().Weight == p2.Language().Weight { if p1.Date().Unix() == p2.Date().Unix() { c := compare.Strings(p1.LinkTitle(), p2.LinkTitle()) @@ -174,7 +173,6 @@ func SortByDefault(pages Pages) { // // This may safely be executed in parallel. func (p Pages) ByTitle() Pages { - const key = "pageSort.ByTitle" pages, _ := spc.get(key, pageBy(lessPageTitle).Sort, p) @@ -187,7 +185,6 @@ func (p Pages) ByTitle() Pages { // // This may safely be executed in parallel. func (p Pages) ByLinkTitle() Pages { - const key = "pageSort.ByLinkTitle" pages, _ := spc.get(key, pageBy(lessPageLinkTitle).Sort, p) @@ -201,7 +198,6 @@ func (p Pages) ByLinkTitle() Pages { // // This may safely be executed in parallel. func (p Pages) ByDate() Pages { - const key = "pageSort.ByDate" pages, _ := spc.get(key, pageBy(lessPageDate).Sort, p) @@ -215,7 +211,6 @@ func (p Pages) ByDate() Pages { // // This may safely be executed in parallel. func (p Pages) ByPublishDate() Pages { - const key = "pageSort.ByPublishDate" pages, _ := spc.get(key, pageBy(lessPagePubDate).Sort, p) @@ -229,7 +224,6 @@ func (p Pages) ByPublishDate() Pages { // // This may safely be executed in parallel. func (p Pages) ByExpiryDate() Pages { - const key = "pageSort.ByExpiryDate" expDate := func(p1, p2 Page) bool { @@ -247,7 +241,6 @@ func (p Pages) ByExpiryDate() Pages { // // This may safely be executed in parallel. func (p Pages) ByLastmod() Pages { - const key = "pageSort.ByLastmod" date := func(p1, p2 Page) bool { @@ -265,11 +258,9 @@ func (p Pages) ByLastmod() Pages { // // This may safely be executed in parallel. func (p Pages) ByLength() Pages { - const key = "pageSort.ByLength" length := func(p1, p2 Page) bool { - p1l, ok1 := p1.(resource.LengthProvider) p2l, ok2 := p2.(resource.LengthProvider) @@ -295,7 +286,6 @@ func (p Pages) ByLength() Pages { // // This may safely be executed in parallel. func (p Pages) ByLanguage() Pages { - const key = "pageSort.ByLanguage" pages, _ := spc.get(key, pageBy(lessPageLanguage).Sort, p) @@ -365,7 +355,6 @@ func (p Pages) ByParam(paramsKey interface{}) Pages { s2 := cast.ToString(v2) return compare.LessStrings(s1, s2) - } pages, _ := spc.get(key, pageBy(paramsKeyComparator).Sort, p) diff --git a/resources/page/pages_sort_search.go b/resources/page/pages_sort_search.go index ff44e42d5..b400f61e8 100644 --- a/resources/page/pages_sort_search.go +++ b/resources/page/pages_sort_search.go @@ -69,7 +69,6 @@ func searchPageBinary(p Page, pages Pages, less func(p1, p2 Page) bool) int { } return searchPageLinear(p, pages, i) - } // isProbablySorted tests if the pages slice is probably sorted. diff --git a/resources/page/pages_sort_search_test.go b/resources/page/pages_sort_search_test.go index 6cc4ed5ea..8f115109c 100644 --- a/resources/page/pages_sort_search_test.go +++ b/resources/page/pages_sort_search_test.go @@ -38,7 +38,6 @@ func TestSearchPage(t *testing.T) { c.Assert(idx, qt.Equals, i) } } - } func BenchmarkSearchPage(b *testing.B) { @@ -72,23 +71,23 @@ func BenchmarkSearchPage(b *testing.B) { } for _, variant := range []Variant{ - Variant{"Shuffled", shufflePages, searchPage}, - Variant{"ByWeight", func(pages Pages) Pages { + {"Shuffled", shufflePages, searchPage}, + {"ByWeight", func(pages Pages) Pages { return pages.ByWeight() }, searchPage}, - Variant{"ByWeight.Reverse", func(pages Pages) Pages { + {"ByWeight.Reverse", func(pages Pages) Pages { return pages.ByWeight().Reverse() }, searchPage}, - Variant{"ByDate", func(pages Pages) Pages { + {"ByDate", func(pages Pages) Pages { return pages.ByDate() }, searchPage}, - Variant{"ByPublishDate", func(pages Pages) Pages { + {"ByPublishDate", func(pages Pages) Pages { return pages.ByPublishDate() }, searchPage}, - Variant{"ByTitle", func(pages Pages) Pages { + {"ByTitle", func(pages Pages) Pages { return pages.ByTitle() }, searchPage}, - Variant{"ByTitle Linear", func(pages Pages) Pages { + {"ByTitle Linear", func(pages Pages) Pages { return pages.ByTitle() }, linearSearch}, } { @@ -120,5 +119,4 @@ func TestIsPagesProbablySorted(t *testing.T) { c.Assert(isPagesProbablySorted(createSortTestPages(300).ByWeight(), DefaultPageSort), qt.Not(qt.IsNil)) c.Assert(isPagesProbablySorted(createSortTestPages(6), DefaultPageSort), qt.IsNil) c.Assert(isPagesProbablySorted(createSortTestPages(300).ByTitle(), pageLessFunctions...), qt.Not(qt.IsNil)) - } diff --git a/resources/page/pages_sort_test.go b/resources/page/pages_sort_test.go index 670abb90a..737a4f540 100644 --- a/resources/page/pages_sort_test.go +++ b/resources/page/pages_sort_test.go @@ -126,7 +126,6 @@ func TestSortByN(t *testing.T) { t.Errorf("[%d] sort error", i) } } - } func TestLimit(t *testing.T) { @@ -260,7 +259,6 @@ func setSortVals(dates [4]time.Time, titles [4]string, weights [4]int, pages Pag for _, p := range pages { p.(*testPage).content = "" } - } func createSortTestPages(num int) Pages { diff --git a/resources/page/pages_test.go b/resources/page/pages_test.go index 18b10f5bd..829b029b4 100644 --- a/resources/page/pages_test.go +++ b/resources/page/pages_test.go @@ -20,7 +20,6 @@ import ( ) func TestProbablyEq(t *testing.T) { - p1, p2, p3 := &testPage{title: "p1"}, &testPage{title: "p2"}, &testPage{title: "p3"} pages12 := Pages{p1, p2} pages21 := Pages{p2, p1} @@ -39,7 +38,6 @@ func TestProbablyEq(t *testing.T) { c.Assert(PageGroup{Key: "a", Pages: pages12}.ProbablyEq(PageGroup{Key: "a", Pages: pages12}), qt.Equals, true) c.Assert(PageGroup{Key: "a", Pages: pages12}.ProbablyEq(PageGroup{Key: "b", Pages: pages12}), qt.Equals, false) - }) t.Run("PagesGroup", func(t *testing.T) { @@ -49,9 +47,7 @@ func TestProbablyEq(t *testing.T) { c.Assert(PagesGroup{pg1, pg2}.ProbablyEq(PagesGroup{pg1, pg2}), qt.Equals, true) c.Assert(PagesGroup{pg1, pg2}.ProbablyEq(PagesGroup{pg2, pg1}), qt.Equals, false) - }) - } func TestToPages(t *testing.T) { diff --git a/resources/page/pagination.go b/resources/page/pagination.go index 6d5da966e..f41433183 100644 --- a/resources/page/pagination.go +++ b/resources/page/pagination.go @@ -110,7 +110,6 @@ func (p *Pager) element() paginatedElement { // page returns the Page with the given index func (p *Pager) page(index int) (Page, error) { - if pages, ok := p.element().(Pages); ok { if pages != nil && len(pages) > index { return pages[index], nil @@ -207,7 +206,6 @@ func splitPages(pages Pages, size int) []paginatedElement { } func splitPageGroups(pageGroups PagesGroup, size int) []paginatedElement { - type keyPage struct { key interface{} page Page @@ -269,7 +267,6 @@ func ResolvePagerSize(cfg config.Provider, options ...interface{}) (int, error) } func Paginate(td TargetPathDescriptor, seq interface{}, pagerSize int) (*Paginator, error) { - if pagerSize <= 0 { return nil, errors.New("'paginate' configuration setting must be positive to paginate") } @@ -300,7 +297,6 @@ func Paginate(td TargetPathDescriptor, seq interface{}, pagerSize int) (*Paginat // The motivation behind this is to avoid potential costly reflect.DeepEqual // when "probably" is good enough. func probablyEqualPageLists(a1 interface{}, a2 interface{}) bool { - if a1 == nil || a2 == nil { return a1 == a2 } @@ -347,7 +343,6 @@ func probablyEqualPageLists(a1 interface{}, a2 interface{}) bool { } func newPaginatorFromPages(pages Pages, size int, urlFactory paginationURLFactory) (*Paginator, error) { - if size <= 0 { return nil, errors.New("Paginator size must be positive") } @@ -358,7 +353,6 @@ func newPaginatorFromPages(pages Pages, size int, urlFactory paginationURLFactor } func newPaginatorFromPageGroups(pageGroups PagesGroup, size int, urlFactory paginationURLFactory) (*Paginator, error) { - if size <= 0 { return nil, errors.New("Paginator size must be positive") } @@ -389,7 +383,6 @@ func newPaginator(elements []paginatedElement, total, size int, urlFactory pagin } func newPaginationURLFactory(d TargetPathDescriptor) paginationURLFactory { - return func(pageNumber int) string { pathDescriptor := d var rel string @@ -399,6 +392,5 @@ func newPaginationURLFactory(d TargetPathDescriptor) paginationURLFactory { } return CreateTargetPaths(pathDescriptor).RelPermalink(d.PathSpec) - } } diff --git a/resources/page/pagination_test.go b/resources/page/pagination_test.go index f4441a892..8d4f857d7 100644 --- a/resources/page/pagination_test.go +++ b/resources/page/pagination_test.go @@ -37,7 +37,6 @@ func TestSplitPages(t *testing.T) { lastChunk := chunks[4] c.Assert(lastChunk.Len(), qt.Equals, 1) - } func TestSplitPageGroups(t *testing.T) { @@ -78,7 +77,6 @@ func TestSplitPageGroups(t *testing.T) { } else { t.Fatal("Excepted PageGroup") } - } func TestPager(t *testing.T) { @@ -111,7 +109,6 @@ func TestPager(t *testing.T) { first = pag.Pagers()[0].First() c.Assert(first.PageGroups(), qt.Not(qt.HasLen), 0) c.Assert(first.Pages(), qt.HasLen, 0) - } func doTestPages(t *testing.T, paginator *Paginator) { @@ -171,7 +168,6 @@ func TestPagerNoPages(t *testing.T) { first = paginator.Pagers()[0].First() c.Assert(first.PageGroups(), qt.HasLen, 0) c.Assert(first.Pages(), qt.HasLen, 0) - } func doTestPagerNoPages(t *testing.T, paginator *Paginator) { @@ -195,7 +191,6 @@ func doTestPagerNoPages(t *testing.T, paginator *Paginator) { c.Assert(pageOne.TotalPages(), qt.Equals, 0) c.Assert(pageOne.PageNumber(), qt.Equals, 1) c.Assert(pageOne.PageSize(), qt.Equals, 5) - } func TestPaginationURLFactory(t *testing.T) { @@ -206,7 +201,6 @@ func TestPaginationURLFactory(t *testing.T) { for _, uglyURLs := range []bool{false, true} { c.Run(fmt.Sprintf("uglyURLs=%t", uglyURLs), func(c *qt.C) { - tests := []struct { name string d TargetPathDescriptor @@ -215,10 +209,16 @@ func TestPaginationURLFactory(t *testing.T) { expected string expectedUgly string }{ - {"HTML home page 32", - TargetPathDescriptor{Kind: KindHome, Type: output.HTMLFormat}, "http://example.com/", 32, "/zoo/32/", "/zoo/32.html"}, - {"JSON home page 42", - TargetPathDescriptor{Kind: KindHome, Type: output.JSONFormat}, "http://example.com/", 42, "/zoo/42/index.json", "/zoo/42.json"}, + { + "HTML home page 32", + TargetPathDescriptor{Kind: KindHome, Type: output.HTMLFormat}, + "http://example.com/", 32, "/zoo/32/", "/zoo/32.html", + }, + { + "JSON home page 42", + TargetPathDescriptor{Kind: KindHome, Type: output.JSONFormat}, + "http://example.com/", 42, "/zoo/42/index.json", "/zoo/42.json", + }, } for _, test := range tests { @@ -242,7 +242,6 @@ func TestPaginationURLFactory(t *testing.T) { } }) - } } @@ -276,7 +275,6 @@ func TestProbablyEqualPageLists(t *testing.T) { if result != this.expect { t.Errorf("[%d] got %t but expected %t", i, result, this.expect) - } } } diff --git a/resources/page/permalinks.go b/resources/page/permalinks.go index 0e9b9e212..19ac52172 100644 --- a/resources/page/permalinks.go +++ b/resources/page/permalinks.go @@ -60,7 +60,6 @@ func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { // NewPermalinkExpander creates a new PermalinkExpander configured by the given // PathSpec. func NewPermalinkExpander(ps *helpers.PathSpec) (PermalinkExpander, error) { - p := PermalinkExpander{ps: ps} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ @@ -103,11 +102,9 @@ func (l PermalinkExpander) Expand(key string, p Page) (string, error) { } return expand(p) - } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { - expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. @@ -138,7 +135,6 @@ func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Pa } expanders[k] = func(p Page) (string, error) { - if matches == nil { return pattern, nil } @@ -149,7 +145,6 @@ func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Pa attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) - if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } @@ -159,7 +154,6 @@ func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Pa } return newField, nil - } } @@ -176,7 +170,7 @@ var attributeRegexp = regexp.MustCompile(`:\w+`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { fragments := strings.Split(pp[1:], "/") - var bail = false + bail := false for i := range fragments { if bail { return false diff --git a/resources/page/permalinks_test.go b/resources/page/permalinks_test.go index e4eeda748..e40e7e0ef 100644 --- a/resources/page/permalinks_test.go +++ b/resources/page/permalinks_test.go @@ -113,7 +113,6 @@ func TestPermalinkExpansionMultiSection(t *testing.T) { expanded, err = expander.Expand("blog", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/blue/2012") - } func TestPermalinkExpansionConcurrent(t *testing.T) { diff --git a/resources/page/testhelpers_test.go b/resources/page/testhelpers_test.go index 54a908d3b..963848439 100644 --- a/resources/page/testhelpers_test.go +++ b/resources/page/testhelpers_test.go @@ -128,8 +128,8 @@ func (p *testPage) AlternativeOutputFormats() OutputFormats { func (p *testPage) Author() Author { return Author{} - } + func (p *testPage) Authors() AuthorList { return nil } @@ -165,6 +165,7 @@ func (p *testPage) Sitemap() config.Sitemap { func (p *testPage) Layout() string { return "" } + func (p *testPage) Date() time.Time { return p.date } diff --git a/resources/page/weighted.go b/resources/page/weighted.go index 7e5e25451..af8b54446 100644 --- a/resources/page/weighted.go +++ b/resources/page/weighted.go @@ -20,9 +20,7 @@ import ( "github.com/gohugoio/hugo/common/collections" ) -var ( - _ collections.Slicer = WeightedPage{} -) +var _ collections.Slicer = WeightedPage{} // WeightedPages is a list of Pages with their corresponding (and relative) weight // [{Weight: 30, Page: *1}, {Weight: 40, Page: *2}] diff --git a/resources/page/zero_file.autogen.go b/resources/page/zero_file.autogen.go index 23e36b764..f928982e0 100644 --- a/resources/page/zero_file.autogen.go +++ b/resources/page/zero_file.autogen.go @@ -38,50 +38,62 @@ func (z zeroFile) Path() (o0 string) { z.log.Println(".File.Path on zero object. Wrap it in if or with: {{ with .File }}{{ .Path }}{{ end }}") return } + func (z zeroFile) Section() (o0 string) { z.log.Println(".File.Section on zero object. Wrap it in if or with: {{ with .File }}{{ .Section }}{{ end }}") return } + func (z zeroFile) Lang() (o0 string) { z.log.Println(".File.Lang on zero object. Wrap it in if or with: {{ with .File }}{{ .Lang }}{{ end }}") return } + func (z zeroFile) Filename() (o0 string) { z.log.Println(".File.Filename on zero object. Wrap it in if or with: {{ with .File }}{{ .Filename }}{{ end }}") return } + func (z zeroFile) Dir() (o0 string) { z.log.Println(".File.Dir on zero object. Wrap it in if or with: {{ with .File }}{{ .Dir }}{{ end }}") return } + func (z zeroFile) Extension() (o0 string) { z.log.Println(".File.Extension on zero object. Wrap it in if or with: {{ with .File }}{{ .Extension }}{{ end }}") return } + func (z zeroFile) Ext() (o0 string) { z.log.Println(".File.Ext on zero object. Wrap it in if or with: {{ with .File }}{{ .Ext }}{{ end }}") return } + func (z zeroFile) LogicalName() (o0 string) { z.log.Println(".File.LogicalName on zero object. Wrap it in if or with: {{ with .File }}{{ .LogicalName }}{{ end }}") return } + func (z zeroFile) BaseFileName() (o0 string) { z.log.Println(".File.BaseFileName on zero object. Wrap it in if or with: {{ with .File }}{{ .BaseFileName }}{{ end }}") return } + func (z zeroFile) TranslationBaseName() (o0 string) { z.log.Println(".File.TranslationBaseName on zero object. Wrap it in if or with: {{ with .File }}{{ .TranslationBaseName }}{{ end }}") return } + func (z zeroFile) ContentBaseName() (o0 string) { z.log.Println(".File.ContentBaseName on zero object. Wrap it in if or with: {{ with .File }}{{ .ContentBaseName }}{{ end }}") return } + func (z zeroFile) UniqueID() (o0 string) { z.log.Println(".File.UniqueID on zero object. Wrap it in if or with: {{ with .File }}{{ .UniqueID }}{{ end }}") return } + func (z zeroFile) FileInfo() (o0 hugofs.FileMetaInfo) { z.log.Println(".File.FileInfo on zero object. Wrap it in if or with: {{ with .File }}{{ .FileInfo }}{{ end }}") return diff --git a/resources/postpub/fields.go b/resources/postpub/fields.go index f1cfe6092..ed3491438 100644 --- a/resources/postpub/fields.go +++ b/resources/postpub/fields.go @@ -53,7 +53,7 @@ func structToMap(s interface{}) map[string]interface{} { // insert placeholder for the templates. Do it very shallow for now. func insertFieldPlaceholders(root string, m map[string]interface{}, createPlaceholder func(s string) string) { - for k, _ := range m { + for k := range m { m[k] = createPlaceholder(root + "." + k) } } diff --git a/resources/postpub/fields_test.go b/resources/postpub/fields_test.go index d67c7c9a9..10a68ac5a 100644 --- a/resources/postpub/fields_test.go +++ b/resources/postpub/fields_test.go @@ -42,5 +42,4 @@ func TestCreatePlaceholders(t *testing.T) { "SubType": "pre_foo.SubType_post", "Suffixes": "pre_foo.Suffixes_post", }) - } diff --git a/resources/postpub/postpub.go b/resources/postpub/postpub.go index 3a1dd2f85..85b4221fd 100644 --- a/resources/postpub/postpub.go +++ b/resources/postpub/postpub.go @@ -108,7 +108,6 @@ func (r *PostPublishResource) GetFieldString(pattern string) (string, bool) { default: panic(fmt.Sprintf("unknown field accessor %q", fieldAccessor)) } - } func (r *PostPublishResource) fieldToString(receiver interface{}, path string) string { diff --git a/resources/resource.go b/resources/resource.go index acdf2d744..64f9f12f3 100644 --- a/resources/resource.go +++ b/resources/resource.go @@ -276,7 +276,6 @@ func (l *genericResource) Publish() error { defer fw.Close() _, err = io.Copy(fw, fr) - }) return err @@ -435,7 +434,6 @@ func (l genericResource) clone() *genericResource { // returns an opened file or nil if nothing to write (it may already be published). func (l *genericResource) openDestinationsForWriting() (w io.WriteCloser, err error) { - l.publishInit.Do(func() { targetFilenames := l.getTargetFilenames() var changedFilenames []string @@ -456,11 +454,9 @@ func (l *genericResource) openDestinationsForWriting() (w io.WriteCloser, err er } w, err = helpers.OpenFilesForWriting(l.getSpec().BaseFs.PublishFs, changedFilenames...) - }) return - } func (r *genericResource) openPublishFileForWriting(relTargetPath string) (io.WriteCloser, error) { diff --git a/resources/resource/params.go b/resources/resource/params.go index 89da718ec..c76eedeab 100644 --- a/resources/resource/params.go +++ b/resources/resource/params.go @@ -30,5 +30,4 @@ func Param(r ResourceParamsProvider, fallback maps.Params, key interface{}) (int } return maps.GetNestedParam(keyStr, ".", r.Params(), fallback) - } diff --git a/resources/resource_cache.go b/resources/resource_cache.go index 6c4ba951b..f498bb0c0 100644 --- a/resources/resource_cache.go +++ b/resources/resource_cache.go @@ -69,8 +69,8 @@ func resourceKeyPartition(filename string) string { // Commonly used aliases and directory names used for some types. var extAliasKeywords = map[string][]string{ - "sass": []string{"scss"}, - "scss": []string{"sass"}, + "sass": {"scss"}, + "scss": {"sass"}, } // ResourceKeyPartitions resolves a ordered slice of partitions that is @@ -201,7 +201,6 @@ func (c *ResourceCache) getOrCreate(key string, f func() (interface{}, error)) ( c.set(key, r) return r, nil - } func (c *ResourceCache) getFilenames(key string) (string, string) { @@ -230,7 +229,6 @@ func (c *ResourceCache) getFromFile(key string) (filecache.ItemInfo, io.ReadClos fi, rc, _ := c.fileCache.Get(filenameContent) return fi, rc, meta, rc != nil - } // writeMeta writes the metadata to file and returns a writer for the content part. @@ -254,7 +252,6 @@ func (c *ResourceCache) writeMeta(key string, meta transformedResourceMetadata) fi, fc, err := c.fileCache.WriteCloser(filenameContent) return fi, fc, err - } func (c *ResourceCache) set(key string, r interface{}) { @@ -294,7 +291,6 @@ func (c *ResourceCache) DeletePartitions(partitions ...string) { delete(c.cache, k) } } - } func (c *ResourceCache) DeleteMatches(re *regexp.Regexp) { @@ -305,7 +301,5 @@ func (c *ResourceCache) DeleteMatches(re *regexp.Regexp) { if re.MatchString(k) { delete(c.cache, k) } - } - } diff --git a/resources/resource_factories/bundler/bundler.go b/resources/resource_factories/bundler/bundler.go index 1ea92bea3..7de228227 100644 --- a/resources/resource_factories/bundler/bundler.go +++ b/resources/resource_factories/bundler/bundler.go @@ -130,7 +130,6 @@ func (c *Client) Concat(targetPath string, r resource.Resources) (resource.Resou } return newMultiReadSeekCloser(rcsources...), nil - } composite, err := c.rs.New( @@ -138,13 +137,12 @@ func (c *Client) Concat(targetPath string, r resource.Resources) (resource.Resou Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: concatr, - RelTargetFilename: filepath.Clean(targetPath)}) - + RelTargetFilename: filepath.Clean(targetPath), + }) if err != nil { return nil, err } return composite, nil }) - } diff --git a/resources/resource_factories/bundler/bundler_test.go b/resources/resource_factories/bundler/bundler_test.go index 16a5215ba..17a74cc88 100644 --- a/resources/resource_factories/bundler/bundler_test.go +++ b/resources/resource_factories/bundler/bundler_test.go @@ -37,5 +37,4 @@ func TestMultiReadSeekCloser(t *testing.T) { _, err := rc.Seek(0, 0) c.Assert(err, qt.IsNil) } - } diff --git a/resources/resource_factories/create/create.go b/resources/resource_factories/create/create.go index 4ac20d36e..1bba98d21 100644 --- a/resources/resource_factories/create/create.go +++ b/resources/resource_factories/create/create.go @@ -47,9 +47,9 @@ func (c *Client) Get(filename string) (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, - SourceFilename: filename}) + SourceFilename: filename, + }) }) - } // Match gets the resources matching the given pattern from the assets filesystem. @@ -93,8 +93,8 @@ func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, erro OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, - RelTargetFilename: meta.Path()}) - + RelTargetFilename: meta.Path(), + }) if err != nil { return true, err } @@ -102,7 +102,6 @@ func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, erro res = append(res, r) return firstOnly, nil - } if err := hugofs.Glob(c.rs.BaseFs.Assets.Fs, pattern, handle); err != nil { @@ -110,7 +109,6 @@ func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, erro } return res, nil - }) } @@ -124,8 +122,7 @@ func (c *Client) FromString(targetPath, content string) (resource.Resource, erro OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, - RelTargetFilename: filepath.Clean(targetPath)}) - + RelTargetFilename: filepath.Clean(targetPath), + }) }) - } diff --git a/resources/resource_metadata.go b/resources/resource_metadata.go index 7bf7479a3..a0c232c67 100644 --- a/resources/resource_metadata.go +++ b/resources/resource_metadata.go @@ -16,6 +16,7 @@ package resources import ( "fmt" "strconv" + "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/media" @@ -24,8 +25,6 @@ import ( "github.com/pkg/errors" "github.com/spf13/cast" - "strings" - "github.com/gohugoio/hugo/common/maps" ) diff --git a/resources/resource_metadata_test.go b/resources/resource_metadata_test.go index c79a50021..87a537f74 100644 --- a/resources/resource_metadata_test.go +++ b/resources/resource_metadata_test.go @@ -43,7 +43,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(logo1.Title(), qt.Equals, "My Resource") c.Assert(logo1.Name(), qt.Equals, "My Name") c.Assert(foo2.Name(), qt.Equals, "My Name") - }}, {[]map[string]interface{}{ { @@ -62,7 +61,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(foo2.Name(), qt.Equals, "My Name") c.Assert(foo3.Name(), qt.Equals, "My Name") c.Assert(foo3.Title(), qt.Equals, "My Resource") - }}, {[]map[string]interface{}{ { @@ -102,7 +100,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(icon1, qt.Equals, "logo") c.Assert(icon2, qt.Equals, "resource") - }}, {[]map[string]interface{}{ { @@ -126,7 +123,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(foo3.Title(), qt.Equals, "Resource #5") c.Assert(resources.GetMatch("logo name #1*"), qt.Equals, logo2) - }}, {[]map[string]interface{}{ { @@ -146,7 +142,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(logo2.Name(), qt.Equals, "Name #1") c.Assert(logo1.Title(), qt.Equals, "Other Logo #2") c.Assert(logo1.Name(), qt.Equals, "Name #2") - }}, {[]map[string]interface{}{ { @@ -166,7 +161,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(logo2.Name(), qt.Equals, "Name #1") c.Assert(logo1.Title(), qt.Equals, "Other Logo #2") c.Assert(logo1.Name(), qt.Equals, "Name #2") - }}, {[]map[string]interface{}{ { @@ -186,7 +180,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(logo2.Name(), qt.Equals, "Name #1") c.Assert(logo1.Title(), qt.Equals, "Logo #2") c.Assert(logo1.Name(), qt.Equals, "Name #2") - }}, {[]map[string]interface{}{ { @@ -195,7 +188,6 @@ func TestAssignMetadata(t *testing.T) { }, func(err error) { // Missing src c.Assert(err, qt.Not(qt.IsNil)) - }}, {[]map[string]interface{}{ { @@ -205,7 +197,6 @@ func TestAssignMetadata(t *testing.T) { }, func(err error) { // Invalid pattern c.Assert(err, qt.Not(qt.IsNil)) - }}, } { @@ -227,5 +218,4 @@ func TestAssignMetadata(t *testing.T) { this.assertFunc(AssignMetadata(this.metaData, resources...)) } - } diff --git a/resources/resource_spec.go b/resources/resource_spec.go index 0ca60fe31..1659332ab 100644 --- a/resources/resource_spec.go +++ b/resources/resource_spec.go @@ -53,7 +53,6 @@ func NewSpec( errorHandler herrors.ErrorSender, outputFormats output.Formats, mimeTypes media.Types) (*Spec, error) { - imgConfig, err := images.DecodeConfig(s.Cfg.GetStringMap("imaging")) if err != nil { return nil, err @@ -96,12 +95,12 @@ func NewSpec( fileCaches.ImageCache(), s, - )} + ), + } rs.ResourceCache = newResourceCache(rs) return rs, nil - } type Spec struct { @@ -189,7 +188,6 @@ func (r *Spec) newGenericResource(sourceFs afero.Fs, baseFilename, mediaType, ) - } func (r *Spec) newGenericResourceWithBase( @@ -201,7 +199,6 @@ func (r *Spec) newGenericResourceWithBase( sourceFilename, baseFilename string, mediaType media.Type) *genericResource { - if osFileInfo != nil && osFileInfo.IsDir() { panic(fmt.Sprintf("dirs not supported resource types: %v", osFileInfo)) } @@ -250,7 +247,6 @@ func (r *Spec) newGenericResourceWithBase( } return g - } func (r *Spec) newResource(sourceFs afero.Fs, fd ResourceSourceDescriptor) (resource.Resource, error) { @@ -318,7 +314,6 @@ func (r *Spec) newResource(sourceFs afero.Fs, fd ResourceSourceDescriptor) (reso } return newResourceAdapter(gr.spec, fd.LazyPublish, gr), nil - } func (r *Spec) newResourceFor(fd ResourceSourceDescriptor) (resource.Resource, error) { diff --git a/resources/resource_test.go b/resources/resource_test.go index 7a0b8069d..bf7a94529 100644 --- a/resources/resource_test.go +++ b/resources/resource_test.go @@ -39,7 +39,6 @@ func TestGenericResource(t *testing.T) { c.Assert(r.Permalink(), qt.Equals, "https://example.com/foo.css") c.Assert(r.RelPermalink(), qt.Equals, "/foo.css") c.Assert(r.ResourceType(), qt.Equals, "css") - } func TestGenericResourceWithLinkFacory(t *testing.T) { @@ -78,7 +77,6 @@ func TestNewResourceFromFilename(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(r, qt.Not(qt.IsNil)) c.Assert(r.ResourceType(), qt.Equals, "json") - } func TestNewResourceFromFilenameSubPathInBaseURL(t *testing.T) { @@ -96,7 +94,6 @@ func TestNewResourceFromFilenameSubPathInBaseURL(t *testing.T) { c.Assert(r.ResourceType(), qt.Equals, "image") c.Assert(r.RelPermalink(), qt.Equals, "/docs/a/b/logo.png") c.Assert(r.Permalink(), qt.Equals, "https://example.com/docs/a/b/logo.png") - } var pngType, _ = media.FromStringAndExt("image/png", "png") @@ -108,11 +105,11 @@ func TestResourcesByType(t *testing.T) { spec.newGenericResource(nil, nil, nil, "/a/foo1.css", "foo1.css", media.CSSType), spec.newGenericResource(nil, nil, nil, "/a/logo.png", "logo.css", pngType), spec.newGenericResource(nil, nil, nil, "/a/foo2.css", "foo2.css", media.CSSType), - spec.newGenericResource(nil, nil, nil, "/a/foo3.css", "foo3.css", media.CSSType)} + spec.newGenericResource(nil, nil, nil, "/a/foo3.css", "foo3.css", media.CSSType), + } c.Assert(len(resources.ByType("css")), qt.Equals, 3) c.Assert(len(resources.ByType("image")), qt.Equals, 1) - } func TestResourcesGetByPrefix(t *testing.T) { @@ -123,7 +120,8 @@ func TestResourcesGetByPrefix(t *testing.T) { spec.newGenericResource(nil, nil, nil, "/a/logo1.png", "logo1.png", pngType), spec.newGenericResource(nil, nil, nil, "/b/Logo2.png", "Logo2.png", pngType), spec.newGenericResource(nil, nil, nil, "/b/foo2.css", "foo2.css", media.CSSType), - spec.newGenericResource(nil, nil, nil, "/b/foo3.css", "foo3.css", media.CSSType)} + spec.newGenericResource(nil, nil, nil, "/b/foo3.css", "foo3.css", media.CSSType), + } c.Assert(resources.GetMatch("asdf*"), qt.IsNil) c.Assert(resources.GetMatch("logo*").RelPermalink(), qt.Equals, "/logo1.png") @@ -141,7 +139,6 @@ func TestResourcesGetByPrefix(t *testing.T) { c.Assert(logo.Params(), qt.Not(qt.IsNil)) c.Assert(logo.Name(), qt.Equals, "logo1.png") c.Assert(logo.Title(), qt.Equals, "logo1.png") - } func TestResourcesGetMatch(t *testing.T) { @@ -187,7 +184,6 @@ func TestResourcesGetMatch(t *testing.T) { // (it is possible for users to do a rename) // This is analogous to standing in a directory and doing "ls *.*". c.Assert(len(resources.Match("/c/**.css")), qt.Equals, 0) - } func BenchmarkResourcesMatch(b *testing.B) { @@ -218,7 +214,6 @@ func BenchmarkResourcesMatchA100(b *testing.B) { for i := 0; i < b.N; i++ { resources.Match(pattern) } - } func benchResources(b *testing.B) resource.Resources { @@ -242,7 +237,6 @@ func benchResources(b *testing.B) resource.Resources { } return resources - } func BenchmarkAssignMetadata(b *testing.B) { @@ -252,7 +246,7 @@ func BenchmarkAssignMetadata(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() var resources resource.Resources - var meta = []map[string]interface{}{ + meta := []map[string]interface{}{ { "title": "Foo #:counter", "name": "Foo Name #:counter", diff --git a/resources/resource_transformers/babel/babel.go b/resources/resource_transformers/babel/babel.go index a9d39d31b..a7598f820 100644 --- a/resources/resource_transformers/babel/babel.go +++ b/resources/resource_transformers/babel/babel.go @@ -51,6 +51,7 @@ func DecodeOptions(m map[string]interface{}) (opts Options, err error) { err = mapstructure.WeakDecode(m, &opts) return } + func (opts Options) toArgs() []string { var args []string @@ -111,7 +112,6 @@ func (t *babelTransformation) Transform(ctx *resources.ResourceTransformationCtx // Try PATH binary = binaryName if _, err := exec.LookPath(binary); err != nil { - // This may be on a CI server etc. Will fall back to pre-built assets. return herrors.ErrFeatureNotAvailable } diff --git a/resources/resource_transformers/integrity/integrity.go b/resources/resource_transformers/integrity/integrity.go index 1b74de7eb..bbd0b6675 100644 --- a/resources/resource_transformers/integrity/integrity.go +++ b/resources/resource_transformers/integrity/integrity.go @@ -55,7 +55,6 @@ func (t *fingerprintTransformation) Key() internal.ResourceTransformationKey { // Transform creates a MD5 hash of the Resource content and inserts that hash before // the extension in the filename. func (t *fingerprintTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { - h, err := newHash(t.algo) if err != nil { return err diff --git a/resources/resource_transformers/integrity/integrity_test.go b/resources/resource_transformers/integrity/integrity_test.go index 3759e6313..8a17fef7a 100644 --- a/resources/resource_transformers/integrity/integrity_test.go +++ b/resources/resource_transformers/integrity/integrity_test.go @@ -24,7 +24,6 @@ import ( ) func TestHashFromAlgo(t *testing.T) { - for _, algo := range []struct { name string bits int @@ -35,7 +34,6 @@ func TestHashFromAlgo(t *testing.T) { {"sha512", 512}, {"shaman", -1}, } { - t.Run(algo.name, func(t *testing.T) { c := qt.New(t) h, err := newHash(algo.name) @@ -46,7 +44,6 @@ func TestHashFromAlgo(t *testing.T) { c.Assert(err, qt.Not(qt.IsNil)) c.Assert(err.Error(), qt.Contains, "use either md5, sha256, sha384 or sha512") } - }) } } diff --git a/resources/resource_transformers/js/options.go b/resources/resource_transformers/js/options.go index 925b19956..75daa0cad 100644 --- a/resources/resource_transformers/js/options.go +++ b/resources/resource_transformers/js/options.go @@ -212,12 +212,10 @@ func createBuildPlugins(c *Client, opts Options) ([]api.Plugin, error) { build.OnResolve(api.OnResolveOptions{Filter: `.*`}, func(args api.OnResolveArgs) (api.OnResolveResult, error) { return resolveImport(args) - }) build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: nsImportHugo}, func(args api.OnLoadArgs) (api.OnLoadResult, error) { b, err := ioutil.ReadFile(args.Path) - if err != nil { return api.OnLoadResult{}, errors.Wrapf(err, "failed to read %q", args.Path) } @@ -266,11 +264,9 @@ func createBuildPlugins(c *Client, opts Options) ([]api.Plugin, error) { } return []api.Plugin{importResolver, paramsPlugin}, nil - } func toBuildOptions(opts Options) (buildOptions api.BuildOptions, err error) { - var target api.Target switch opts.Target { case "", "esnext": @@ -336,8 +332,8 @@ func toBuildOptions(opts Options) (buildOptions api.BuildOptions, err error) { } // By default we only need to specify outDir and no outFile - var outDir = opts.outDir - var outFile = "" + outDir := opts.outDir + outFile := "" var sourceMap api.SourceMap switch opts.SourceMap { case "inline": @@ -381,5 +377,4 @@ func toBuildOptions(opts Options) (buildOptions api.BuildOptions, err error) { }, } return - } diff --git a/resources/resource_transformers/js/options_test.go b/resources/resource_transformers/js/options_test.go index ef8c203ce..f07ccc26b 100644 --- a/resources/resource_transformers/js/options_test.go +++ b/resources/resource_transformers/js/options_test.go @@ -76,7 +76,8 @@ func TestToBuildOptions(t *testing.T) { opts, err = toBuildOptions(Options{ Target: "es2018", Format: "cjs", Minify: true, mediaType: media.JavascriptType, - SourceMap: "inline"}) + SourceMap: "inline", + }) c.Assert(err, qt.IsNil) c.Assert(opts, qt.DeepEquals, api.BuildOptions{ Bundle: true, @@ -93,7 +94,8 @@ func TestToBuildOptions(t *testing.T) { opts, err = toBuildOptions(Options{ Target: "es2018", Format: "cjs", Minify: true, mediaType: media.JavascriptType, - SourceMap: "inline"}) + SourceMap: "inline", + }) c.Assert(err, qt.IsNil) c.Assert(opts, qt.DeepEquals, api.BuildOptions{ Bundle: true, @@ -107,5 +109,4 @@ func TestToBuildOptions(t *testing.T) { Loader: api.LoaderJS, }, }) - } diff --git a/resources/resource_transformers/minifier/minify.go b/resources/resource_transformers/minifier/minify.go index 060485e80..51a3f4047 100644 --- a/resources/resource_transformers/minifier/minify.go +++ b/resources/resource_transformers/minifier/minify.go @@ -57,5 +57,4 @@ func (c *Client) Minify(res resources.ResourceTransformer) (resource.Resource, e rs: c.rs, m: c.m, }) - } diff --git a/resources/resource_transformers/minifier/minify_test.go b/resources/resource_transformers/minifier/minify_test.go index 38828c17c..b0ebe3171 100644 --- a/resources/resource_transformers/minifier/minify_test.go +++ b/resources/resource_transformers/minifier/minify_test.go @@ -39,5 +39,4 @@ func TestTransform(t *testing.T) { content, err := transformed.(resource.ContentProvider).Content() c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "<h1>Hugo Rocks!</h1>") - } diff --git a/resources/resource_transformers/postcss/postcss.go b/resources/resource_transformers/postcss/postcss.go index daeb7212a..8ba40ebd1 100644 --- a/resources/resource_transformers/postcss/postcss.go +++ b/resources/resource_transformers/postcss/postcss.go @@ -19,6 +19,7 @@ import ( "encoding/hex" "io" "io/ioutil" + "os/exec" "path" "path/filepath" "regexp" @@ -36,8 +37,6 @@ import ( "github.com/gohugoio/hugo/hugofs" "github.com/pkg/errors" - "os/exec" - "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" @@ -139,7 +138,6 @@ func (t *postcssTransformation) Key() internal.ResourceTransformationKey { // npm install -g postcss-cli // npm install -g autoprefixer func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { - const localPostCSSPath = "node_modules/.bin/" const binaryName = "postcss" @@ -174,7 +172,6 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC if configFile == "" && t.options.Config != "" { // Only fail if the user specificed config file is not found. return errors.Errorf("postcss config %q not found:", configFile) - } } @@ -271,7 +268,6 @@ func (imp *importResolver) importRecursive( lineNum int, content string, inPath string) (int, string, error) { - basePath := path.Dir(inPath) var replacements []string @@ -350,7 +346,6 @@ func (imp *importResolver) resolve() (io.Reader, error) { } return strings.NewReader(newContent), nil - } // See https://www.w3schools.com/cssref/pr_import_rule.asp diff --git a/resources/resource_transformers/postcss/postcss_test.go b/resources/resource_transformers/postcss/postcss_test.go index a49487c97..c5f855445 100644 --- a/resources/resource_transformers/postcss/postcss_test.go +++ b/resources/resource_transformers/postcss/postcss_test.go @@ -44,7 +44,6 @@ func TestDecodeOptions(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(opts2.NoMap, qt.Equals, true) - } func TestShouldImport(t *testing.T) { @@ -117,7 +116,6 @@ E_STYLE Offset: 1, Filename: "d.css", }) - } func BenchmarkImportResolver(b *testing.B) { diff --git a/resources/resource_transformers/tocss/scss/client_test.go b/resources/resource_transformers/tocss/scss/client_test.go index f9adac226..9dddd3869 100644 --- a/resources/resource_transformers/tocss/scss/client_test.go +++ b/resources/resource_transformers/tocss/scss/client_test.go @@ -46,5 +46,4 @@ func TestReplaceRegularCSSImports(t *testing.T) { reverted := replaceRegularImportsOut(res) c.Assert(reverted, qt.Equals, scssWithImport) - } diff --git a/resources/resource_transformers/tocss/scss/tocss.go b/resources/resource_transformers/tocss/scss/tocss.go index fc7a19f33..f4f15fad1 100644 --- a/resources/resource_transformers/tocss/scss/tocss.go +++ b/resources/resource_transformers/tocss/scss/tocss.go @@ -127,7 +127,7 @@ func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx // more correct for the main entry path (main.scss typically), but // it will mess up the import mappings. As a workaround, we do a replacement // in the source map itself (see below). - //options.InputPath = inputPath + // options.InputPath = inputPath options.to.SourceMapOptions.OutputPath = outName options.to.SourceMapOptions.Contents = true options.to.SourceMapOptions.OmitURL = false diff --git a/resources/testhelpers_test.go b/resources/testhelpers_test.go index 0462f7ecd..32e4213ea 100644 --- a/resources/testhelpers_test.go +++ b/resources/testhelpers_test.go @@ -1,15 +1,14 @@ package resources import ( - "path/filepath" - "testing" - "image" "io" "io/ioutil" "os" + "path/filepath" "runtime" "strings" + "testing" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/modules" @@ -51,11 +50,9 @@ func createTestCfg() *viper.Viper { cfg.Set("allModules", modules.Modules{mod}) return cfg - } func newTestResourceSpec(desc specDescriptor) *Spec { - baseURL := desc.baseURL if baseURL == "" { baseURL = "https://example.com/" @@ -133,7 +130,6 @@ func newTestResourceOsFs(c *qt.C) (*Spec, string) { c.Assert(err, qt.IsNil) return spec, workDir - } func fetchSunset(c *qt.C) resource.Image { diff --git a/resources/transform.go b/resources/transform.go index 354a20eec..d995bb46b 100644 --- a/resources/transform.go +++ b/resources/transform.go @@ -293,7 +293,6 @@ func (r *resourceAdapter) publish() { r.spec.Logger.Errorf("Failed to publish Resource: %s", r.publisherErr) } }) - } func (r *resourceAdapter) TransformationKey() string { @@ -397,7 +396,6 @@ func (r *resourceAdapter) transform(publish, setContent bool) error { } newErr := func(err error) error { - msg := fmt.Sprintf("%s: failed to transform %q (%s)", strings.ToUpper(tr.Key().Name), tctx.InPath, tctx.InMediaType.Type()) if err == herrors.ErrFeatureNotAvailable { @@ -416,7 +414,6 @@ func (r *resourceAdapter) transform(publish, setContent bool) error { } return errors.Wrap(err, msg) - } var tryFileCache bool diff --git a/resources/transform_test.go b/resources/transform_test.go index b2dad2210..488fefd6e 100644 --- a/resources/transform_test.go +++ b/resources/transform_test.go @@ -385,11 +385,10 @@ func TestTransform(t *testing.T) { resizedNotPublished, err := img.Resize("50x50") c.Assert(err, qt.IsNil) c.Assert(resizedNotPublished.Height(), qt.Equals, 50) - //c.Assert(resized.RelPermalink(), qt.Equals, "/gopher.changed_hu2e827f5a78333ebc04166dd643235dea_1462_50x50_resize_linear_2.png") + // c.Assert(resized.RelPermalink(), qt.Equals, "/gopher.changed_hu2e827f5a78333ebc04166dd643235dea_1462_50x50_resize_linear_2.png") assertShouldExist(c, spec, "public/gopher.changed_hu2e827f5a78333ebc04166dd643235dea_1462_50x50_resize_linear_2.png", false) assertNoDuplicateWrites(c, spec) - }) c.Run("Concurrent", func(c *qt.C) { diff --git a/scripts/fork_go_templates/main.go b/scripts/fork_go_templates/main.go index 04202b254..c295ab734 100644 --- a/scripts/fork_go_templates/main.go +++ b/scripts/fork_go_templates/main.go @@ -35,7 +35,6 @@ func main() { goimports(htmlRoot) gofmt(forkRoot) - } const ( @@ -97,36 +96,41 @@ package parse } return content - } var goPackages = []goPackage{ - goPackage{srcPkg: "text/template", dstPkg: "texttemplate", - replacer: func(name, content string) string { return textTemplateReplacers.Replace(commonReplace(name, content)) }}, - goPackage{srcPkg: "html/template", dstPkg: "htmltemplate", replacer: func(name, content string) string { - if strings.HasSuffix(name, "content.go") { - // Remove template.HTML types. We need to use the Go types. - content = removeAll(`(?s)// Strings of content.*?\)\n`, content) - } + { + srcPkg: "text/template", dstPkg: "texttemplate", + replacer: func(name, content string) string { return textTemplateReplacers.Replace(commonReplace(name, content)) }, + }, + { + srcPkg: "html/template", dstPkg: "htmltemplate", replacer: func(name, content string) string { + if strings.HasSuffix(name, "content.go") { + // Remove template.HTML types. We need to use the Go types. + content = removeAll(`(?s)// Strings of content.*?\)\n`, content) + } - content = commonReplace(name, content) + content = commonReplace(name, content) - return htmlTemplateReplacers.Replace(content) - }, + return htmlTemplateReplacers.Replace(content) + }, rewriter: func(name string) { for _, s := range []string{"CSS", "HTML", "HTMLAttr", "JS", "JSStr", "URL", "Srcset"} { rewrite(name, fmt.Sprintf("%s -> htmltemplate.%s", s, s)) } rewrite(name, `"text/template/parse" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"`) - }}, - goPackage{srcPkg: "internal/fmtsort", dstPkg: "fmtsort", rewriter: func(name string) { + }, + }, + {srcPkg: "internal/fmtsort", dstPkg: "fmtsort", rewriter: func(name string) { rewrite(name, `"internal/fmtsort" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"`) }}, - goPackage{srcPkg: "internal/testenv", dstPkg: "testenv", + { + srcPkg: "internal/testenv", dstPkg: "testenv", replacer: func(name, content string) string { return testEnvReplacers.Replace(content) }, rewriter: func(name string) { rewrite(name, `"internal/testenv" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`) - }}, - goPackage{srcPkg: "internal/cfg", dstPkg: "cfg", rewriter: func(name string) { + }, + }, + {srcPkg: "internal/cfg", dstPkg: "cfg", rewriter: func(name string) { rewrite(name, `"internal/cfg" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`) }}, } @@ -196,7 +200,6 @@ func doWithGoFiles(dir string, func removeAll(expression, content string) string { re := regexp.MustCompile(expression) return re.ReplaceAllString(content, "") - } func rewrite(filename, rule string) { diff --git a/source/fileInfo.go b/source/fileInfo.go index 849afa45e..4e7866315 100644 --- a/source/fileInfo.go +++ b/source/fileInfo.go @@ -232,7 +232,6 @@ func (sp *SourceSpec) NewFileInfoFrom(path, filename string) (*FileInfo, error) } func (sp *SourceSpec) NewFileInfo(fi hugofs.FileMetaInfo) (*FileInfo, error) { - m := fi.Meta() filename := m.Filename() @@ -290,5 +289,4 @@ func (sp *SourceSpec) NewFileInfo(fi hugofs.FileMetaInfo) (*FileInfo, error) { } return f, nil - } diff --git a/source/fileInfo_test.go b/source/fileInfo_test.go index 1c9da7e41..b8bb33cd3 100644 --- a/source/fileInfo_test.go +++ b/source/fileInfo_test.go @@ -38,18 +38,15 @@ func TestFileInfo(t *testing.T) { c.Assert(f.Section(), qt.Equals, "b") c.Assert(f.TranslationBaseName(), qt.Equals, filepath.FromSlash("page")) c.Assert(f.BaseFileName(), qt.Equals, filepath.FromSlash("page")) - }}, {filepath.FromSlash("/a/"), filepath.FromSlash("/a/b/c/d/page.md"), func(f *FileInfo) { c.Assert(f.Section(), qt.Equals, "b") - }}, {filepath.FromSlash("/a/"), filepath.FromSlash("/a/b/page.en.MD"), func(f *FileInfo) { c.Assert(f.Section(), qt.Equals, "b") c.Assert(f.Path(), qt.Equals, filepath.FromSlash("b/page.en.MD")) c.Assert(f.TranslationBaseName(), qt.Equals, filepath.FromSlash("page")) c.Assert(f.BaseFileName(), qt.Equals, filepath.FromSlash("page.en")) - }}, } { path := strings.TrimPrefix(this.filename, this.base) @@ -57,5 +54,4 @@ func TestFileInfo(t *testing.T) { c.Assert(err, qt.IsNil) this.assert(f) } - } diff --git a/source/filesystem.go b/source/filesystem.go index ce62c15a4..1cd75f032 100644 --- a/source/filesystem.go +++ b/source/filesystem.go @@ -102,11 +102,9 @@ func (f *Filesystem) captureFiles() error { }) return w.Walk() - } func (f *Filesystem) shouldRead(filename string, fi hugofs.FileMetaInfo) (bool, error) { - ignore := f.SourceSpec.IgnoreFile(fi.Meta().Filename()) if fi.IsDir() { diff --git a/source/filesystem_test.go b/source/filesystem_test.go index ec7a305dc..5dc187978 100644 --- a/source/filesystem_test.go +++ b/source/filesystem_test.go @@ -74,7 +74,6 @@ func TestUnicodeNorm(t *testing.T) { t.Fatalf("file %q name in NFD form should be normalized (%s)", f.BaseFileName(), path.NFC) } } - } func newTestConfig() *viper.Viper { diff --git a/source/sourceSpec.go b/source/sourceSpec.go index 504a3a22d..e8407a14d 100644 --- a/source/sourceSpec.go +++ b/source/sourceSpec.go @@ -74,7 +74,6 @@ func NewSourceSpec(ps *helpers.PathSpec, fs afero.Fs) *SourceSpec { } return &SourceSpec{ignoreFilesRe: regexps, PathSpec: ps, SourceFs: fs, Languages: languages, DefaultContentLanguage: defaultLang, DisabledLanguages: disabledLangsSet} - } // IgnoreFile returns whether a given file should be ignored. diff --git a/tpl/cast/cast_test.go b/tpl/cast/cast_test.go index d3f8d9733..c6219728b 100644 --- a/tpl/cast/cast_test.go +++ b/tpl/cast/cast_test.go @@ -15,7 +15,6 @@ package cast import ( "html/template" - "testing" qt "github.com/frankban/quicktest" diff --git a/tpl/cast/docshelper.go b/tpl/cast/docshelper.go index a497f6e8a..035db1740 100644 --- a/tpl/cast/docshelper.go +++ b/tpl/cast/docshelper.go @@ -41,7 +41,6 @@ func init() { } return docshelper.DocProvider{"tpl": map[string]interface{}{"funcs": namespaces}} - } docshelper.AddDocProviderFunc(docsProvider) diff --git a/tpl/cast/init.go b/tpl/cast/init.go index 3aee6f036..3f1f3f253 100644 --- a/tpl/cast/init.go +++ b/tpl/cast/init.go @@ -51,7 +51,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/cast/init_test.go b/tpl/cast/init_test.go index 73d9d5adc..dd024b775 100644 --- a/tpl/cast/init_test.go +++ b/tpl/cast/init_test.go @@ -38,5 +38,4 @@ func TestInit(t *testing.T) { c.Assert(found, qt.Equals, true) c.Assert(ns.Context(), hqt.IsSameType, &Namespace{}) - } diff --git a/tpl/collections/append.go b/tpl/collections/append.go index 297328dc8..50fafe3d9 100644 --- a/tpl/collections/append.go +++ b/tpl/collections/append.go @@ -34,5 +34,4 @@ func (ns *Namespace) Append(args ...interface{}) (interface{}, error) { from := args[:len(args)-1] return collections.Append(to, from...) - } diff --git a/tpl/collections/append_test.go b/tpl/collections/append_test.go index a254601b4..9dcc7d2b9 100644 --- a/tpl/collections/append_test.go +++ b/tpl/collections/append_test.go @@ -40,9 +40,11 @@ func TestAppend(t *testing.T) { {"", []interface{}{[]string{"a", "b"}}, false}, {[]string{"a", "b"}, []interface{}{}, false}, // No string concatenation. - {"ab", + { + "ab", []interface{}{"c"}, - false}, + false, + }, } { errMsg := qt.Commentf("[%d]", i) @@ -62,5 +64,4 @@ func TestAppend(t *testing.T) { t.Fatalf("%s got\n%T: %v\nexpected\n%T: %v", errMsg, result, result, test.expected, test.expected) } } - } diff --git a/tpl/collections/apply.go b/tpl/collections/apply.go index 55d29d3a9..86554def1 100644 --- a/tpl/collections/apply.go +++ b/tpl/collections/apply.go @@ -52,7 +52,6 @@ func (ns *Namespace) Apply(seq interface{}, fname string, args ...interface{}) ( vv := seqv.Index(i) vvv, err := applyFnToThis(fnv, vv, args...) - if err != nil { return nil, err } diff --git a/tpl/collections/apply_test.go b/tpl/collections/apply_test.go index f9199b6b6..98cb78b51 100644 --- a/tpl/collections/apply_test.go +++ b/tpl/collections/apply_test.go @@ -14,12 +14,11 @@ package collections import ( + "fmt" "io" "reflect" "testing" - "fmt" - qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/output" @@ -58,7 +57,6 @@ func (templateFinder) GetFunc(name string) (reflect.Value, bool) { } return reflect.ValueOf(fmt.Sprint), true - } func TestApply(t *testing.T) { @@ -88,5 +86,4 @@ func TestApply(t *testing.T) { if err == nil { t.Errorf("apply with unknown func should fail") } - } diff --git a/tpl/collections/collections.go b/tpl/collections/collections.go index d90467022..3521f9cd5 100644 --- a/tpl/collections/collections.go +++ b/tpl/collections/collections.go @@ -18,7 +18,6 @@ package collections import ( "fmt" "html/template" - "math/rand" "net/url" "reflect" @@ -478,9 +477,9 @@ func (ns *Namespace) Seq(args ...interface{}) ([]int, error) { return nil, errors.New("invalid arguments to Seq") } - var inc = 1 + inc := 1 var last int - var first = intArgs[0] + first := intArgs[0] if len(intArgs) == 1 { last = first @@ -580,7 +579,6 @@ type intersector struct { } func (i *intersector) appendIfNotSeen(v reflect.Value) { - vi := v.Interface() if !i.seen[vi] { i.r = reflect.Append(i.r, v) @@ -729,7 +727,6 @@ func (ns *Namespace) Uniq(seq interface{}) (interface{}, error) { } return slice.Interface(), nil - } // KeyVals creates a key and values wrapper. diff --git a/tpl/collections/collections_test.go b/tpl/collections/collections_test.go index 21c8bfb56..a75ec9d16 100644 --- a/tpl/collections/collections_test.go +++ b/tpl/collections/collections_test.go @@ -17,7 +17,6 @@ import ( "errors" "fmt" "html/template" - "math/rand" "reflect" "testing" @@ -195,8 +194,10 @@ func TestDictionary(t *testing.T) { }{ {[]interface{}{"a", "b"}, map[string]interface{}{"a": "b"}}, {[]interface{}{[]string{"a", "b"}, "c"}, map[string]interface{}{"a": map[string]interface{}{"b": "c"}}}, - {[]interface{}{[]string{"a", "b"}, "c", []string{"a", "b2"}, "c2", "b", "c"}, - map[string]interface{}{"a": map[string]interface{}{"b": "c", "b2": "c2"}, "b": "c"}}, + { + []interface{}{[]string{"a", "b"}, "c", []string{"a", "b2"}, "c2", "b", "c"}, + map[string]interface{}{"a": map[string]interface{}{"b": "c", "b2": "c2"}, "b": "c"}, + }, {[]interface{}{"a", 12, "b", []int{4}}, map[string]interface{}{"a": 12, "b": []int{4}}}, // errors {[]interface{}{5, "b"}, false}, @@ -237,7 +238,6 @@ func TestReverse(t *testing.T) { c.Assert(reversed, qt.IsNil) _, err = ns.Reverse(43) c.Assert(err, qt.Not(qt.IsNil)) - } func TestEchoParam(t *testing.T) { @@ -369,8 +369,10 @@ func (p testPage) String() string { return "p-" + p.Title } -type pagesPtr []*testPage -type pagesVals []testPage +type ( + pagesPtr []*testPage + pagesVals []testPage +) var ( p1 = &testPage{"A"} @@ -716,7 +718,6 @@ func TestSlice(t *testing.T) { c.Assert(result, qt.DeepEquals, test.expected, errMsg) } - } func TestUnion(t *testing.T) { @@ -907,7 +908,6 @@ type TstParams struct { func (x TstParams) Params() maps.Params { return x.params - } type TstXIHolder struct { diff --git a/tpl/collections/complement_test.go b/tpl/collections/complement_test.go index d0e27353c..7e8d695b4 100644 --- a/tpl/collections/complement_test.go +++ b/tpl/collections/complement_test.go @@ -66,7 +66,8 @@ func TestComplement(t *testing.T) { {"error", []interface{}{[]string{"c", "d"}, []string{"a", "b"}}, false}, {[]string{"a", "b", "c"}, []interface{}{[][]string{{"c", "d"}}}, false}, { - []interface{}{[][]string{{"c", "d"}}}, []interface{}{[]string{"c", "d"}, []string{"a", "b"}}, + []interface{}{[][]string{{"c", "d"}}}, + []interface{}{[]string{"c", "d"}, []string{"a", "b"}}, []interface{}{[][]string{{"c", "d"}}}, }, } { @@ -93,5 +94,4 @@ func TestComplement(t *testing.T) { c.Assert(err, qt.Not(qt.IsNil)) _, err = ns.Complement([]string{"a", "b"}) c.Assert(err, qt.Not(qt.IsNil)) - } diff --git a/tpl/collections/index_test.go b/tpl/collections/index_test.go index 0c380d8d5..c690fe648 100644 --- a/tpl/collections/index_test.go +++ b/tpl/collections/index_test.go @@ -52,7 +52,6 @@ func TestIndex(t *testing.T) { {[]int{0, 1}, []interface{}{nil}, nil, true}, {tstNoStringer{}, []interface{}{0}, nil, true}, } { - c.Run(fmt.Sprint(i), func(c *qt.C) { errMsg := qt.Commentf("[%d] %v", i, test) diff --git a/tpl/collections/merge_test.go b/tpl/collections/merge_test.go index 92c973cd4..bde4d90b1 100644 --- a/tpl/collections/merge_test.go +++ b/tpl/collections/merge_test.go @@ -43,7 +43,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "c": 3}, map[string]interface{}{"a": 1, "b": 2}, }, - map[string]interface{}{"a": 1, "b": 2, "c": 3}, false, + map[string]interface{}{"a": 1, "b": 2, "c": 3}, + false, }, { "multi", @@ -52,7 +53,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 1, "b": 2}, map[string]interface{}{"a": 9, "c": 4, "d": 7}, }, - map[string]interface{}{"a": 9, "b": 2, "c": 4, "d": 7, "e": 11}, false, + map[string]interface{}{"a": 9, "b": 2, "c": 4, "d": 7, "e": 11}, + false, }, { "basic case insensitive", @@ -60,7 +62,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"A": 42, "c": 3}, map[string]interface{}{"a": 1, "b": 2}, }, - map[string]interface{}{"a": 1, "b": 2, "c": 3}, false, + map[string]interface{}{"a": 1, "b": 2, "c": 3}, + false, }, { "nested", @@ -68,7 +71,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "c": 3, "b": map[string]interface{}{"d": 55, "e": 66, "f": 3}}, map[string]interface{}{"a": 1, "b": map[string]interface{}{"d": 1, "e": 2}}, }, - map[string]interface{}{"a": 1, "b": map[string]interface{}{"d": 1, "e": 2, "f": 3}, "c": 3}, false, + map[string]interface{}{"a": 1, "b": map[string]interface{}{"d": 1, "e": 2, "f": 3}, "c": 3}, + false, }, { // https://github.com/gohugoio/hugo/issues/6633 @@ -77,7 +81,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "c": 3}, maps.Params{"a": 1, "b": 2}, }, - maps.Params{"a": int(1), "b": int(2), "c": int(3)}, false, + maps.Params{"a": int(1), "b": int(2), "c": int(3)}, + false, }, { "params dst, upper case src", @@ -85,7 +90,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "C": 3}, maps.Params{"a": 1, "b": 2}, }, - maps.Params{"a": int(1), "b": int(2), "c": int(3)}, false, + maps.Params{"a": int(1), "b": int(2), "c": int(3)}, + false, }, { "params src", @@ -93,7 +99,8 @@ func TestMerge(t *testing.T) { maps.Params{"a": 42, "c": 3}, map[string]interface{}{"a": 1, "c": 2}, }, - map[string]interface{}{"a": int(1), "c": int(2)}, false, + map[string]interface{}{"a": int(1), "c": int(2)}, + false, }, { "params src, upper case dst", @@ -101,7 +108,8 @@ func TestMerge(t *testing.T) { maps.Params{"a": 42, "c": 3}, map[string]interface{}{"a": 1, "C": 2}, }, - map[string]interface{}{"a": int(1), "C": int(2)}, false, + map[string]interface{}{"a": int(1), "C": int(2)}, + false, }, { "nested, params dst", @@ -109,7 +117,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "c": 3, "b": map[string]interface{}{"d": 55, "e": 66, "f": 3}}, maps.Params{"a": 1, "b": maps.Params{"d": 1, "e": 2}}, }, - maps.Params{"a": 1, "b": maps.Params{"d": 1, "e": 2, "f": 3}, "c": 3}, false, + maps.Params{"a": 1, "b": maps.Params{"d": 1, "e": 2, "f": 3}, "c": 3}, + false, }, { // https://github.com/gohugoio/hugo/issues/7899 @@ -118,7 +127,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"k": "v"}, map[string]interface{}{"k": map[string]interface{}{"k2": "v2"}}, }, - map[string]interface{}{"k": map[string]interface{}{"k2": "v2"}}, false, + map[string]interface{}{"k": map[string]interface{}{"k2": "v2"}}, + false, }, {"src nil", []interface{}{nil, simpleMap}, simpleMap, false}, // Error cases. diff --git a/tpl/collections/reflect_helpers.go b/tpl/collections/reflect_helpers.go index 3d73b70e1..453d2f356 100644 --- a/tpl/collections/reflect_helpers.go +++ b/tpl/collections/reflect_helpers.go @@ -165,7 +165,6 @@ func convertNumber(v reflect.Value, to reflect.Kind) (reflect.Value, error) { } return n, nil - } func newSliceElement(items interface{}) interface{} { diff --git a/tpl/collections/sort_test.go b/tpl/collections/sort_test.go index 75e23fc7b..4798b5090 100644 --- a/tpl/collections/sort_test.go +++ b/tpl/collections/sort_test.go @@ -238,7 +238,6 @@ func TestSort(t *testing.T) { }, {nil, nil, "asc", false}, } { - t.Run(fmt.Sprintf("test%d", i), func(t *testing.T) { var result interface{} var err error @@ -261,6 +260,5 @@ func TestSort(t *testing.T) { } } }) - } } diff --git a/tpl/collections/symdiff.go b/tpl/collections/symdiff.go index 85a2076aa..e61814e26 100644 --- a/tpl/collections/symdiff.go +++ b/tpl/collections/symdiff.go @@ -65,5 +65,4 @@ func (ns *Namespace) SymDiff(s2, s1 interface{}) (interface{}, error) { } return slice.Interface(), nil - } diff --git a/tpl/collections/symdiff_test.go b/tpl/collections/symdiff_test.go index ac40fda55..120dfaac6 100644 --- a/tpl/collections/symdiff_test.go +++ b/tpl/collections/symdiff_test.go @@ -75,5 +75,4 @@ func TestSymDiff(t *testing.T) { c.Assert(err, qt.Not(qt.IsNil)) _, err = ns.Complement([]string{"a", "b"}) c.Assert(err, qt.Not(qt.IsNil)) - } diff --git a/tpl/collections/where_test.go b/tpl/collections/where_test.go index d6a1dd141..75ee109f9 100644 --- a/tpl/collections/where_test.go +++ b/tpl/collections/where_test.go @@ -62,7 +62,6 @@ func TestWhere(t *testing.T) { } return testVariants - } for i, test := range []testt{ @@ -171,17 +170,17 @@ func TestWhere(t *testing.T) { }, key: "B", match: "b2", expect: []maps.Params{ - maps.Params{"a": "a2", "b": "b2"}, + {"a": "a2", "b": "b2"}, }, }, { seq: []maps.Params{ - maps.Params{ + { "a": map[string]interface{}{ "b": "b1", }, }, - maps.Params{ + { "a": map[string]interface{}{ "b": "b2", }, @@ -189,7 +188,7 @@ func TestWhere(t *testing.T) { }, key: "A.B", match: "b2", expect: []maps.Params{ - maps.Params{ + { "a": map[string]interface{}{ "b": "b2", }, diff --git a/tpl/compare/compare_test.go b/tpl/compare/compare_test.go index c21ca11bc..76fe2698a 100644 --- a/tpl/compare/compare_test.go +++ b/tpl/compare/compare_test.go @@ -44,8 +44,10 @@ var testT = &T{ NonEmptyInterfaceTypedNil: (*T)(nil), } -type tstEqerType1 string -type tstEqerType2 string +type ( + tstEqerType1 string + tstEqerType2 string +) func (t tstEqerType2) Eq(other interface{}) bool { return cast.ToString(t) == cast.ToString(other) @@ -397,7 +399,6 @@ func TestCase(t *testing.T) { c.Assert(n.Eq("az", "az"), qt.Equals, true) c.Assert(n.Eq("az", stringType("az")), qt.Equals, true) - } func TestStringType(t *testing.T) { diff --git a/tpl/compare/init.go b/tpl/compare/init.go index 3b9dc6856..f96e382e5 100644 --- a/tpl/compare/init.go +++ b/tpl/compare/init.go @@ -79,7 +79,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/crypto/init.go b/tpl/crypto/init.go index 9a958bd38..2c6e94298 100644 --- a/tpl/crypto/init.go +++ b/tpl/crypto/init.go @@ -59,7 +59,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/data/data.go b/tpl/data/data.go index 964844336..15d042e0a 100644 --- a/tpl/data/data.go +++ b/tpl/data/data.go @@ -35,7 +35,6 @@ import ( // New returns a new instance of the data-namespaced template functions. func New(deps *deps.Deps) *Namespace { - return &Namespace{ deps: deps, cacheGetCSV: deps.FileCaches.GetCSVCache(), diff --git a/tpl/data/data_test.go b/tpl/data/data_test.go index e1839dd48..f9e8621f2 100644 --- a/tpl/data/data_test.go +++ b/tpl/data/data_test.go @@ -109,7 +109,7 @@ func TestGetCSV(t *testing.T) { if _, ok := test.expect.(bool); ok { c.Assert(int(ns.deps.Log.LogCounters().ErrorCounter.Count()), qt.Equals, 1) - //c.Assert(err, msg, qt.Not(qt.IsNil)) + // c.Assert(err, msg, qt.Not(qt.IsNil)) c.Assert(got, qt.IsNil) continue } @@ -199,7 +199,7 @@ func TestGetJSON(t *testing.T) { if _, ok := test.expect.(bool); ok { c.Assert(int(ns.deps.Log.LogCounters().ErrorCounter.Count()), qt.Equals, 1) - //c.Assert(err, msg, qt.Not(qt.IsNil)) + // c.Assert(err, msg, qt.Not(qt.IsNil)) continue } diff --git a/tpl/data/resources.go b/tpl/data/resources.go index a7b8b3f49..ba98f12b4 100644 --- a/tpl/data/resources.go +++ b/tpl/data/resources.go @@ -81,7 +81,6 @@ func (ns *Namespace) getRemote(cache *filecache.Cache, unmarshal func([]byte) (b } return nil, err - }) if !handled { @@ -100,7 +99,6 @@ func getLocal(url string, fs afero.Fs, cfg config.Provider) ([]byte, error) { } return afero.ReadFile(fs, filename) - } // getResource loads the content of a local or remote file and returns its content and the diff --git a/tpl/data/resources_test.go b/tpl/data/resources_test.go index 7350f82f1..5ad0f0970 100644 --- a/tpl/data/resources_test.go +++ b/tpl/data/resources_test.go @@ -69,7 +69,6 @@ func TestScpGetLocal(t *testing.T) { t.Errorf("\nExpected: %s\nActual: %s\n", string(test.content), string(c)) } } - } func getTestServer(handler func(w http.ResponseWriter, r *http.Request)) (*httptest.Server, *http.Client) { diff --git a/tpl/fmt/fmt.go b/tpl/fmt/fmt.go index 780add0d1..713088b57 100644 --- a/tpl/fmt/fmt.go +++ b/tpl/fmt/fmt.go @@ -50,7 +50,6 @@ func (ns *Namespace) Print(a ...interface{}) string { // Printf returns a formatted string representation of the passed arguments. func (ns *Namespace) Printf(format string, a ...interface{}) string { return _fmt.Sprintf(format, a...) - } // Println returns string representation of the passed arguments ending with a newline. diff --git a/tpl/hugo/init.go b/tpl/hugo/init.go index 1556b759c..c57d4a27a 100644 --- a/tpl/hugo/init.go +++ b/tpl/hugo/init.go @@ -23,7 +23,6 @@ const name = "hugo" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { - h := d.Site.Hugo() ns := &internal.TemplateFuncsNamespace{ @@ -34,7 +33,6 @@ func init() { // We just add the Hugo struct as the namespace here. No method mappings. return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/images/init.go b/tpl/images/init.go index 299c76846..e9fd52e73 100644 --- a/tpl/images/init.go +++ b/tpl/images/init.go @@ -35,7 +35,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/inflect/init.go b/tpl/inflect/init.go index 3f258356b..52b234df3 100644 --- a/tpl/inflect/init.go +++ b/tpl/inflect/init.go @@ -54,7 +54,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/internal/go_templates/fmtsort/sort_test.go b/tpl/internal/go_templates/fmtsort/sort_test.go index 364c5bf6d..189c693cc 100644 --- a/tpl/internal/go_templates/fmtsort/sort_test.go +++ b/tpl/internal/go_templates/fmtsort/sort_test.go @@ -6,11 +6,12 @@ package fmtsort_test import ( "fmt" - "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort" "math" "reflect" "strings" "testing" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort" ) var compareTests = [][]reflect.Value{ diff --git a/tpl/internal/go_templates/htmltemplate/content_test.go b/tpl/internal/go_templates/htmltemplate/content_test.go index b5de701d3..f2c5c5ed1 100644 --- a/tpl/internal/go_templates/htmltemplate/content_test.go +++ b/tpl/internal/go_templates/htmltemplate/content_test.go @@ -427,7 +427,7 @@ func TestStringer(t *testing.T) { if err := tmpl.Execute(b, s); err != nil { t.Fatal(err) } - var expect = "string=3" + expect := "string=3" if b.String() != expect { t.Errorf("expected %q got %q", expect, b.String()) } diff --git a/tpl/internal/go_templates/htmltemplate/css.go b/tpl/internal/go_templates/htmltemplate/css.go index eb92fc92b..b006a0718 100644 --- a/tpl/internal/go_templates/htmltemplate/css.go +++ b/tpl/internal/go_templates/htmltemplate/css.go @@ -210,8 +210,10 @@ var cssReplacementTable = []string{ '}': `\7d`, } -var expressionBytes = []byte("expression") -var mozBindingBytes = []byte("mozbinding") +var ( + expressionBytes = []byte("expression") + mozBindingBytes = []byte("mozbinding") +) // cssValueFilter allows innocuous CSS values in the output including CSS // quantities (10px or 25%), ID or class literals (#foo, .bar), keyword values diff --git a/tpl/internal/go_templates/htmltemplate/escape_test.go b/tpl/internal/go_templates/htmltemplate/escape_test.go index 075db4e13..ee5421cc8 100644 --- a/tpl/internal/go_templates/htmltemplate/escape_test.go +++ b/tpl/internal/go_templates/htmltemplate/escape_test.go @@ -891,7 +891,6 @@ func TestEscapeSet(t *testing.T) { t.Errorf("want\n\t%q\ngot\n\t%q", test.want, got) } } - } func TestErrors(t *testing.T) { @@ -1088,7 +1087,6 @@ func TestErrors(t *testing.T) { // Check that we get the same error if we call Execute again. if err := tmpl.Execute(buf, nil); err == nil || err.Error() != got { t.Errorf("input=%q: unexpected error on second call %q", test.input, err) - } } } diff --git a/tpl/internal/go_templates/htmltemplate/example_test.go b/tpl/internal/go_templates/htmltemplate/example_test.go index a93b8d2fb..ee1cbbb4a 100644 --- a/tpl/internal/go_templates/htmltemplate/example_test.go +++ b/tpl/internal/go_templates/htmltemplate/example_test.go @@ -82,7 +82,6 @@ func Example() { // <div><strong>no rows</strong></div> // </body> // </html> - } func Example_autoescaping() { @@ -123,7 +122,6 @@ func Example_escape() { // \"Fran \u0026 Freddie\'s Diner\" \[email protected]\u003E // \"Fran \u0026 Freddie\'s Diner\"32\[email protected]\u003E // %22Fran+%26+Freddie%27s+Diner%2232%3Ctasty%40example.com%3E - } func ExampleTemplate_Delims() { diff --git a/tpl/internal/go_templates/htmltemplate/js.go b/tpl/internal/go_templates/htmltemplate/js.go index cfd413461..f19e774c7 100644 --- a/tpl/internal/go_templates/htmltemplate/js.go +++ b/tpl/internal/go_templates/htmltemplate/js.go @@ -337,6 +337,7 @@ var jsStrNormReplacementTable = []string{ '<': `\u003c`, '>': `\u003e`, } + var jsRegexpReplacementTable = []string{ 0: `\u0000`, '\t': `\t`, diff --git a/tpl/internal/go_templates/htmltemplate/js_test.go b/tpl/internal/go_templates/htmltemplate/js_test.go index e15087f0f..f7ee3cfaa 100644 --- a/tpl/internal/go_templates/htmltemplate/js_test.go +++ b/tpl/internal/go_templates/htmltemplate/js_test.go @@ -206,7 +206,8 @@ func TestJSStrEscaper(t *testing.T) { {"<!--", `\u003c!--`}, {"-->", `--\u003e`}, // From https://code.google.com/p/doctype/wiki/ArticleUtf7 - {"+ADw-script+AD4-alert(1)+ADw-/script+AD4-", + { + "+ADw-script+AD4-alert(1)+ADw-/script+AD4-", `\u002bADw-script\u002bAD4-alert(1)\u002bADw-\/script\u002bAD4-`, }, // Invalid UTF-8 sequence diff --git a/tpl/internal/go_templates/htmltemplate/transition.go b/tpl/internal/go_templates/htmltemplate/transition.go index 06df67933..5ba7f8017 100644 --- a/tpl/internal/go_templates/htmltemplate/transition.go +++ b/tpl/internal/go_templates/htmltemplate/transition.go @@ -41,8 +41,10 @@ var transitionFunc = [...]func(context, []byte) (context, int){ stateError: tError, } -var commentStart = []byte("<!--") -var commentEnd = []byte("-->") +var ( + commentStart = []byte("<!--") + commentEnd = []byte("-->") +) // tText is the context transition function for the text state. func tText(c context, s []byte) (context, int) { diff --git a/tpl/internal/go_templates/htmltemplate/transition_test.go b/tpl/internal/go_templates/htmltemplate/transition_test.go index 00b0ff6ca..c3257a839 100644 --- a/tpl/internal/go_templates/htmltemplate/transition_test.go +++ b/tpl/internal/go_templates/htmltemplate/transition_test.go @@ -42,7 +42,6 @@ func TestFindEndTag(t *testing.T) { } func BenchmarkTemplateSpecialTags(b *testing.B) { - r := struct { Name, Gift string }{"Aunt Mildred", "bone china tea set"} diff --git a/tpl/internal/go_templates/testenv/testenv.go b/tpl/internal/go_templates/testenv/testenv.go index 90044570d..7c46089f5 100644 --- a/tpl/internal/go_templates/testenv/testenv.go +++ b/tpl/internal/go_templates/testenv/testenv.go @@ -13,7 +13,6 @@ package testenv import ( "errors" "flag" - "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg" "os" "os/exec" "path/filepath" @@ -22,6 +21,8 @@ import ( "strings" "sync" "testing" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg" ) // Builder reports the name of the builder running this test diff --git a/tpl/internal/go_templates/testenv/testenv_windows.go b/tpl/internal/go_templates/testenv/testenv_windows.go index eb8d6ac16..f9e7da5a7 100644 --- a/tpl/internal/go_templates/testenv/testenv_windows.go +++ b/tpl/internal/go_templates/testenv/testenv_windows.go @@ -12,8 +12,10 @@ import ( "syscall" ) -var symlinkOnce sync.Once -var winSymlinkErr error +var ( + symlinkOnce sync.Once + winSymlinkErr error +) func initWinHasSymlink() { tmpdir, err := ioutil.TempDir("", "symtest") diff --git a/tpl/internal/go_templates/texttemplate/example_test.go b/tpl/internal/go_templates/texttemplate/example_test.go index f192cac4f..09555c95a 100644 --- a/tpl/internal/go_templates/texttemplate/example_test.go +++ b/tpl/internal/go_templates/texttemplate/example_test.go @@ -34,7 +34,7 @@ Josie Name, Gift string Attended bool } - var recipients = []Recipient{ + recipients := []Recipient{ {"Aunt Mildred", "bone china tea set", true}, {"Uncle John", "moleskin pants", false}, {"Cousin Rodney", "", false}, diff --git a/tpl/internal/go_templates/texttemplate/exec.go b/tpl/internal/go_templates/texttemplate/exec.go index 879cd0884..db533d735 100644 --- a/tpl/internal/go_templates/texttemplate/exec.go +++ b/tpl/internal/go_templates/texttemplate/exec.go @@ -6,12 +6,13 @@ package template import ( "fmt" - "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort" - "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "io" "reflect" "runtime" "strings" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort" + "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" ) // maxExecDepth specifies the maximum stack depth of templates within diff --git a/tpl/internal/go_templates/texttemplate/exec_test.go b/tpl/internal/go_templates/texttemplate/exec_test.go index 940a1de6a..cc79d2143 100644 --- a/tpl/internal/go_templates/texttemplate/exec_test.go +++ b/tpl/internal/go_templates/texttemplate/exec_test.go @@ -318,12 +318,16 @@ var execTests = []execTest{ {"$.U.V", "{{$.U.V}}", "v", tVal, true}, {"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true}, {"simple assignment", "{{$x := 2}}{{$x = 3}}{{$x}}", "3", tVal, true}, - {"nested assignment", + { + "nested assignment", "{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{$x}}", - "3", tVal, true}, - {"nested assignment changes the last declaration", + "3", tVal, true, + }, + { + "nested assignment changes the last declaration", "{{$x := 1}}{{if true}}{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{end}}{{$x}}", - "1", tVal, true}, + "1", tVal, true, + }, // Type with String method. {"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true}, @@ -370,15 +374,21 @@ var execTests = []execTest{ {".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: <nil>-", tVal, true}, {".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true}, {"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true}, - {"method on chained var", + { + "method on chained var", "{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}", - "true", tVal, true}, - {"chained method", + "true", tVal, true, + }, + { + "chained method", "{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}", - "true", tVal, true}, - {"chained method on variable", + "true", tVal, true, + }, + { + "chained method on variable", "{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}", - "true", tVal, true}, + "true", tVal, true, + }, {".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true}, {".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true}, {"method on nil value from slice", "-{{range .}}{{.Method1 1234}}{{end}}-", "-1234-", tSliceOfNil, true}, @@ -464,10 +474,14 @@ var execTests = []execTest{ {"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true}, // HTML. - {"html", `{{html "<script>alert(\"XSS\");</script>"}}`, - "<script>alert("XSS");</script>", nil, true}, - {"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`, - "<script>alert("XSS");</script>", nil, true}, + { + "html", `{{html "<script>alert(\"XSS\");</script>"}}`, + "<script>alert("XSS");</script>", nil, true, + }, + { + "html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`, + "<script>alert("XSS");</script>", nil, true, + }, {"html", `{{html .PS}}`, "a string", tVal, true}, {"html typed nil", `{{html .NIL}}`, "<nil>", tVal, true}, {"html untyped nil", `{{html .Empty0}}`, "<no value>", tVal, true}, @@ -825,7 +839,7 @@ var delimPairs = []string{ func TestDelims(t *testing.T) { const hello = "Hello, world" - var value = struct{ Str string }{hello} + value := struct{ Str string }{hello} for i := 0; i < len(delimPairs); i += 2 { text := ".Str" left := delimPairs[i+0] @@ -848,7 +862,7 @@ func TestDelims(t *testing.T) { if err != nil { t.Fatalf("delim %q text %q parse err %s", left, text, err) } - var b = new(bytes.Buffer) + b := new(bytes.Buffer) err = tmpl.Execute(b, value) if err != nil { t.Fatalf("delim %q exec err %s", left, err) @@ -949,7 +963,7 @@ const treeTemplate = ` ` func TestTree(t *testing.T) { - var tree = &Tree{ + tree := &Tree{ 1, &Tree{ 2, &Tree{ @@ -1195,7 +1209,7 @@ var cmpTests = []cmpTest{ func TestComparison(t *testing.T) { b := new(bytes.Buffer) - var cmpStruct = struct { + cmpStruct := struct { Uthree, Ufour uint NegOne, Three int Ptr, NilPtr *int diff --git a/tpl/internal/go_templates/texttemplate/hugo_template.go b/tpl/internal/go_templates/texttemplate/hugo_template.go index 7cd6df0fb..0dc6331c7 100644 --- a/tpl/internal/go_templates/texttemplate/hugo_template.go +++ b/tpl/internal/go_templates/texttemplate/hugo_template.go @@ -77,7 +77,6 @@ func (t *executer) Execute(p Preparer, wr io.Writer, data interface{}) error { } return tmpl.executeWithState(state, value) - } // Prepare returns a template ready for execution. diff --git a/tpl/internal/go_templates/texttemplate/hugo_template_test.go b/tpl/internal/go_templates/texttemplate/hugo_template_test.go index 98a2575eb..90bb09315 100644 --- a/tpl/internal/go_templates/texttemplate/hugo_template_test.go +++ b/tpl/internal/go_templates/texttemplate/hugo_template_test.go @@ -85,5 +85,4 @@ Method: {{ .Hello1 "v1" }} c.Assert(got, qt.Contains, "hello hugo") c.Assert(got, qt.Contains, "Map: av") c.Assert(got, qt.Contains, "Method: v2 v1") - } diff --git a/tpl/internal/go_templates/texttemplate/multi_test.go b/tpl/internal/go_templates/texttemplate/multi_test.go index 7323be379..569a45dbb 100644 --- a/tpl/internal/go_templates/texttemplate/multi_test.go +++ b/tpl/internal/go_templates/texttemplate/multi_test.go @@ -11,8 +11,9 @@ package template import ( "bytes" "fmt" - "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "testing" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" ) const ( @@ -29,22 +30,32 @@ type multiParseTest struct { } var multiParseTests = []multiParseTest{ - {"empty", "", noError, + { + "empty", "", noError, nil, - nil}, - {"one", `{{define "foo"}} FOO {{end}}`, noError, + nil, + }, + { + "one", `{{define "foo"}} FOO {{end}}`, noError, []string{"foo"}, - []string{" FOO "}}, - {"two", `{{define "foo"}} FOO {{end}}{{define "bar"}} BAR {{end}}`, noError, + []string{" FOO "}, + }, + { + "two", `{{define "foo"}} FOO {{end}}{{define "bar"}} BAR {{end}}`, noError, []string{"foo", "bar"}, - []string{" FOO ", " BAR "}}, + []string{" FOO ", " BAR "}, + }, // errors - {"missing end", `{{define "foo"}} FOO `, hasError, + { + "missing end", `{{define "foo"}} FOO `, hasError, + nil, + nil, + }, + { + "malformed name", `{{define "foo}} FOO `, hasError, nil, - nil}, - {"malformed name", `{{define "foo}} FOO `, hasError, nil, - nil}, + }, } func TestMultiParse(t *testing.T) { @@ -400,7 +411,7 @@ func TestIssue19294(t *testing.T) { // by the contents of "stylesheet", but if the internal map associating // names with templates is built in the wrong order, the empty block // looks non-empty and this doesn't happen. - var inlined = map[string]string{ + inlined := map[string]string{ "stylesheet": `{{define "stylesheet"}}stylesheet{{end}}`, "xhtml": `{{block "stylesheet" .}}{{end}}`, } diff --git a/tpl/internal/go_templates/texttemplate/parse/node.go b/tpl/internal/go_templates/texttemplate/parse/node.go index 1c116ea6f..dee67a2ed 100644 --- a/tpl/internal/go_templates/texttemplate/parse/node.go +++ b/tpl/internal/go_templates/texttemplate/parse/node.go @@ -249,7 +249,6 @@ func (a *ActionNode) tree() *Tree { func (a *ActionNode) Copy() Node { return a.tr.newAction(a.Pos, a.Line, a.Pipe.CopyPipe()) - } // CommandNode holds a command (a pipeline inside an evaluating action). diff --git a/tpl/internal/go_templates/texttemplate/parse/parse.go b/tpl/internal/go_templates/texttemplate/parse/parse.go index c9b80f4a2..7a58c5788 100644 --- a/tpl/internal/go_templates/texttemplate/parse/parse.go +++ b/tpl/internal/go_templates/texttemplate/parse/parse.go @@ -453,7 +453,7 @@ func (t *Tree) parseControl(allowElseIf bool, context string) (pos Pos, line int var next Node list, next = t.itemList() switch next.Type() { - case nodeEnd: //done + case nodeEnd: // done case nodeElse: if allowElseIf { // Special case for "else if". If the "else" is followed immediately by an "if", diff --git a/tpl/internal/go_templates/texttemplate/parse/parse_test.go b/tpl/internal/go_templates/texttemplate/parse/parse_test.go index 79e7bb5ae..97511190d 100644 --- a/tpl/internal/go_templates/texttemplate/parse/parse_test.go +++ b/tpl/internal/go_templates/texttemplate/parse/parse_test.go @@ -178,70 +178,134 @@ const ( ) var parseTests = []parseTest{ - {"empty", "", noError, - ``}, - {"comment", "{{/*\n\n\n*/}}", noError, - ``}, - {"spaces", " \t\n", noError, - `" \t\n"`}, - {"text", "some text", noError, - `"some text"`}, - {"emptyAction", "{{}}", hasError, - `{{}}`}, - {"field", "{{.X}}", noError, - `{{.X}}`}, - {"simple command", "{{printf}}", noError, - `{{printf}}`}, - {"$ invocation", "{{$}}", noError, - "{{$}}"}, - {"variable invocation", "{{with $x := 3}}{{$x 23}}{{end}}", noError, - "{{with $x := 3}}{{$x 23}}{{end}}"}, - {"variable with fields", "{{$.I}}", noError, - "{{$.I}}"}, - {"multi-word command", "{{printf `%d` 23}}", noError, - "{{printf `%d` 23}}"}, - {"pipeline", "{{.X|.Y}}", noError, - `{{.X | .Y}}`}, - {"pipeline with decl", "{{$x := .X|.Y}}", noError, - `{{$x := .X | .Y}}`}, - {"nested pipeline", "{{.X (.Y .Z) (.A | .B .C) (.E)}}", noError, - `{{.X (.Y .Z) (.A | .B .C) (.E)}}`}, - {"field applied to parentheses", "{{(.Y .Z).Field}}", noError, - `{{(.Y .Z).Field}}`}, - {"simple if", "{{if .X}}hello{{end}}", noError, - `{{if .X}}"hello"{{end}}`}, - {"if with else", "{{if .X}}true{{else}}false{{end}}", noError, - `{{if .X}}"true"{{else}}"false"{{end}}`}, - {"if with else if", "{{if .X}}true{{else if .Y}}false{{end}}", noError, - `{{if .X}}"true"{{else}}{{if .Y}}"false"{{end}}{{end}}`}, - {"if else chain", "+{{if .X}}X{{else if .Y}}Y{{else if .Z}}Z{{end}}+", noError, - `"+"{{if .X}}"X"{{else}}{{if .Y}}"Y"{{else}}{{if .Z}}"Z"{{end}}{{end}}{{end}}"+"`}, - {"simple range", "{{range .X}}hello{{end}}", noError, - `{{range .X}}"hello"{{end}}`}, - {"chained field range", "{{range .X.Y.Z}}hello{{end}}", noError, - `{{range .X.Y.Z}}"hello"{{end}}`}, - {"nested range", "{{range .X}}hello{{range .Y}}goodbye{{end}}{{end}}", noError, - `{{range .X}}"hello"{{range .Y}}"goodbye"{{end}}{{end}}`}, - {"range with else", "{{range .X}}true{{else}}false{{end}}", noError, - `{{range .X}}"true"{{else}}"false"{{end}}`}, - {"range over pipeline", "{{range .X|.M}}true{{else}}false{{end}}", noError, - `{{range .X | .M}}"true"{{else}}"false"{{end}}`}, - {"range []int", "{{range .SI}}{{.}}{{end}}", noError, - `{{range .SI}}{{.}}{{end}}`}, - {"range 1 var", "{{range $x := .SI}}{{.}}{{end}}", noError, - `{{range $x := .SI}}{{.}}{{end}}`}, - {"range 2 vars", "{{range $x, $y := .SI}}{{.}}{{end}}", noError, - `{{range $x, $y := .SI}}{{.}}{{end}}`}, - {"constants", "{{range .SI 1 -3.2i true false 'a' nil}}{{end}}", noError, - `{{range .SI 1 -3.2i true false 'a' nil}}{{end}}`}, - {"template", "{{template `x`}}", noError, - `{{template "x"}}`}, - {"template with arg", "{{template `x` .Y}}", noError, - `{{template "x" .Y}}`}, - {"with", "{{with .X}}hello{{end}}", noError, - `{{with .X}}"hello"{{end}}`}, - {"with with else", "{{with .X}}hello{{else}}goodbye{{end}}", noError, - `{{with .X}}"hello"{{else}}"goodbye"{{end}}`}, + { + "empty", "", noError, + ``, + }, + { + "comment", "{{/*\n\n\n*/}}", noError, + ``, + }, + { + "spaces", " \t\n", noError, + `" \t\n"`, + }, + { + "text", "some text", noError, + `"some text"`, + }, + { + "emptyAction", "{{}}", hasError, + `{{}}`, + }, + { + "field", "{{.X}}", noError, + `{{.X}}`, + }, + { + "simple command", "{{printf}}", noError, + `{{printf}}`, + }, + { + "$ invocation", "{{$}}", noError, + "{{$}}", + }, + { + "variable invocation", "{{with $x := 3}}{{$x 23}}{{end}}", noError, + "{{with $x := 3}}{{$x 23}}{{end}}", + }, + { + "variable with fields", "{{$.I}}", noError, + "{{$.I}}", + }, + { + "multi-word command", "{{printf `%d` 23}}", noError, + "{{printf `%d` 23}}", + }, + { + "pipeline", "{{.X|.Y}}", noError, + `{{.X | .Y}}`, + }, + { + "pipeline with decl", "{{$x := .X|.Y}}", noError, + `{{$x := .X | .Y}}`, + }, + { + "nested pipeline", "{{.X (.Y .Z) (.A | .B .C) (.E)}}", noError, + `{{.X (.Y .Z) (.A | .B .C) (.E)}}`, + }, + { + "field applied to parentheses", "{{(.Y .Z).Field}}", noError, + `{{(.Y .Z).Field}}`, + }, + { + "simple if", "{{if .X}}hello{{end}}", noError, + `{{if .X}}"hello"{{end}}`, + }, + { + "if with else", "{{if .X}}true{{else}}false{{end}}", noError, + `{{if .X}}"true"{{else}}"false"{{end}}`, + }, + { + "if with else if", "{{if .X}}true{{else if .Y}}false{{end}}", noError, + `{{if .X}}"true"{{else}}{{if .Y}}"false"{{end}}{{end}}`, + }, + { + "if else chain", "+{{if .X}}X{{else if .Y}}Y{{else if .Z}}Z{{end}}+", noError, + `"+"{{if .X}}"X"{{else}}{{if .Y}}"Y"{{else}}{{if .Z}}"Z"{{end}}{{end}}{{end}}"+"`, + }, + { + "simple range", "{{range .X}}hello{{end}}", noError, + `{{range .X}}"hello"{{end}}`, + }, + { + "chained field range", "{{range .X.Y.Z}}hello{{end}}", noError, + `{{range .X.Y.Z}}"hello"{{end}}`, + }, + { + "nested range", "{{range .X}}hello{{range .Y}}goodbye{{end}}{{end}}", noError, + `{{range .X}}"hello"{{range .Y}}"goodbye"{{end}}{{end}}`, + }, + { + "range with else", "{{range .X}}true{{else}}false{{end}}", noError, + `{{range .X}}"true"{{else}}"false"{{end}}`, + }, + { + "range over pipeline", "{{range .X|.M}}true{{else}}false{{end}}", noError, + `{{range .X | .M}}"true"{{else}}"false"{{end}}`, + }, + { + "range []int", "{{range .SI}}{{.}}{{end}}", noError, + `{{range .SI}}{{.}}{{end}}`, + }, + { + "range 1 var", "{{range $x := .SI}}{{.}}{{end}}", noError, + `{{range $x := .SI}}{{.}}{{end}}`, + }, + { + "range 2 vars", "{{range $x, $y := .SI}}{{.}}{{end}}", noError, + `{{range $x, $y := .SI}}{{.}}{{end}}`, + }, + { + "constants", "{{range .SI 1 -3.2i true false 'a' nil}}{{end}}", noError, + `{{range .SI 1 -3.2i true false 'a' nil}}{{end}}`, + }, + { + "template", "{{template `x`}}", noError, + `{{template "x"}}`, + }, + { + "template with arg", "{{template `x` .Y}}", noError, + `{{template "x" .Y}}`, + }, + { + "with", "{{with .X}}hello{{end}}", noError, + `{{with .X}}"hello"{{end}}`, + }, + { + "with with else", "{{with .X}}hello{{else}}goodbye{{end}}", noError, + `{{with .X}}"hello"{{else}}"goodbye"{{end}}`, + }, // Trimming spaces. {"trim left", "x \r\n\t{{- 3}}", noError, `"x"{{3}}`}, {"trim right", "{{3 -}}\n\n\ty", noError, `{{3}}"y"`}, @@ -250,8 +314,10 @@ var parseTests = []parseTest{ {"comment trim left", "x \r\n\t{{- /* hi */}}", noError, `"x"`}, {"comment trim right", "{{/* hi */ -}}\n\n\ty", noError, `"y"`}, {"comment trim left and right", "x \r\n\t{{- /* */ -}}\n\n\ty", noError, `"x""y"`}, - {"block definition", `{{block "foo" .}}hello{{end}}`, noError, - `{{template "foo" .}}`}, + { + "block definition", `{{block "foo" .}}hello{{end}}`, noError, + `{{template "foo" .}}`, + }, // Errors. {"unclosed action", "hello{{range", hasError, ""}, {"unmatched end", "{{end}}", hasError, ""}, @@ -401,89 +467,143 @@ func TestErrorContextWithTreeCopy(t *testing.T) { // All failures, and the result is a string that must appear in the error message. var errorTests = []parseTest{ // Check line numbers are accurate. - {"unclosed1", + { + "unclosed1", "line1\n{{", - hasError, `unclosed1:2: unexpected unclosed action in command`}, - {"unclosed2", + hasError, `unclosed1:2: unexpected unclosed action in command`, + }, + { + "unclosed2", "line1\n{{define `x`}}line2\n{{", - hasError, `unclosed2:3: unexpected unclosed action in command`}, + hasError, `unclosed2:3: unexpected unclosed action in command`, + }, // Specific errors. - {"function", + { + "function", "{{foo}}", - hasError, `function "foo" not defined`}, - {"comment", + hasError, `function "foo" not defined`, + }, + { + "comment", "{{/*}}", - hasError, `unclosed comment`}, - {"lparen", + hasError, `unclosed comment`, + }, + { + "lparen", "{{.X (1 2 3}}", - hasError, `unclosed left paren`}, - {"rparen", + hasError, `unclosed left paren`, + }, + { + "rparen", "{{.X 1 2 3)}}", - hasError, `unexpected ")"`}, - {"space", + hasError, `unexpected ")"`, + }, + { + "space", "{{`x`3}}", - hasError, `in operand`}, - {"idchar", + hasError, `in operand`, + }, + { + "idchar", "{{a#}}", - hasError, `'#'`}, - {"charconst", + hasError, `'#'`, + }, + { + "charconst", "{{'a}}", - hasError, `unterminated character constant`}, - {"stringconst", + hasError, `unterminated character constant`, + }, + { + "stringconst", `{{"a}}`, - hasError, `unterminated quoted string`}, - {"rawstringconst", + hasError, `unterminated quoted string`, + }, + { + "rawstringconst", "{{`a}}", - hasError, `unterminated raw quoted string`}, - {"number", + hasError, `unterminated raw quoted string`, + }, + { + "number", "{{0xi}}", - hasError, `number syntax`}, - {"multidefine", + hasError, `number syntax`, + }, + { + "multidefine", "{{define `a`}}a{{end}}{{define `a`}}b{{end}}", - hasError, `multiple definition of template`}, - {"eof", + hasError, `multiple definition of template`, + }, + { + "eof", "{{range .X}}", - hasError, `unexpected EOF`}, - {"variable", + hasError, `unexpected EOF`, + }, + { + "variable", // Declare $x so it's defined, to avoid that error, and then check we don't parse a declaration. "{{$x := 23}}{{with $x.y := 3}}{{$x 23}}{{end}}", - hasError, `unexpected ":="`}, - {"multidecl", + hasError, `unexpected ":="`, + }, + { + "multidecl", "{{$a,$b,$c := 23}}", - hasError, `too many declarations`}, - {"undefvar", + hasError, `too many declarations`, + }, + { + "undefvar", "{{$a}}", - hasError, `undefined variable`}, - {"wrongdot", + hasError, `undefined variable`, + }, + { + "wrongdot", "{{true.any}}", - hasError, `unexpected . after term`}, - {"wrongpipeline", + hasError, `unexpected . after term`, + }, + { + "wrongpipeline", "{{12|false}}", - hasError, `non executable command in pipeline`}, - {"emptypipeline", + hasError, `non executable command in pipeline`, + }, + { + "emptypipeline", `{{ ( ) }}`, - hasError, `missing value for parenthesized pipeline`}, - {"multilinerawstring", + hasError, `missing value for parenthesized pipeline`, + }, + { + "multilinerawstring", "{{ $v := `\n` }} {{", - hasError, `multilinerawstring:2: unexpected unclosed action`}, - {"rangeundefvar", + hasError, `multilinerawstring:2: unexpected unclosed action`, + }, + { + "rangeundefvar", "{{range $k}}{{end}}", - hasError, `undefined variable`}, - {"rangeundefvars", + hasError, `undefined variable`, + }, + { + "rangeundefvars", "{{range $k, $v}}{{end}}", - hasError, `undefined variable`}, - {"rangemissingvalue1", + hasError, `undefined variable`, + }, + { + "rangemissingvalue1", "{{range $k,}}{{end}}", - hasError, `missing value for range`}, - {"rangemissingvalue2", + hasError, `missing value for range`, + }, + { + "rangemissingvalue2", "{{range $k, $v := }}{{end}}", - hasError, `missing value for range`}, - {"rangenotvariable1", + hasError, `missing value for range`, + }, + { + "rangenotvariable1", "{{range $k, .}}{{end}}", - hasError, `range can only initialize variables`}, - {"rangenotvariable2", + hasError, `range can only initialize variables`, + }, + { + "rangenotvariable2", "{{range $k, 123 := .}}{{end}}", - hasError, `range can only initialize variables`}, + hasError, `range can only initialize variables`, + }, } func TestErrors(t *testing.T) { diff --git a/tpl/internal/go_templates/texttemplate/template.go b/tpl/internal/go_templates/texttemplate/template.go index 9c6ba6dfc..755a8426e 100644 --- a/tpl/internal/go_templates/texttemplate/template.go +++ b/tpl/internal/go_templates/texttemplate/template.go @@ -5,9 +5,10 @@ package template import ( - "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "reflect" "sync" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" ) // common holds the information shared by related templates. diff --git a/tpl/internal/templatefuncsRegistry.go b/tpl/internal/templatefuncsRegistry.go index 99877dcca..6d58d8d2b 100644 --- a/tpl/internal/templatefuncsRegistry.go +++ b/tpl/internal/templatefuncsRegistry.go @@ -83,7 +83,6 @@ func (t *TemplateFuncsNamespace) AddMethodMapping(m interface{}, aliases []strin Aliases: aliases, Examples: examples, } - } // TemplateFuncMethodMapping represents a mapping of functions to methods for a @@ -165,7 +164,6 @@ func (namespaces TemplateFuncsNamespaces) MarshalJSON() ([]byte, error) { } func (t *TemplateFuncsNamespace) toJSON() ([]byte, error) { - var buf bytes.Buffer godoc := getGetTplPackagesGoDoc()[t.Name] diff --git a/tpl/js/js.go b/tpl/js/js.go index b7a2fe066..d5d435be7 100644 --- a/tpl/js/js.go +++ b/tpl/js/js.go @@ -62,5 +62,4 @@ func (ns *Namespace) Build(args ...interface{}) (resource.Resource, error) { } return ns.client.Process(r, m) - } diff --git a/tpl/lang/init.go b/tpl/lang/init.go index 6a23cdc4c..520eccb88 100644 --- a/tpl/lang/init.go +++ b/tpl/lang/init.go @@ -45,7 +45,6 @@ func init() { }, ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/math/init.go b/tpl/math/init.go index e7f9114ba..ddbd2fc73 100644 --- a/tpl/math/init.go +++ b/tpl/math/init.go @@ -114,7 +114,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/math/math.go b/tpl/math/math.go index ecaf61ebc..2b2497c3e 100644 --- a/tpl/math/math.go +++ b/tpl/math/math.go @@ -64,7 +64,6 @@ func (ns *Namespace) Floor(x interface{}) (float64, error) { // Log returns the natural logarithm of a number. func (ns *Namespace) Log(a interface{}) (float64, error) { af, err := cast.ToFloat64E(a) - if err != nil { return 0, errors.New("Log operator can't be used with non integer or float value") } @@ -76,7 +75,6 @@ func (ns *Namespace) Log(a interface{}) (float64, error) { // NOTE: will return for NaN for negative values of a func (ns *Namespace) Sqrt(a interface{}) (float64, error) { af, err := cast.ToFloat64E(a) - if err != nil { return 0, errors.New("Sqrt operator can't be used with non integer or float value") } diff --git a/tpl/math/math_test.go b/tpl/math/math_test.go index c48f71837..da59d7938 100644 --- a/tpl/math/math_test.go +++ b/tpl/math/math_test.go @@ -197,7 +197,6 @@ func TestSqrt(t *testing.T) { result, err := ns.Sqrt(-1) c.Assert(err, qt.IsNil) c.Assert(result, qt.Satisfies, math.IsNaN) - } func TestMod(t *testing.T) { diff --git a/tpl/openapi/openapi3/init.go b/tpl/openapi/openapi3/init.go index 1e1a4ae05..4b4396ff4 100644 --- a/tpl/openapi/openapi3/init.go +++ b/tpl/openapi/openapi3/init.go @@ -35,7 +35,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/openapi/openapi3/openapi3.go b/tpl/openapi/openapi3/openapi3.go index 7dfd2f6a7..cc88f4125 100644 --- a/tpl/openapi/openapi3/openapi3.go +++ b/tpl/openapi/openapi3/openapi3.go @@ -49,7 +49,6 @@ type Namespace struct { } func (ns *Namespace) Unmarshal(r resource.UnmarshableResource) (*kopenapi3.Swagger, error) { - key := r.Key() if key == "" { return nil, errors.New("no Key set in Resource") @@ -87,11 +86,9 @@ func (ns *Namespace) Unmarshal(r resource.UnmarshableResource) (*kopenapi3.Swagg return s, err }) - if err != nil { return nil, err } return v.(*kopenapi3.Swagger), nil - } diff --git a/tpl/os/init.go b/tpl/os/init.go index 3ef8702d6..9d9b75473 100644 --- a/tpl/os/init.go +++ b/tpl/os/init.go @@ -56,7 +56,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/os/os.go b/tpl/os/os.go index eb31498af..214706593 100644 --- a/tpl/os/os.go +++ b/tpl/os/os.go @@ -28,7 +28,6 @@ import ( // New returns a new instance of the os-namespaced template functions. func New(d *deps.Deps) *Namespace { - var rfs afero.Fs if d.Fs != nil { rfs = d.Fs.WorkingDir @@ -80,7 +79,6 @@ func readFile(fs afero.Fs, filename string) (string, error) { return "", err } b, err := afero.ReadFile(fs, filename) - if err != nil { return "", err } diff --git a/tpl/partials/init.go b/tpl/partials/init.go index c2135bca5..4666fa336 100644 --- a/tpl/partials/init.go +++ b/tpl/partials/init.go @@ -49,7 +49,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/partials/partials.go b/tpl/partials/partials.go index 8b545399e..016e0423c 100644 --- a/tpl/partials/partials.go +++ b/tpl/partials/partials.go @@ -159,7 +159,6 @@ func (ns *Namespace) Include(name string, contextList ...interface{}) (interface } return result, nil - } // IncludeCached executes and caches partial templates. The cache is created with name+variants as the key. diff --git a/tpl/partials/partials_test.go b/tpl/partials/partials_test.go index 60e9dd721..656ab2d59 100644 --- a/tpl/partials/partials_test.go +++ b/tpl/partials/partials_test.go @@ -37,5 +37,4 @@ func TestCreateKey(t *testing.T) { c.Assert(create("a", map[string]string{"a": "av"}), qt.Equals, partialCacheKey{name: "a", variant: "4809626101226749924"}) c.Assert(create("a", []string{"a", "b"}), qt.Equals, partialCacheKey{name: "a", variant: "2712570657419664240"}) } - } diff --git a/tpl/path/init.go b/tpl/path/init.go index 518dcad22..a7f65073c 100644 --- a/tpl/path/init.go +++ b/tpl/path/init.go @@ -55,7 +55,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) } diff --git a/tpl/resources/init.go b/tpl/resources/init.go index df83cb3bb..d0e20d0ae 100644 --- a/tpl/resources/init.go +++ b/tpl/resources/init.go @@ -66,7 +66,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/resources/resources.go b/tpl/resources/resources.go index cdde6bd5d..73f3743b6 100644 --- a/tpl/resources/resources.go +++ b/tpl/resources/resources.go @@ -93,7 +93,6 @@ func (ns *Namespace) Get(filename interface{}) (resource.Resource, error) { filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) - } // GetMatch finds the first Resource matching the given pattern, or nil if none found. @@ -108,7 +107,6 @@ func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { } return ns.createClient.GetMatch(patternStr) - } // Match gets all resources matching the given base path prefix, e.g @@ -281,7 +279,6 @@ func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) - } // Babel processes the given Resource with Babel. @@ -300,5 +297,4 @@ func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { } return ns.babelClient.Process(r, options) - } diff --git a/tpl/safe/init.go b/tpl/safe/init.go index edb16ed87..becaf38f3 100644 --- a/tpl/safe/init.go +++ b/tpl/safe/init.go @@ -74,7 +74,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/safe/safe_test.go b/tpl/safe/safe_test.go index d5288fef0..e91605762 100644 --- a/tpl/safe/safe_test.go +++ b/tpl/safe/safe_test.go @@ -15,7 +15,6 @@ package safe import ( "html/template" - "testing" qt "github.com/frankban/quicktest" diff --git a/tpl/site/init.go b/tpl/site/init.go index 48713bb3b..4dc934997 100644 --- a/tpl/site/init.go +++ b/tpl/site/init.go @@ -24,7 +24,6 @@ const name = "site" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { - s := d.Site ns := &internal.TemplateFuncsNamespace{ Name: name, @@ -38,7 +37,6 @@ func init() { // We just add the Site as the namespace here. No method mappings. return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/strings/truncate.go b/tpl/strings/truncate.go index ff863db7c..6e3a50ed2 100644 --- a/tpl/strings/truncate.go +++ b/tpl/strings/truncate.go @@ -17,7 +17,6 @@ import ( "errors" "html" "html/template" - "regexp" "unicode" "unicode/utf8" diff --git a/tpl/strings/truncate_test.go b/tpl/strings/truncate_test.go index b4aa1ffad..51743e935 100644 --- a/tpl/strings/truncate_test.go +++ b/tpl/strings/truncate_test.go @@ -15,7 +15,6 @@ package strings import ( "html/template" - "reflect" "strings" "testing" @@ -81,5 +80,4 @@ func TestTruncate(t *testing.T) { if err == nil { t.Errorf("Should have errored") } - } diff --git a/tpl/template.go b/tpl/template.go index 82d877545..73db9b3a6 100644 --- a/tpl/template.go +++ b/tpl/template.go @@ -14,9 +14,8 @@ package tpl import ( - "reflect" - "io" + "reflect" "regexp" "github.com/gohugoio/hugo/output" diff --git a/tpl/templates/init.go b/tpl/templates/init.go index 8bc53ef49..4ae5c12cc 100644 --- a/tpl/templates/init.go +++ b/tpl/templates/init.go @@ -31,13 +31,13 @@ func init() { ns.AddMethodMapping(ctx.Exists, nil, - [][2]string{{`{{ if (templates.Exists "partials/header.html") }}Yes!{{ end }}`, `Yes!`}, + [][2]string{ + {`{{ if (templates.Exists "partials/header.html") }}Yes!{{ end }}`, `Yes!`}, {`{{ if not (templates.Exists "partials/doesnotexist.html") }}No!{{ end }}`, `No!`}, }, ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/templates/templates.go b/tpl/templates/templates.go index 80eb2d378..e00537330 100644 --- a/tpl/templates/templates.go +++ b/tpl/templates/templates.go @@ -36,5 +36,4 @@ type Namespace struct { func (ns *Namespace) Exists(name string) bool { _, found := ns.deps.Tmpl().Lookup(name) return found - } diff --git a/tpl/time/init.go b/tpl/time/init.go index 7abb36637..23e5263ba 100644 --- a/tpl/time/init.go +++ b/tpl/time/init.go @@ -91,7 +91,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/tplimpl/embedded/generate/generate.go b/tpl/tplimpl/embedded/generate/generate.go index df4de4799..3f7cc0257 100644 --- a/tpl/tplimpl/embedded/generate/generate.go +++ b/tpl/tplimpl/embedded/generate/generate.go @@ -25,7 +25,6 @@ import ( ) func main() { - templateFolder := filepath.Join("..", "templates") temlatePath := filepath.Join(".", templateFolder) @@ -92,7 +91,6 @@ var EmbeddedTemplates = [][2]string{ fmt.Fprint(file, " ", v, ",\n") } fmt.Fprint(file, "}\n") - } func nameValue(name, value string) string { diff --git a/tpl/tplimpl/shortcodes.go b/tpl/tplimpl/shortcodes.go index cc4d99491..789bc07d3 100644 --- a/tpl/tplimpl/shortcodes.go +++ b/tpl/tplimpl/shortcodes.go @@ -80,7 +80,6 @@ func (s *shortcodeTemplates) fromVariantsSlice(variants []string) (shortcodeVari // calculate a weight for two string slices of same length. // higher value means "better match". func (s *shortcodeTemplates) compareVariants(a, b []string) int { - weight := 0 k := len(a) for i, av := range a { @@ -101,7 +100,6 @@ func templateVariants(name string) []string { } func templateNameAndVariants(name string) (string, []string) { - variants := make([]string, numTemplateVariants) parts := strings.Split(name, ".") diff --git a/tpl/tplimpl/shortcodes_test.go b/tpl/tplimpl/shortcodes_test.go index 4ef8c5cd7..f97c7f278 100644 --- a/tpl/tplimpl/shortcodes_test.go +++ b/tpl/tplimpl/shortcodes_test.go @@ -20,14 +20,12 @@ import ( ) func TestShortcodesTemplate(t *testing.T) { - t.Run("isShortcode", func(t *testing.T) { c := qt.New(t) c.Assert(isShortcode("shortcodes/figures.html"), qt.Equals, true) c.Assert(isShortcode("_internal/shortcodes/figures.html"), qt.Equals, true) c.Assert(isShortcode("shortcodes\\figures.html"), qt.Equals, false) c.Assert(isShortcode("myshortcodes"), qt.Equals, false) - }) t.Run("variantsFromName", func(t *testing.T) { @@ -40,7 +38,6 @@ func TestShortcodesTemplate(t *testing.T) { name, variants := templateNameAndVariants("figure.html") c.Assert(name, qt.Equals, "figure") c.Assert(variants, qt.DeepEquals, []string{"", "html", "html"}) - }) t.Run("compareVariants", func(t *testing.T) { @@ -65,7 +62,6 @@ func TestShortcodesTemplate(t *testing.T) { w := s.compareVariants(templateVariants(test.name1), templateVariants(test.name2)) c.Assert(w, qt.Equals, test.expected) } - }) t.Run("indexOf", func(t *testing.T) { @@ -81,7 +77,6 @@ func TestShortcodesTemplate(t *testing.T) { c.Assert(s.indexOf([]string{"a", "b", "c"}), qt.Equals, 0) c.Assert(s.indexOf([]string{"a", "b", "d"}), qt.Equals, 1) c.Assert(s.indexOf([]string{"a", "b", "x"}), qt.Equals, -1) - }) t.Run("Name", func(t *testing.T) { @@ -92,6 +87,5 @@ func TestShortcodesTemplate(t *testing.T) { c.Assert(templateBaseName(templateShortcode, "shortcodes/test/foo.html"), qt.Equals, "test/foo.html") c.Assert(true, qt.Equals, true) - }) } diff --git a/tpl/tplimpl/template.go b/tpl/tplimpl/template.go index e3a4ce090..eb91ab837 100644 --- a/tpl/tplimpl/template.go +++ b/tpl/tplimpl/template.go @@ -167,7 +167,6 @@ func newTemplateExec(d *deps.Deps) (*templateExec, error) { if d.WithTemplate != nil { if err := d.WithTemplate(e); err != nil { return nil, err - } } @@ -246,7 +245,6 @@ func (t *templateExec) MarkReady() error { }) return err - } type templateHandler struct { @@ -345,7 +343,6 @@ func (t *templateHandler) LookupVariant(name string, variants tpl.TemplateVarian more := len(s.variants) > 1 return sv.ts, true, more - } // LookupVariants returns all variants of name, nil if none found. @@ -362,11 +359,9 @@ func (t *templateHandler) LookupVariants(name string) []tpl.Template { } return variants - } func (t *templateHandler) HasTemplate(name string) bool { - if _, found := t.baseof[name]; found { return true } @@ -501,7 +496,6 @@ func (t *templateHandler) addFileContext(templ tpl.Template, inerr error) error err, _ := checkFilename(ts.baseInfo, inerr) return err - } func (t *templateHandler) addShortcodeVariant(ts *templateState) { @@ -584,7 +578,6 @@ func (t *templateHandler) addTemplateFile(name, path string) error { t.applyTemplateTransformers(t.main, templ) return nil - } func (t *templateHandler) addTemplateTo(info templateInfo, to *templateNamespace) (*templateState, error) { @@ -716,7 +709,6 @@ func (t *templateHandler) loadTemplates() error { } return nil - } func (t *templateHandler) nameIsText(name string) (string, bool) { @@ -763,7 +755,6 @@ func (t *templateHandler) extractPartials(templ tpl.Template) error { } return nil - } func (t *templateHandler) postTransform() error { @@ -874,7 +865,6 @@ func (t *templateNamespace) newTemplateLookup(in *templateState) func(name strin return newTemplateState(templ, templateInfo{name: templ.Name()}) } return nil - } } @@ -933,7 +923,6 @@ func (t *templateState) isText() bool { func isText(templ tpl.Template) bool { _, isText := templ.(*texttemplate.Template) return isText - } type templateStateMap struct { @@ -1003,7 +992,6 @@ func removeLeadingBOM(s string) string { } return s - } // resolves _internal/shortcodes/param.html => param.html etc. @@ -1015,7 +1003,6 @@ func templateBaseName(typ templateType, name string) string { default: panic("not implemented") } - } func unwrap(templ tpl.Template) tpl.Template { @@ -1041,5 +1028,4 @@ func templates(in tpl.Template) []tpl.Template { } return templs - } diff --git a/tpl/tplimpl/template_ast_transformers.go b/tpl/tplimpl/template_ast_transformers.go index 015cf72af..de9b5424f 100644 --- a/tpl/tplimpl/template_ast_transformers.go +++ b/tpl/tplimpl/template_ast_transformers.go @@ -73,7 +73,6 @@ func (c templateContext) getIfNotVisited(name string) *templateState { func newTemplateContext( t *templateState, lookupFn func(name string) *templateState) *templateContext { - return &templateContext{ t: t, lookupFn: lookupFn, @@ -86,7 +85,6 @@ func newTemplateContext( func applyTemplateTransformers( t *templateState, lookupFn func(name string) *templateState) (*templateContext, error) { - if t == nil { return nil, errors.New("expected template, but none provided") } @@ -117,9 +115,7 @@ const ( partialReturnWrapperTempl = `{{ $_hugo_dot := $ }}{{ $ := .Arg }}{{ with .Arg }}{{ $_hugo_dot.Set ("PLACEHOLDER") }}{{ end }}` ) -var ( - partialReturnWrapper *parse.ListNode -) +var partialReturnWrapper *parse.ListNode func init() { templ, err := texttemplate.New("").Parse(partialReturnWrapperTempl) @@ -127,7 +123,6 @@ func init() { panic(err) } partialReturnWrapper = templ.Tree.Root - } func (c *templateContext) wrapInPartialReturnWrapper(n *parse.ListNode) *parse.ListNode { @@ -142,7 +137,6 @@ func (c *templateContext) wrapInPartialReturnWrapper(n *parse.ListNode) *parse.L withNode.List.Nodes = append(n.Nodes, retn) return wrapper - } // applyTransformations do 2 things: @@ -275,7 +269,6 @@ func (c *templateContext) collectInner(n *parse.CommandNode) { break } } - } var partialRe = regexp.MustCompile(`^partial(Cached)?$|^partials\.Include(Cached)?$`) @@ -330,7 +323,6 @@ func (c *templateContext) collectReturnNode(n *parse.CommandNode) bool { c.returnNode.Args = c.returnNode.Args[1:] return false - } func findTemplateIn(name string, in tpl.Template) (tpl.Template, bool) { @@ -345,5 +337,4 @@ func findTemplateIn(name string, in tpl.Template) (tpl.Template, bool) { return templ, true } return nil, false - } diff --git a/tpl/tplimpl/template_ast_transformers_test.go b/tpl/tplimpl/template_ast_transformers_test.go index b38446235..56d970b23 100644 --- a/tpl/tplimpl/template_ast_transformers_test.go +++ b/tpl/tplimpl/template_ast_transformers_test.go @@ -44,7 +44,6 @@ func TestTransformRecursiveTemplate(t *testing.T) { newTestTemplateLookup(ts), ) ctx.applyTransformations(templ.Tree.Root) - } func newTestTemplate(templ tpl.Template) *templateState { @@ -78,7 +77,6 @@ func newTestTemplateLookup(in *templateState) func(name string) *templateState { } func TestCollectInfo(t *testing.T) { - configStr := `{ "version": 42 }` tests := []struct { @@ -114,11 +112,9 @@ func TestCollectInfo(t *testing.T) { c.Assert(ctx.t.parseInfo, qt.DeepEquals, test.expected) }) } - } func TestPartialReturn(t *testing.T) { - tests := []struct { name string tplString string @@ -159,8 +155,6 @@ func TestPartialReturn(t *testing.T) { // Just check that it doesn't fail in this test. We have functional tests // in hugoblib. c.Assert(err, qt.IsNil) - }) } - } diff --git a/tpl/tplimpl/template_funcs.go b/tpl/tplimpl/template_funcs.go index 25ace365d..4b3abaada 100644 --- a/tpl/tplimpl/template_funcs.go +++ b/tpl/tplimpl/template_funcs.go @@ -60,8 +60,10 @@ import ( _ "github.com/gohugoio/hugo/tpl/urls" ) -var _ texttemplate.ExecHelper = (*templateExecHelper)(nil) -var zero reflect.Value +var ( + _ texttemplate.ExecHelper = (*templateExecHelper)(nil) + zero reflect.Value +) type templateExecHelper struct { running bool // whether we're in server mode. @@ -145,7 +147,6 @@ func newTemplateExecuter(d *deps.Deps) (texttemplate.Executer, map[string]reflec } func createFuncMap(d *deps.Deps) map[string]interface{} { - funcMap := template.FuncMap{} // Merge the namespace funcs @@ -172,5 +173,4 @@ func createFuncMap(d *deps.Deps) map[string]interface{} { } return funcMap - } diff --git a/tpl/tplimpl/template_funcs_test.go b/tpl/tplimpl/template_funcs_test.go index 852b63930..c142dd672 100644 --- a/tpl/tplimpl/template_funcs_test.go +++ b/tpl/tplimpl/template_funcs_test.go @@ -40,9 +40,7 @@ import ( "github.com/spf13/viper" ) -var ( - logger = loggers.NewErrorLogger() -) +var logger = loggers.NewErrorLogger() func newTestConfig() config.Provider { v := viper.New() @@ -188,7 +186,6 @@ func TestPartialCached(t *testing.T) { t.Fatalf("cache mismatch") } } - } func BenchmarkPartial(b *testing.B) { diff --git a/tpl/tplimpl/template_info_test.go b/tpl/tplimpl/template_info_test.go index 1324b458e..db74c29a8 100644 --- a/tpl/tplimpl/template_info_test.go +++ b/tpl/tplimpl/template_info_test.go @@ -38,7 +38,6 @@ func TestTemplateInfoShortcode(t *testing.T) { tti, ok := tt.(tpl.Info) c.Assert(ok, qt.Equals, true) c.Assert(tti.ParseInfo().IsInner, qt.Equals, true) - } // TODO(bep) move and use in other places @@ -55,5 +54,4 @@ func newD(c *qt.C) *deps.Deps { provider.Update(d) return d - } diff --git a/tpl/transform/init.go b/tpl/transform/init.go index 62cb0a9c3..9e57c07f6 100644 --- a/tpl/transform/init.go +++ b/tpl/transform/init.go @@ -46,13 +46,16 @@ func init() { [][2]string{ { `{{ htmlEscape "Cathal Garvey & The Sunshine Band <[email protected]>" | safeHTML}}`, - `Cathal Garvey & The Sunshine Band <[email protected]>`}, + `Cathal Garvey & The Sunshine Band <[email protected]>`, + }, { `{{ htmlEscape "Cathal Garvey & The Sunshine Band <[email protected]>"}}`, - `Cathal Garvey &amp; The Sunshine Band &lt;[email protected]&gt;`}, + `Cathal Garvey &amp; The Sunshine Band &lt;[email protected]&gt;`, + }, { `{{ htmlEscape "Cathal Garvey & The Sunshine Band <[email protected]>" | htmlUnescape | safeHTML }}`, - `Cathal Garvey & The Sunshine Band <[email protected]>`}, + `Cathal Garvey & The Sunshine Band <[email protected]>`, + }, }, ) @@ -61,16 +64,20 @@ func init() { [][2]string{ { `{{ htmlUnescape "Cathal Garvey & The Sunshine Band <[email protected]>" | safeHTML}}`, - `Cathal Garvey & The Sunshine Band <[email protected]>`}, + `Cathal Garvey & The Sunshine Band <[email protected]>`, + }, { `{{"Cathal Garvey &amp; The Sunshine Band &lt;[email protected]&gt;" | htmlUnescape | htmlUnescape | safeHTML}}`, - `Cathal Garvey & The Sunshine Band <[email protected]>`}, + `Cathal Garvey & The Sunshine Band <[email protected]>`, + }, { `{{"Cathal Garvey &amp; The Sunshine Band &lt;[email protected]&gt;" | htmlUnescape | htmlUnescape }}`, - `Cathal Garvey & The Sunshine Band <[email protected]>`}, + `Cathal Garvey & The Sunshine Band <[email protected]>`, + }, { `{{ htmlUnescape "Cathal Garvey & The Sunshine Band <[email protected]>" | htmlEscape | safeHTML }}`, - `Cathal Garvey & The Sunshine Band <[email protected]>`}, + `Cathal Garvey & The Sunshine Band <[email protected]>`, + }, }, ) @@ -104,7 +111,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/transform/remarshal_test.go b/tpl/transform/remarshal_test.go index daf99fdb4..eb5f4253c 100644 --- a/tpl/transform/remarshal_test.go +++ b/tpl/transform/remarshal_test.go @@ -107,7 +107,6 @@ title: Test Metadata } } - } func TestRemarshalComments(t *testing.T) { @@ -168,7 +167,6 @@ func TestTestRemarshalError(t *testing.T) { _, err = ns.Remarshal("json", "asdf") c.Assert(err, qt.Not(qt.IsNil)) - } func TestTestRemarshalMapInput(t *testing.T) { diff --git a/tpl/transform/transform.go b/tpl/transform/transform.go index b168d2a50..82756ed97 100644 --- a/tpl/transform/transform.go +++ b/tpl/transform/transform.go @@ -98,7 +98,6 @@ func (ns *Namespace) Markdownify(s interface{}) (template.HTML, error) { } b, err := ns.deps.ContentSpec.RenderMarkdown([]byte(ss)) - if err != nil { return "", err } diff --git a/tpl/transform/transform_test.go b/tpl/transform/transform_test.go index b3f4206ff..b98d82d27 100644 --- a/tpl/transform/transform_test.go +++ b/tpl/transform/transform_test.go @@ -15,7 +15,6 @@ package transform import ( "html/template" - "testing" "github.com/gohugoio/hugo/common/loggers" @@ -206,7 +205,6 @@ And then some. c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, template.HTML( "<p>#First</p>\n<p>This is some <em>bold</em> text.</p>\n<h2 id=\"second\">Second</h2>\n<p>This is some more text.</p>\n<p>And then some.</p>\n")) - } func TestPlainify(t *testing.T) { diff --git a/tpl/transform/unmarshal.go b/tpl/transform/unmarshal.go index b606c870a..aa84ca1f8 100644 --- a/tpl/transform/unmarshal.go +++ b/tpl/transform/unmarshal.go @@ -39,7 +39,7 @@ func (ns *Namespace) Unmarshal(args ...interface{}) (interface{}, error) { } var data interface{} - var decoder = metadecoders.Default + decoder := metadecoders.Default if len(args) == 1 { data = args[0] diff --git a/tpl/transform/unmarshal_test.go b/tpl/transform/unmarshal_test.go index 183bdefd5..ec81c316a 100644 --- a/tpl/transform/unmarshal_test.go +++ b/tpl/transform/unmarshal_test.go @@ -79,7 +79,6 @@ func (t testContentResource) Key() string { } func TestUnmarshal(t *testing.T) { - v := viper.New() ns := New(newDeps(v)) c := qt.New(t) @@ -120,21 +119,17 @@ func TestUnmarshal(t *testing.T) { }}, {testContentResource{key: "r1", content: `a;b;c`, mime: media.CSVType}, map[string]interface{}{"delimiter": ";"}, func(r [][]string) { c.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) - }}, {"a,b,c", nil, func(r [][]string) { c.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) - }}, {"a;b;c", map[string]interface{}{"delimiter": ";"}, func(r [][]string) { c.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) - }}, {testContentResource{key: "r1", content: ` % This is a comment a;b;c`, mime: media.CSVType}, map[string]interface{}{"DElimiter": ";", "Comment": "%"}, func(r [][]string) { c.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) - }}, // errors {"thisisnotavaliddataformat", nil, false}, diff --git a/tpl/urls/init.go b/tpl/urls/init.go index debaaabf9..0abe0d125 100644 --- a/tpl/urls/init.go +++ b/tpl/urls/init.go @@ -67,7 +67,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/urls/urls.go b/tpl/urls/urls.go index ee0e55501..652256f44 100644 --- a/tpl/urls/urls.go +++ b/tpl/urls/urls.go @@ -17,9 +17,7 @@ package urls import ( "errors" "fmt" - "html/template" - "net/url" "github.com/gohugoio/hugo/common/urls" diff --git a/transform/livereloadinject/livereloadinject.go b/transform/livereloadinject/livereloadinject.go index cc80d046e..32ed55f63 100644 --- a/transform/livereloadinject/livereloadinject.go +++ b/transform/livereloadinject/livereloadinject.go @@ -30,19 +30,18 @@ type tag struct { } var tags = []tag{ - tag{markup: []byte("<head>"), appendScript: true}, - tag{markup: []byte("<HEAD>"), appendScript: true}, - tag{markup: []byte("</body>")}, - tag{markup: []byte("</BODY>")}, + {markup: []byte("<head>"), appendScript: true}, + {markup: []byte("<HEAD>"), appendScript: true}, + {markup: []byte("</body>")}, + {markup: []byte("</BODY>")}, } // New creates a function that can be used // to inject a script tag for the livereload JavaScript in a HTML document. func New(baseURL url.URL) transform.Transformer { - return func(ft transform.FromTo) error { b := ft.From().Bytes() - var idx = -1 + idx := -1 var match tag // We used to insert the livereload script right before the closing body. // This does not work when combined with tools such as Turbolinks. diff --git a/transform/livereloadinject/livereloadinject_test.go b/transform/livereloadinject/livereloadinject_test.go index 50fbb8b92..b2ec4483a 100644 --- a/transform/livereloadinject/livereloadinject_test.go +++ b/transform/livereloadinject/livereloadinject_test.go @@ -61,5 +61,4 @@ func TestLiveReloadInject(t *testing.T) { c.Run("No match", func(c *qt.C) { c.Assert(apply("<h1>No match</h1>"), qt.Equals, "<h1>No match</h1>") }) - } diff --git a/transform/metainject/hugogenerator.go b/transform/metainject/hugogenerator.go index 5f3a8f63b..20f05145b 100644 --- a/transform/metainject/hugogenerator.go +++ b/transform/metainject/hugogenerator.go @@ -23,8 +23,10 @@ import ( "github.com/gohugoio/hugo/transform" ) -var metaTagsCheck = regexp.MustCompile(`(?i)<meta\s+name=['|"]?generator['|"]?`) -var hugoGeneratorTag = fmt.Sprintf(`<meta name="generator" content="Hugo %s" />`, hugo.CurrentVersion) +var ( + metaTagsCheck = regexp.MustCompile(`(?i)<meta\s+name=['|"]?generator['|"]?`) + hugoGeneratorTag = fmt.Sprintf(`<meta name="generator" content="Hugo %s" />`, hugo.CurrentVersion) +) // HugoGenerator injects a meta generator tag for Hugo if none present. func HugoGenerator(ft transform.FromTo) error { @@ -51,5 +53,4 @@ func HugoGenerator(ft transform.FromTo) error { } return nil - } diff --git a/transform/metainject/hugogenerator_test.go b/transform/metainject/hugogenerator_test.go index ffb4c1425..1d6d7c4b9 100644 --- a/transform/metainject/hugogenerator_test.go +++ b/transform/metainject/hugogenerator_test.go @@ -57,5 +57,4 @@ func TestHugoGeneratorInject(t *testing.T) { t.Errorf("[%d] Expected \n%q got \n%q", i, this.expect, out.String()) } } - } diff --git a/transform/urlreplacers/absurlreplacer.go b/transform/urlreplacers/absurlreplacer.go index 7bac716fb..a875e6fa8 100644 --- a/transform/urlreplacers/absurlreplacer.go +++ b/transform/urlreplacers/absurlreplacer.go @@ -131,7 +131,6 @@ func (l *absurllexer) posAfterURL(q []byte) int { return bytes.IndexFunc(l.content[l.pos:], func(r rune) bool { return r == '>' || unicode.IsSpace(r) }) - } // handle URLs in srcset. @@ -188,7 +187,6 @@ func checkCandidateSrcset(l *absurllexer) { l.pos += len(section) l.start = l.pos - } // main loop @@ -231,12 +229,12 @@ func (l *absurllexer) replace() { } func doReplace(path string, ct transform.FromTo, quotes [][]byte) { - lexer := &absurllexer{ content: ct.From().Bytes(), w: ct.To(), path: []byte(path), - quotes: quotes} + quotes: quotes, + } lexer.replace() } @@ -249,7 +247,8 @@ type absURLReplacer struct { func newAbsURLReplacer() *absURLReplacer { return &absURLReplacer{ htmlQuotes: [][]byte{[]byte("\""), []byte("'")}, - xmlQuotes: [][]byte{[]byte("""), []byte("'")}} + xmlQuotes: [][]byte{[]byte("""), []byte("'")}, + } } func (au *absURLReplacer) replaceInHTML(path string, ct transform.FromTo) { diff --git a/transform/urlreplacers/absurlreplacer_test.go b/transform/urlreplacers/absurlreplacer_test.go index 8e8fdc561..f4aa8b8ae 100644 --- a/transform/urlreplacers/absurlreplacer_test.go +++ b/transform/urlreplacers/absurlreplacer_test.go @@ -116,7 +116,8 @@ var ( srcsetXMLTests = []test{ {srcsetXMLBasic, srcsetXMLBasicCorrect}, {srcsetXMLSingleQuote, srcsetXMLSingleQuoteCorrect}, - {srcsetXMLVariations, srcsetXMLVariationsCorrect}} + {srcsetXMLVariations, srcsetXMLVariationsCorrect}, + } relurlTests = []test{{relPathVariations, relPathVariationsCorrect}} ) @@ -152,7 +153,6 @@ func TestAbsURL(t *testing.T) { tr := transform.New(NewAbsURLTransformer(testBaseURL)) apply(t.Errorf, tr, absURLTests) - } func TestAbsURLUnqoted(t *testing.T) { @@ -174,7 +174,6 @@ func TestRelativeURL(t *testing.T) { tr := transform.New(NewAbsURLTransformer(helpers.GetDottedRelativePath(filepath.FromSlash("/post/sub/")))) applyWithPath(t.Errorf, tr, relurlTests) - } func TestAbsURLSrcSet(t *testing.T) { |