all: Apply staticcheck recommendations
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Sun, 24 Mar 2019 09:11:16 +0000 (10:11 +0100)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Sun, 24 Mar 2019 15:14:51 +0000 (16:14 +0100)
41 files changed:
cache/filecache/filecache.go
common/math/math.go
create/content.go
helpers/content.go
helpers/emoji_test.go
helpers/general.go
helpers/path.go
helpers/path_test.go
helpers/pygments.go
helpers/url.go
hugofs/language_composite_fs_test.go
hugolib/filesystems/basefs.go
hugolib/page.go
hugolib/paths/baseURL.go
hugolib/site.go
hugolib/site_test.go
hugolib/testhelpers_test.go
minifiers/minifiers.go
parser/frontmatter.go
parser/pageparser/pagelexer.go
releaser/releaser.go
resources/image_test.go
source/fileInfo.go
source/filesystem_test.go
source/filesystem_unix_test.go [deleted file]
source/filesystem_windows_test.go [deleted file]
source/sourceSpec.go
tpl/collections/reflect_helpers.go
tpl/data/data.go
tpl/data/resources.go
tpl/data/resources_test.go
tpl/math/math.go
tpl/os/os.go
tpl/partials/partials.go
tpl/template.go
tpl/tplimpl/embedded/generate/generate.go
tpl/transform/remarshal.go
transform/chain_test.go
transform/livereloadinject/livereloadinject_test.go
transform/urlreplacers/absurlreplacer.go
transform/urlreplacers/absurlreplacer_test.go

index d4e3f5d6a4188641cbb0834de726a5453b1d1e3f..6ad417117e0ec957372f075ef2dba75cffa0394f 100644 (file)
@@ -274,7 +274,7 @@ func (c *Cache) isExpired(modTime time.Time) bool {
        if c.maxAge < 0 {
                return false
        }
-       return c.maxAge == 0 || time.Now().Sub(modTime) > c.maxAge
+       return c.maxAge == 0 || time.Since(modTime) > c.maxAge
 }
 
 // For testing
index 3c5ef1f9d74c54cdc7b5c21f377cbe677dd7e5ed..cd06379aa50b56734389bd3c06cef26a9ec9165c 100644 (file)
@@ -46,7 +46,7 @@ func DoArithmetic(a, b interface{}, op rune) (interface{}, error) {
                                bu = 0
                        }
                default:
-                       return nil, errors.New("Can't apply the operator to the values")
+                       return nil, errors.New("can't apply the operator to the values")
                }
        case reflect.Float32, reflect.Float64:
                af = av.Float()
@@ -58,7 +58,7 @@ func DoArithmetic(a, b interface{}, op rune) (interface{}, error) {
                case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
                        bf = float64(bv.Uint()) // may overflow
                default:
-                       return nil, errors.New("Can't apply the operator to the values")
+                       return nil, errors.New("can't apply the operator to the values")
                }
        case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
                au = av.Uint()
@@ -79,7 +79,7 @@ func DoArithmetic(a, b interface{}, op rune) (interface{}, error) {
                case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
                        bu = bv.Uint()
                default:
-                       return nil, errors.New("Can't apply the operator to the values")
+                       return nil, errors.New("can't apply the operator to the values")
                }
        case reflect.String:
                as := av.String()
@@ -87,9 +87,9 @@ func DoArithmetic(a, b interface{}, op rune) (interface{}, error) {
                        bs := bv.String()
                        return as + bs, nil
                }
-               return nil, errors.New("Can't apply the operator to the values")
+               return nil, errors.New("can't apply the operator to the values")
        default:
-               return nil, errors.New("Can't apply the operator to the values")
+               return nil, errors.New("can't apply the operator to the values")
        }
 
        switch op {
@@ -128,8 +128,8 @@ func DoArithmetic(a, b interface{}, op rune) (interface{}, error) {
                } else if bu != 0 {
                        return au / bu, nil
                }
-               return nil, errors.New("Can't divide the value by 0")
+               return nil, errors.New("can't divide the value by 0")
        default:
-               return nil, errors.New("There is no such an operation")
+               return nil, errors.New("there is no such an operation")
        }
 }
index 264a0f3aca3c2cc36b83517ae98549ebe39090df..e48dfc078bb72b05255753c6941af40985da212f 100644 (file)
@@ -142,6 +142,9 @@ func newContentFromDir(
                }
 
                out, err := targetFs.Create(targetFilename)
+               if err != nil {
+                       return err
+               }
 
                _, err = io.Copy(out, in)
                if err != nil {
index bc19f6559470d9f4a31c2de3339c305dc3b04071..be5090c211dcec2a1415a15d8f80ac65c342cf2e 100644 (file)
@@ -147,10 +147,8 @@ func newBlackfriday(config map[string]interface{}) *BlackFriday {
                siteConfig[k] = v
        }
 
-       if config != nil {
-               for k, v := range config {
-                       siteConfig[k] = v
-               }
+       for k, v := range config {
+               siteConfig[k] = v
        }
 
        combinedConfig := &BlackFriday{}
@@ -755,7 +753,7 @@ func externallyRenderContent(ctx *RenderingContext, path string, args []string)
        err := cmd.Run()
        // Most external helpers exit w/ non-zero exit code only if severe, i.e.
        // halting errors occurred. -> log stderr output regardless of state of err
-       for _, item := range strings.Split(string(cmderr.Bytes()), "\n") {
+       for _, item := range strings.Split(cmderr.String(), "\n") {
                item := strings.TrimSpace(item)
                if item != "" {
                        jww.ERROR.Printf("%s: %s", ctx.DocumentName, item)
index f9189eb43cab3eeced3f2c5d9ae46679f97a99e5..89f9df5faadd5ad4b437792ef7a22b66b5a09f8e 100644 (file)
@@ -80,7 +80,7 @@ func BenchmarkEmojiKyokomiFprint(b *testing.B) {
                defer bufferpool.PutBuffer(buff)
                emoji.Fprint(buff, string(in))
 
-               bc := make([]byte, buff.Len(), buff.Len())
+               bc := make([]byte, buff.Len())
                copy(bc, buff.Bytes())
                return bc
        }
index 962b35bc6c448dfcb3e743d890146ce62536421c..3cf7ba8af675113d7ed8d481bf8a3d9550fa90e5 100644 (file)
@@ -57,7 +57,7 @@ func FindAvailablePort() (*net.TCPAddr, error) {
                if a, ok := addr.(*net.TCPAddr); ok {
                        return a, nil
                }
-               return nil, fmt.Errorf("Unable to obtain a valid tcp port. %v", addr)
+               return nil, fmt.Errorf("unable to obtain a valid tcp port: %v", addr)
        }
        return nil, err
 }
@@ -128,7 +128,7 @@ func ReaderToBytes(lines io.Reader) []byte {
 
        b.ReadFrom(lines)
 
-       bc := make([]byte, b.Len(), b.Len())
+       bc := make([]byte, b.Len())
        copy(bc, b.Bytes())
        return bc
 }
@@ -417,10 +417,8 @@ func NormalizeHugoFlags(f *pflag.FlagSet, name string) pflag.NormalizedName {
        switch name {
        case "baseUrl":
                name = "baseURL"
-               break
        case "uglyUrls":
                name = "uglyURLs"
-               break
        }
        return pflag.NormalizedName(name)
 }
index de2c9b0a04f9def2db174c80f450e069f9db051e..36bd3269bf819ce49a0f5bb57ac35955a67c805e 100644 (file)
@@ -29,6 +29,7 @@ import (
        "github.com/gohugoio/hugo/common/hugio"
        _errors "github.com/pkg/errors"
        "github.com/spf13/afero"
+       "golang.org/x/text/runes"
        "golang.org/x/text/transform"
        "golang.org/x/text/unicode/norm"
 )
@@ -155,7 +156,7 @@ func (p *PathSpec) UnicodeSanitize(s string) string {
 
        if p.RemovePathAccents {
                // remove accents - see https://blog.golang.org/normalization
-               t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
+               t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
                result, _, _ = transform.String(t, string(target))
        } else {
                result = string(target)
@@ -164,10 +165,6 @@ func (p *PathSpec) UnicodeSanitize(s string) string {
        return result
 }
 
-func isMn(r rune) bool {
-       return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
-}
-
 // ReplaceExtension takes a path and an extension, strips the old extension
 // and returns the path with the new extension.
 func ReplaceExtension(path string, newExt string) string {
@@ -208,7 +205,7 @@ func makePathRelative(inPath string, possibleDirectories ...string) (string, err
                        return strings.TrimPrefix(inPath, currentPath), nil
                }
        }
-       return inPath, errors.New("Can't extract relative path, unknown prefix")
+       return inPath, errors.New("can't extract relative path, unknown prefix")
 }
 
 // Should be good enough for Hugo.
@@ -403,15 +400,13 @@ func ExtractRootPaths(paths []string) []string {
 
 }
 
-var numInPathRe = regexp.MustCompile("\\.(\\d+)\\.")
-
 // 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)
+               return "", fmt.Errorf("can't get absolute path for executable: %v", err)
        }
 
        path := filepath.Dir(serverFile)
@@ -437,7 +432,7 @@ func SymbolicWalk(fs afero.Fs, root string, walker filepath.WalkFunc) error {
 
        // Sanity check
        if root != "" && len(root) < 4 {
-               return errors.New("Path is too short")
+               return errors.New("path is too short")
        }
 
        // Handle the root first
@@ -448,7 +443,7 @@ func SymbolicWalk(fs afero.Fs, root string, walker filepath.WalkFunc) error {
        }
 
        if !fileInfo.IsDir() {
-               return fmt.Errorf("Cannot walk regular file %s", root)
+               return fmt.Errorf("cannot walk regular file %s", root)
        }
 
        if err := walker(realPath, fileInfo, err); err != nil && err != filepath.SkipDir {
index c249a519dfe3c6909933b68888993372507d74da..98291936c1aae34f2ce35ca3de4b5fd6955e28fd 100644 (file)
@@ -171,7 +171,7 @@ func TestGetRealPath(t *testing.T) {
                t.Skip("Skip TestGetRealPath as os.Symlink needs administrator rights on Windows")
        }
 
-       d1, err := ioutil.TempDir("", "d1")
+       d1, _ := ioutil.TempDir("", "d1")
        defer os.Remove(d1)
        fs := afero.NewOsFs()
 
@@ -418,6 +418,7 @@ func createNonZeroSizedFileInTempDir() (*os.File, error) {
        f, err := createZeroSizedFileInTempDir()
        if err != nil {
                // no file ??
+               return nil, err
        }
        byteString := []byte("byteString")
        err = ioutil.WriteFile(f.Name(), byteString, 0644)
@@ -430,10 +431,7 @@ func createNonZeroSizedFileInTempDir() (*os.File, error) {
 }
 
 func deleteFileInTempDir(f *os.File) {
-       err := os.Remove(f.Name())
-       if err != nil {
-               // now what?
-       }
+       _ = os.Remove(f.Name())
 }
 
 func createEmptyTempDir() (string, error) {
@@ -449,7 +447,7 @@ func createEmptyTempDir() (string, error) {
 func createTempDirWithZeroLengthFiles() (string, error) {
        d, dirErr := createEmptyTempDir()
        if dirErr != nil {
-               //now what?
+               return "", dirErr
        }
        filePrefix := "_path_test_"
        _, fileErr := ioutil.TempFile(d, filePrefix) // dir is os.TempDir()
@@ -467,7 +465,7 @@ func createTempDirWithZeroLengthFiles() (string, error) {
 func createTempDirWithNonZeroLengthFiles() (string, error) {
        d, dirErr := createEmptyTempDir()
        if dirErr != nil {
-               //now what?
+               return "", dirErr
        }
        filePrefix := "_path_test_"
        f, fileErr := ioutil.TempFile(d, filePrefix) // dir is os.TempDir()
@@ -494,10 +492,7 @@ func createTempDirWithNonZeroLengthFiles() (string, error) {
 }
 
 func deleteTempDir(d string) {
-       err := os.RemoveAll(d)
-       if err != nil {
-               // now what?
-       }
+       _ = os.RemoveAll(d)
 }
 
 func TestExists(t *testing.T) {
index 64c5b3ea8ed2502df6bb597f048c8396128ee877..0fe1e75920019e94b608a15a2109e54110e2b36e 100644 (file)
@@ -153,7 +153,7 @@ func (h highlighters) pygmentsHighlight(code, lang, optsStr string) (string, err
                return code, err
        }
 
-       str := string(normalizeExternalHelperLineFeeds([]byte(out.String())))
+       str := string(normalizeExternalHelperLineFeeds(out.Bytes()))
 
        str = h.injectCodeTag(str, lang)
 
@@ -235,10 +235,8 @@ func parseOptions(defaults map[string]string, in string) (map[string]string, err
        in = strings.Trim(in, " ")
        opts := make(map[string]string)
 
-       if defaults != nil {
-               for k, v := range defaults {
-                       opts[k] = v
-               }
+       for k, v := range defaults {
+               opts[k] = v
        }
 
        if in == "" {
index a24f05b126c0d01dd11f6ef71e45dc04fe7cf0e3..6dbdea299e341982725c5bbf19c49270ca80c3cd 100644 (file)
@@ -142,7 +142,7 @@ func MakePermalink(host, plink string) *url.URL {
        }
 
        if p.Host != "" {
-               panic(fmt.Errorf("Can't make permalink from absolute link %q", plink))
+               panic(fmt.Errorf("can't make permalink from absolute link %q", plink))
        }
 
        base.Path = path.Join(base.Path, p.Path)
index bb4ddf7017b125059403a2b89891d130bd30e2f1..ab4e25fc0acebfd734b6f6318097a9e058e16038 100644 (file)
@@ -70,6 +70,7 @@ func TestCompositeLanguagFsTest(t *testing.T) {
        assert.NoError(err)
        defer f.Close()
        files, err := f.Readdir(-1)
+       assert.NoError(err)
        assert.Equal(4, len(files))
        expected := map[string]bool{
                filepath.FromSlash("/content/en/f1.txt"):    true,
index ee1c870d9fb3bc680a0ac9dea67c280d9b235929..d88141efd7d5b5bdc08aef34eae21df3b587cf6f 100644 (file)
@@ -17,7 +17,6 @@ package filesystems
 
 import (
        "errors"
-       "io"
        "os"
        "path/filepath"
        "strings"
@@ -759,22 +758,3 @@ func removeDuplicatesKeepRight(in []string) []string {
 
        return out
 }
-
-func printFs(fs afero.Fs, path string, w io.Writer) {
-       if fs == nil {
-               return
-       }
-       afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error {
-               if info != nil && !info.IsDir() {
-                       s := path
-                       if lang, ok := info.(hugofs.LanguageAnnouncer); ok {
-                               s = s + "\tLANG: " + lang.Lang()
-                       }
-                       if fp, ok := info.(hugofs.FilePather); ok {
-                               s = s + "\tRF: " + fp.Filename() + "\tBP: " + fp.BaseDir()
-                       }
-                       fmt.Fprintln(w, "    ", s)
-               }
-               return nil
-       })
-}
index 24d659fb17c7b46f974c8f3bd30d01c248ded075..576342cfae6d6735acfb3402fc9a55975f917724 100644 (file)
@@ -20,12 +20,10 @@ import (
        "os"
        "path"
        "path/filepath"
-       "runtime"
        "sort"
        "strings"
 
        "github.com/bep/gitmap"
-       "github.com/spf13/cast"
 
        "github.com/gohugoio/hugo/helpers"
 
@@ -831,19 +829,6 @@ func (ps pageStatePages) findPagePosByFilnamePrefix(prefix string) int {
        return currPos
 }
 
-func content(c resource.ContentProvider) string {
-       cc, err := c.Content()
-       if err != nil {
-               panic(err)
-       }
-
-       ccs, err := cast.ToStringE(cc)
-       if err != nil {
-               panic(err)
-       }
-       return ccs
-}
-
 func (s *Site) sectionsFromFile(fi source.File) []string {
        dirname := fi.Dir()
        dirname = strings.Trim(dirname, helpers.FilePathSeparator)
@@ -861,9 +846,3 @@ func (s *Site) sectionsFromFile(fi source.File) []string {
 
        return parts
 }
-
-func printStackTrace(length int) string {
-       trace := make([]byte, length)
-       runtime.Stack(trace, true)
-       return string(trace)
-}
index de36c863640757630b3710e9bf73dae5cf77e2d7..a3c7e9d272eb8ef07650aacef79f70c7faf794b4 100644 (file)
@@ -62,7 +62,7 @@ func (b BaseURL) WithProtocol(protocol string) (string, error) {
        if isFullProtocol && u.Opaque != "" {
                u.Opaque = "//" + u.Opaque
        } else if isOpaqueProtocol && u.Opaque == "" {
-               return "", fmt.Errorf("Cannot determine BaseURL for protocol %q", protocol)
+               return "", fmt.Errorf("cannot determine BaseURL for protocol %q", protocol)
        }
 
        return u.String(), nil
index be70db5ee0d46bd61ca5b8b48935e9f7f71880cc..145ae2d49b27501f57e6dcbe68a68fb635d99160 100644 (file)
@@ -67,9 +67,6 @@ import (
        "github.com/spf13/viper"
 )
 
-// used to indicate if run as a test.
-var testMode bool
-
 // Site contains all the information relevant for constructing a static
 // site.  The basic flow of information is as follows:
 //
index 98fe1ff4f8c2554d723819ea3ed4ee6e44ad076e..21575072dcc349bdad81069080497a50e8a999a7 100644 (file)
@@ -35,10 +35,6 @@ const (
        templateWithURLAbs  = "<a href=\"/foobar.jpg\">Going</a>"
 )
 
-func init() {
-       testMode = true
-}
-
 func TestRenderWithInvalidTemplate(t *testing.T) {
        t.Parallel()
        cfg, fs := newTestCfg()
index 7de2280c7ac6b10a1241400a66323b6a47e21244..0a8fbe7f5a355f11ad0633060541ac77a94288f6 100644 (file)
@@ -20,6 +20,7 @@ import (
        "github.com/gohugoio/hugo/resources/page"
        "github.com/sanity-io/litter"
        "github.com/spf13/afero"
+       "github.com/spf13/cast"
 
        "github.com/gohugoio/hugo/helpers"
        "github.com/gohugoio/hugo/tpl"
@@ -27,6 +28,8 @@ import (
 
        "os"
 
+       "github.com/gohugoio/hugo/resources/resource"
+
        "github.com/gohugoio/hugo/common/loggers"
        "github.com/gohugoio/hugo/hugofs"
        "github.com/stretchr/testify/assert"
@@ -672,6 +675,19 @@ func getPage(in page.Page, ref string) page.Page {
        return p
 }
 
+func content(c resource.ContentProvider) string {
+       cc, err := c.Content()
+       if err != nil {
+               panic(err)
+       }
+
+       ccs, err := cast.ToStringE(cc)
+       if err != nil {
+               panic(err)
+       }
+       return ccs
+}
+
 func dumpPages(pages ...page.Page) {
        fmt.Println("---------")
        for i, p := range pages {
@@ -726,11 +742,3 @@ func parallel(t *testing.T) {
                t.Parallel()
        }
 }
-
-// Useful to debug nilpointers/panics in templates.
-// Put "defer recoverStack()" in top of the failing function.
-func recoverStack() {
-       if r := recover(); r != nil {
-               fmt.Println(printStackTrace(1000))
-       }
-}
index db2251b68852f0d81f499dfe9fdd7587a07461ef..9533ebb6917ef168414022a92600619ae670f8fb 100644 (file)
@@ -80,7 +80,7 @@ func New(mediaTypes media.Types, outputFormats output.Formats) Client {
        addMinifier(m, mediaTypes, "css", cssMin)
        addMinifierFunc(m, mediaTypes, "js", js.Minify)
        m.AddFuncRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"), js.Minify)
-       m.AddFuncRegexp(regexp.MustCompile("^(application|text)/(x-|ld\\+)?json$"), json.Minify)
+       m.AddFuncRegexp(regexp.MustCompile(`^(application|text)/(x-|ld\+)?json$`), json.Minify)
        addMinifierFunc(m, mediaTypes, "json", json.Minify)
        addMinifierFunc(m, mediaTypes, "svg", svg.Minify)
        addMinifierFunc(m, mediaTypes, "xml", xml.Minify)
index ab1bc4d55c2247361c1a92fc0e66f4822b2bf75f..4965d3fe88954de00737c57615be2a058a81b1ba 100644 (file)
@@ -22,7 +22,7 @@ import (
 
        "github.com/BurntSushi/toml"
 
-       "gopkg.in/yaml.v2"
+       yaml "gopkg.in/yaml.v2"
 )
 
 const (
@@ -62,7 +62,7 @@ func InterfaceToConfig(in interface{}, format metadecoders.Format, w io.Writer)
                return err
 
        default:
-               return errors.New("Unsupported Format provided")
+               return errors.New("unsupported Format provided")
        }
 }
 
index 11723f279928a01a8465b3bb0c5ec87228b1ca41..d010c8152016da3d01019e76edcd4be444deed6c 100644 (file)
@@ -442,13 +442,6 @@ func lexMainSection(l *pageLexer) stateFunc {
 
 }
 
-func (l *pageLexer) posFirstNonWhiteSpace() int {
-       f := func(c rune) bool {
-               return !unicode.IsSpace(c)
-       }
-       return bytes.IndexFunc(l.input[l.pos:], f)
-}
-
 func lexDone(l *pageLexer) stateFunc {
 
        // Done!
@@ -477,14 +470,6 @@ func (l *pageLexer) hasPrefix(prefix []byte) bool {
        return bytes.HasPrefix(l.input[l.pos:], prefix)
 }
 
-func (l *pageLexer) hasPrefixByte(prefix byte) bool {
-       b := l.input[l.pos:]
-       if len(b) == 0 {
-               return false
-       }
-       return b[0] == prefix
-}
-
 // helper functions
 
 // returns the min index >= 0
index 0c0765a719aeed5bcf15a67d27c09fad7aac1ffc..01c1d5219611ffbd2736eb8b1b734c86241420f4 100644 (file)
@@ -102,7 +102,7 @@ func (r *ReleaseHandler) Run() error {
        }
 
        if exists {
-               return fmt.Errorf("Tag %q already exists", tag)
+               return fmt.Errorf("tag %q already exists", tag)
        }
 
        var changeLogFromTag string
index ffa48229670133a4e9fad7c7297e5e6172917a30..fd1eb5410db8b9b9c4d160a332bcbaa0fbac95c1 100644 (file)
@@ -171,21 +171,21 @@ func TestImageTransformConcurrent(t *testing.T) {
                                for k := 0; k < 2; k++ {
                                        r1, err := img.Resize(fmt.Sprintf("%dx", id-k))
                                        if err != nil {
-                                               t.Fatal(err)
+                                               t.Error(err)
                                        }
 
                                        if r1.Width() != id-k {
-                                               t.Fatalf("Width: %d:%d", r1.Width(), j)
+                                               t.Errorf("Width: %d:%d", r1.Width(), j)
                                        }
 
                                        r2, err := r1.Resize(fmt.Sprintf("%dx", id-k-1))
                                        if err != nil {
-                                               t.Fatal(err)
+                                               t.Error(err)
                                        }
 
                                        _, err = r2.decodeSource()
                                        if err != nil {
-                                               t.Fatal("Err decode:", err)
+                                               t.Error("Err decode:", err)
                                        }
 
                                        img = r1
index 752f104e86960c069a9c06d3aa68358ac09a6fba..3f262fb5ece0faf93a8f6e46f185bcc2ce3af2d6 100644 (file)
@@ -14,8 +14,6 @@
 package source
 
 import (
-       "fmt"
-       "io"
        "os"
        "path/filepath"
        "strings"
@@ -23,8 +21,6 @@ import (
 
        "github.com/gohugoio/hugo/common/hugio"
 
-       "github.com/spf13/afero"
-
        "github.com/gohugoio/hugo/hugofs"
 
        "github.com/gohugoio/hugo/helpers"
@@ -286,24 +282,3 @@ func (sp *SourceSpec) NewFileInfo(baseDir, filename string, isLeafBundle bool, f
        return f
 
 }
-
-func printFs(fs afero.Fs, path string, w io.Writer) {
-       if fs == nil {
-               return
-       }
-       afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error {
-
-               if info != nil && !info.IsDir() {
-
-                       s := path
-                       if lang, ok := info.(hugofs.LanguageAnnouncer); ok {
-                               s = s + "\t" + lang.Lang()
-                       }
-                       if fp, ok := info.(hugofs.FilePather); ok {
-                               s = s + "\t" + fp.Filename()
-                       }
-                       fmt.Fprintln(w, "    ", s)
-               }
-               return nil
-       })
-}
index 2c1eeb171f5e6d206d7262f9c0fe9d803eed796b..8c8e30413f28134dd0b6a64bb0f40cdbb83184eb 100644 (file)
@@ -32,14 +32,6 @@ func TestEmptySourceFilesystem(t *testing.T) {
        }
 }
 
-type TestPath struct {
-       filename string
-       logical  string
-       content  string
-       section  string
-       dir      string
-}
-
 func TestUnicodeNorm(t *testing.T) {
        if runtime.GOOS != "darwin" {
                // Normalization code is only for Mac OS, since it is not necessary for other OSes.
diff --git a/source/filesystem_unix_test.go b/source/filesystem_unix_test.go
deleted file mode 100644 (file)
index 560d824..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2015 The Hugo Authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// +build linux darwin !windows
-
-package source
-
-//
-// NOTE, any changes here need to be reflected in filesystem_windows_test.go
-//
-var platformBase = "/base/"
-var platformPaths = []TestPath{
-       {"foobar", "foobar", "aaa", "", ""},
-       {"b/1file", "1file", "aaa", "b", "b/"},
-       {"c/d/2file", "2file", "aaa", "c", "c/d/"},
-       {"/base/e/f/3file", "3file", "aaa", "e", "e/f/"},
-       {"section/foo.rss", "foo.rss", "aaa", "section", "section/"},
-}
diff --git a/source/filesystem_windows_test.go b/source/filesystem_windows_test.go
deleted file mode 100644 (file)
index 4662c5f..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2015 The Hugo Authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package source
-
-//
-// NOTE, any changes here need to be reflected in filesystem_linux_test.go
-//
-
-// Note the case of the volume drive.  It must be the same in all examples.
-var platformBase = "C:\\foo\\"
-var platformPaths = []TestPath{
-       {"foobar", "foobar", "aaa", "", ""},
-       {"b\\1file", "1file", "aaa", "b", "b\\"},
-       {"c\\d\\2file", "2file", "aaa", "c", "c\\d\\"},
-       {"C:\\foo\\e\\f\\3file", "3file", "aaa", "e", "e\\f\\"}, // note volume case is equal to platformBase
-       {"section\\foo.rss", "foo.rss", "aaa", "section", "section\\"},
-}
index 13aac4592c6cfe71afb3f34567b2bafde4b5829f..9731a8d8d4a973626387ae45e46cc8442404c04e 100644 (file)
@@ -124,6 +124,10 @@ func (s *SourceSpec) IsRegularSourceFile(filename string) (bool, error) {
 
        if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
                link, err := filepath.EvalSymlinks(filename)
+               if err != nil {
+                       return false, err
+               }
+
                fi, err = helpers.LstatIfPossible(s.SourceFs, link)
                if err != nil {
                        return false, err
index fca65481f30062bb36e1cbb8915a5d6794f56ac6..69425fcb06a89e6138213191636b4b78297ca11c 100644 (file)
@@ -38,7 +38,7 @@ func numberToFloat(v reflect.Value) (float64, error) {
        case kind == reflect.Interface:
                return numberToFloat(v.Elem())
        default:
-               return 0, fmt.Errorf("Invalid kind %s in numberToFloat", kind)
+               return 0, fmt.Errorf("invalid kind %s in numberToFloat", kind)
        }
 }
 
index 81fde9d706568cca0c8234a485483610f91c566f..15f03929435c55947715d2dd60f9e0ff431c768a 100644 (file)
@@ -58,18 +58,18 @@ func (ns *Namespace) GetCSV(sep string, urlParts ...string) (d [][]string, err e
        url := strings.Join(urlParts, "")
        cache := ns.cacheGetCSV
 
-       unmarshal := func(b []byte) (error, bool) {
+       unmarshal := func(b []byte) (bool, error) {
                if !bytes.Contains(b, []byte(sep)) {
-                       return _errors.Errorf("cannot find separator %s in CSV for %s", sep, url), false
+                       return false, _errors.Errorf("cannot find separator %s in CSV for %s", sep, url)
                }
 
                if d, err = parseCSV(b, sep); err != nil {
                        err = _errors.Wrapf(err, "failed to parse CSV file %s", url)
 
-                       return err, true
+                       return true, err
                }
 
-               return nil, false
+               return false, nil
        }
 
        var req *http.Request
@@ -103,12 +103,12 @@ func (ns *Namespace) GetJSON(urlParts ...string) (interface{}, error) {
                return nil, _errors.Wrapf(err, "Failed to create request for getJSON resource %s", url)
        }
 
-       unmarshal := func(b []byte) (error, bool) {
+       unmarshal := func(b []byte) (bool, error) {
                err := json.Unmarshal(b, &v)
                if err != nil {
-                       return err, true
+                       return true, err
                }
-               return nil, false
+               return false, nil
        }
 
        req.Header.Add("Accept", "application/json")
index 8b246a662e9c4c11339100b0fe9f4ff9f89beafc..7de440ca65fbb6c717661de9b2a57098bb98afb8 100644 (file)
@@ -34,7 +34,7 @@ var (
 )
 
 // getRemote loads the content of a remote file. This method is thread safe.
-func (ns *Namespace) getRemote(cache *filecache.Cache, unmarshal func([]byte) (error, bool), req *http.Request) error {
+func (ns *Namespace) getRemote(cache *filecache.Cache, unmarshal func([]byte) (bool, error), req *http.Request) error {
        url := req.URL.String()
        id := helpers.MD5String(url)
        var handled bool
@@ -63,7 +63,7 @@ func (ns *Namespace) getRemote(cache *filecache.Cache, unmarshal func([]byte) (e
                        }
                        res.Body.Close()
 
-                       err, retry = unmarshal(b)
+                       retry, err = unmarshal(b)
 
                        if err == nil {
                                // Return it so it can be cached.
@@ -85,7 +85,7 @@ func (ns *Namespace) getRemote(cache *filecache.Cache, unmarshal func([]byte) (e
 
        if !handled {
                // This is cached content and should be correct.
-               err, _ = unmarshal(b)
+               _, err = unmarshal(b)
        }
 
        return err
@@ -104,14 +104,14 @@ func getLocal(url string, fs afero.Fs, cfg config.Provider) ([]byte, error) {
 
 // getResource loads the content of a local or remote file and returns its content and the
 // cache ID used, if relevant.
-func (ns *Namespace) getResource(cache *filecache.Cache, unmarshal func(b []byte) (error, bool), req *http.Request) error {
+func (ns *Namespace) getResource(cache *filecache.Cache, unmarshal func(b []byte) (bool, error), req *http.Request) error {
        switch req.URL.Scheme {
        case "":
                b, err := getLocal(req.URL.String(), ns.deps.Fs.Source, ns.deps.Cfg)
                if err != nil {
                        return err
                }
-               err, _ = unmarshal(b)
+               _, err = unmarshal(b)
                return err
        default:
                return ns.getRemote(cache, unmarshal, req)
index d1091b23f290fe14c7c2ccbc7ac53fdbf4ef4901..a42232f940b350726af2beab9d7cc73b12ca0b46 100644 (file)
@@ -114,9 +114,9 @@ func TestScpGetRemote(t *testing.T) {
                ns.client = cl
 
                var c []byte
-               f := func(b []byte) (error, bool) {
+               f := func(b []byte) (bool, error) {
                        c = b
-                       return nil, false
+                       return false, nil
                }
 
                err = ns.getRemote(cache, f, req)
@@ -158,15 +158,15 @@ func TestScpGetRemoteParallel(t *testing.T) {
                                defer wg.Done()
                                for j := 0; j < 10; j++ {
                                        var c []byte
-                                       f := func(b []byte) (error, bool) {
+                                       f := func(b []byte) (bool, error) {
                                                c = b
-                                               return nil, false
+                                               return false, nil
                                        }
                                        err := ns.getRemote(ns.cacheGetJSON, f, req)
 
                                        assert.NoError(t, err)
                                        if string(content) != string(c) {
-                                               t.Fatalf("expected\n%q\ngot\n%q", content, c)
+                                               t.Errorf("expected\n%q\ngot\n%q", content, c)
                                        }
 
                                        time.Sleep(23 * time.Millisecond)
index 0bc813dced59eb34d3e0edc96a33311ca3ccda67..08be42b47d8d544519ede8a56e1eaf00d854dade 100644 (file)
@@ -78,11 +78,11 @@ func (ns *Namespace) Mod(a, b interface{}) (int64, error) {
        bi, errb := cast.ToInt64E(b)
 
        if erra != nil || errb != nil {
-               return 0, errors.New("Modulo operator can't be used with non integer value")
+               return 0, errors.New("modulo operator can't be used with non integer value")
        }
 
        if bi == 0 {
-               return 0, errors.New("The number can't be divided by zero at modulo operation")
+               return 0, errors.New("the number can't be divided by zero at modulo operation")
        }
 
        return ai % bi, nil
index cc4a42d5d34ca81da003aa3f5c8ec77dbe72094a..2dab5c4906ad72ab983d7925bba127389aa2b079 100644 (file)
@@ -73,7 +73,7 @@ func readFile(fs afero.Fs, filename string) (string, error) {
 
        if info, err := fs.Stat(filename); err == nil {
                if info.Size() > 1000000 {
-                       return "", fmt.Errorf("File %q is too big", filename)
+                       return "", fmt.Errorf("file %q is too big", filename)
                }
        } else {
                return "", err
@@ -108,7 +108,7 @@ func (ns *Namespace) ReadDir(i interface{}) ([]_os.FileInfo, error) {
 
        list, err := afero.ReadDir(ns.deps.Fs.WorkingDir, path)
        if err != nil {
-               return nil, fmt.Errorf("Failed to read Directory %s with error message %s", path, err)
+               return nil, fmt.Errorf("failed to read directory %q: %s", path, err)
        }
 
        return list, nil
index ece16276d6c8a4b9f6dd1c3cbacd67fa2a48a38b..1e8a84954bc7d81fb028f7eee584ba3f9832f9df 100644 (file)
@@ -107,7 +107,7 @@ func (ns *Namespace) Include(name string, contextList ...interface{}) (interface
 
        }
 
-       return "", fmt.Errorf("Partial %q not found", name)
+       return "", fmt.Errorf("partial %q not found", name)
 }
 
 // IncludeCached executes and caches partial templates.  An optional variant
index 07152166a2c08b763c9d1b342d83bd93f7c07030..01f79c407b2ff728ff0f8d38b152488e3e32e25f 100644 (file)
@@ -152,7 +152,7 @@ func (t *TemplateAdapter) Execute(w io.Writer, data interface{}) (execErr error)
                // Panics in templates are a little bit too common (nil pointers etc.)
                // See https://github.com/gohugoio/hugo/issues/5327
                if r := recover(); r != nil {
-                       execErr = t.addFileContext(t.Name(), fmt.Errorf(`panic in Execute: %s. See "https://github.com/gohugoio/hugo/issues/5327" for the reason why we cannot provide a better error message for this.`, r))
+                       execErr = t.addFileContext(t.Name(), fmt.Errorf(`panic in Execute: %s. See "https://github.com/gohugoio/hugo/issues/5327" for the reason why we cannot provide a better error message for this`, r))
                }
        }()
 
@@ -174,7 +174,7 @@ func (t *TemplateAdapter) TemplateInfo() Info {
 
 // The identifiers may be truncated in the log, e.g.
 // "executing "main" at <$scaled.SRelPermalin...>: can't evaluate field SRelPermalink in type *resource.Image"
-var identifiersRe = regexp.MustCompile("at \\<(.*?)(\\.{3})?\\>:")
+var identifiersRe = regexp.MustCompile(`at \<(.*?)(\.{3})?\>:`)
 
 func (t *TemplateAdapter) extractIdentifiers(line string) []string {
        m := identifiersRe.FindAllStringSubmatch(line, -1)
index a48e00756ac023d88d7b2a099bc2bc6898599d97..df4de47993962844bf9fe81a1ccc84259291327f 100644 (file)
@@ -39,6 +39,9 @@ func main() {
        var nameValues []string
 
        err = filepath.Walk(temlatePath, func(path string, info os.FileInfo, err error) error {
+               if err != nil {
+                       return err
+               }
 
                if info.IsDir() {
                        return nil
index 62d826b437d35e6d5268487a27e0ac83937d0c20..182bd21d619a99b1b7dde3d3f93d2e248cdc6032 100644 (file)
@@ -41,6 +41,9 @@ func (ns *Namespace) Remarshal(format string, data interface{}) (string, error)
        }
 
        meta, err := metadecoders.Default.UnmarshalToMap([]byte(from), fromFormat)
+       if err != nil {
+               return "", err
+       }
 
        var result bytes.Buffer
        if err := parser.InterfaceToConfig(meta, mark, &result); err != nil {
index e3402429614c00e6b8fb806a04c48e2c4affccba..a8d59f9029c562a83aaadd2a7cc2c20a93ea5fc6 100644 (file)
@@ -58,8 +58,8 @@ func TestChaingMultipleTransformers(t *testing.T) {
 
        expected := "Test: f4r f3r f1r f2r f1r The End."
 
-       if string(out.Bytes()) != expected {
-               t.Errorf("Expected %s got %s", expected, string(out.Bytes()))
+       if out.String() != expected {
+               t.Errorf("Expected %s got %s", expected, out.String())
        }
 }
 
index 0e0f708d31077989448a4a14ee6ac955180f8fa8..1058244b4ea485392de2224bb2eecfd099fa5ab4 100644 (file)
@@ -35,7 +35,7 @@ func doTestLiveReloadInject(t *testing.T, bodyEndTag string) {
        tr.Apply(out, in)
 
        expected := fmt.Sprintf(`<script data-no-instant>document.write('<script src="/livereload.js?port=1313&mindelay=10"></' + 'script>')</script>%s`, bodyEndTag)
-       if string(out.Bytes()) != expected {
-               t.Errorf("Expected %s got %s", expected, string(out.Bytes()))
+       if out.String() != expected {
+               t.Errorf("Expected %s got %s", expected, out.String())
        }
 }
index 02083d9f5f8c972d760dbf837747cc33c4eca7c0..545df914af3830d29bfabd12e2264fec493b2b75 100644 (file)
@@ -37,8 +37,6 @@ type absurllexer struct {
        quotes [][]byte
 }
 
-type stateFunc func(*absurllexer) stateFunc
-
 type prefix struct {
        disabled bool
        b        []byte
@@ -54,11 +52,6 @@ func newPrefixState() []*prefix {
        }
 }
 
-type absURLMatcher struct {
-       match []byte
-       quote []byte
-}
-
 func (l *absurllexer) emit() {
        l.w.Write(l.content[l.start:l.pos])
        l.start = l.pos
index f7a5b16560da0ef7f306126c7f8656a5ce73d4fa..3c2dbf777901dcdc9cbd49a9df0832cec7282834 100644 (file)
@@ -41,7 +41,6 @@ const (
        replace1 = "No replacements."
        replace2 = "ᚠᛇᚻ ᛒᛦᚦ ᚠᚱᚩᚠᚢᚱ\nᚠᛁᚱᚪ ᚷᛖᚻᚹᛦᛚᚳᚢᛗ"
        replace3 = `End of file: src="/`
-       replace4 = `End of file: srcset="/`
        replace5 = `Srcsett with no closing quote: srcset="/img/small.jpg do be do be do.`
 
        // Issue: 816, schemaless links combined with others