ref: b5f39d23b86f9cb83c51da9fe4abb4c19c01c3b7
parent: 3011f36c27ecde309325e6c75ca377f4f87fa97a
author: Bjørn Erik Pedersen <[email protected]>
date: Sun Mar 24 06:11:16 EDT 2019
all: Apply staticcheck recommendations
--- a/cache/filecache/filecache.go
+++ b/cache/filecache/filecache.go
@@ -274,7 +274,7 @@
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
--- a/common/math/math.go
+++ b/common/math/math.go
@@ -46,7 +46,7 @@
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 @@
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 @@
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 @@
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 @@
} 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")
}
}
--- a/create/content.go
+++ b/create/content.go
@@ -142,6 +142,9 @@
}
out, err := targetFs.Create(targetFilename)
+ if err != nil {
+ return err
+ }
_, err = io.Copy(out, in)
if err != nil {
--- a/helpers/content.go
+++ b/helpers/content.go
@@ -147,10 +147,8 @@
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 @@
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)
--- a/helpers/emoji_test.go
+++ b/helpers/emoji_test.go
@@ -80,7 +80,7 @@
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
}
--- a/helpers/general.go
+++ b/helpers/general.go
@@ -57,7 +57,7 @@
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 @@
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 @@
switch name {
case "baseUrl":
name = "baseURL"
- break
case "uglyUrls":
name = "uglyURLs"
- break
}
return pflag.NormalizedName(name)
}
--- a/helpers/path.go
+++ b/helpers/path.go
@@ -29,6 +29,7 @@
"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 @@
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 @@
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 @@
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,8 +400,6 @@
}
-var numInPathRe = regexp.MustCompile("\\.(\\d+)\\.")
-
// FindCWD returns the current working directory from where the Hugo
// executable is run.
func FindCWD() (string, error) {
@@ -411,7 +406,7 @@
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 @@
// 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 @@
}
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 {
--- a/helpers/path_test.go
+++ b/helpers/path_test.go
@@ -171,7 +171,7 @@
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 @@
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 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 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 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 deleteTempDir(d string) {
- err := os.RemoveAll(d)
- if err != nil {
- // now what?
- }
+ _ = os.RemoveAll(d)
}
func TestExists(t *testing.T) {
--- a/helpers/pygments.go
+++ b/helpers/pygments.go
@@ -153,7 +153,7 @@
return code, err
}
- str := string(normalizeExternalHelperLineFeeds([]byte(out.String())))
+ str := string(normalizeExternalHelperLineFeeds(out.Bytes()))
str = h.injectCodeTag(str, lang)
@@ -235,10 +235,8 @@
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 == "" {
--- a/helpers/url.go
+++ b/helpers/url.go
@@ -142,7 +142,7 @@
}
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)
--- a/hugofs/language_composite_fs_test.go
+++ b/hugofs/language_composite_fs_test.go
@@ -70,6 +70,7 @@
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,
--- a/hugolib/filesystems/basefs.go
+++ b/hugolib/filesystems/basefs.go
@@ -17,7 +17,6 @@
import (
"errors"
- "io"
"os"
"path/filepath"
"strings"
@@ -758,23 +757,4 @@
}
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
- })
}
--- a/hugolib/page.go
+++ b/hugolib/page.go
@@ -20,12 +20,10 @@
"os"
"path"
"path/filepath"
- "runtime"
"sort"
"strings"
"github.com/bep/gitmap"
- "github.com/spf13/cast"
"github.com/gohugoio/hugo/helpers"
@@ -831,19 +829,6 @@
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)
@@ -860,10 +845,4 @@
}
return parts
-}
-
-func printStackTrace(length int) string {
- trace := make([]byte, length)
- runtime.Stack(trace, true)
- return string(trace)
}
--- a/hugolib/paths/baseURL.go
+++ b/hugolib/paths/baseURL.go
@@ -62,7 +62,7 @@
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
--- a/hugolib/site.go
+++ b/hugolib/site.go
@@ -67,9 +67,6 @@
"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:
//
--- a/hugolib/site_test.go
+++ b/hugolib/site_test.go
@@ -35,10 +35,6 @@
templateWithURLAbs = "<a href=\"/foobar.jpg\">Going</a>"
)
-func init() {
- testMode = true
-}
-
func TestRenderWithInvalidTemplate(t *testing.T) {
t.Parallel()
cfg, fs := newTestCfg()
--- a/hugolib/testhelpers_test.go
+++ b/hugolib/testhelpers_test.go
@@ -20,6 +20,7 @@
"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 @@
"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 @@
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 {
@@ -724,13 +740,5 @@
func parallel(t *testing.T) {
if parallelEnabled {
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))
}
}
--- a/minifiers/minifiers.go
+++ b/minifiers/minifiers.go
@@ -80,7 +80,7 @@
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)
--- a/parser/frontmatter.go
+++ b/parser/frontmatter.go
@@ -22,7 +22,7 @@
"github.com/BurntSushi/toml"
- "gopkg.in/yaml.v2"
+ yaml "gopkg.in/yaml.v2"
)
const (
@@ -62,7 +62,7 @@
return err
default:
- return errors.New("Unsupported Format provided")
+ return errors.New("unsupported Format provided")
}
}
--- a/parser/pageparser/pagelexer.go
+++ b/parser/pageparser/pagelexer.go
@@ -442,13 +442,6 @@
}
-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!
@@ -475,14 +468,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
--- a/releaser/releaser.go
+++ b/releaser/releaser.go
@@ -102,7 +102,7 @@
}
if exists {
- return fmt.Errorf("Tag %q already exists", tag)
+ return fmt.Errorf("tag %q already exists", tag)
}
var changeLogFromTag string
--- a/resources/image_test.go
+++ b/resources/image_test.go
@@ -171,21 +171,21 @@
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
--- a/source/fileInfo.go
+++ b/source/fileInfo.go
@@ -14,8 +14,6 @@
package source
import (
- "fmt"
- "io"
"os"
"path/filepath"
"strings"
@@ -23,8 +21,6 @@
"github.com/gohugoio/hugo/common/hugio"
- "github.com/spf13/afero"
-
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/helpers"
@@ -285,25 +281,4 @@
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
- })
}
--- a/source/filesystem_test.go
+++ b/source/filesystem_test.go
@@ -32,14 +32,6 @@
}
}
-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.
--- a/source/filesystem_unix_test.go
+++ /dev/null
@@ -1,28 +1,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/"},
-}
--- a/source/filesystem_windows_test.go
+++ /dev/null
@@ -1,28 +1,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\\"},
-}
--- a/source/sourceSpec.go
+++ b/source/sourceSpec.go
@@ -124,6 +124,10 @@
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
--- a/tpl/collections/reflect_helpers.go
+++ b/tpl/collections/reflect_helpers.go
@@ -38,7 +38,7 @@
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)
}
}
--- a/tpl/data/data.go
+++ b/tpl/data/data.go
@@ -58,18 +58,18 @@
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 @@
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")
--- a/tpl/data/resources.go
+++ b/tpl/data/resources.go
@@ -34,7 +34,7 @@
)
// 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 @@
}
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 @@
if !handled {
// This is cached content and should be correct.
- err, _ = unmarshal(b)
+ _, err = unmarshal(b)
}
return err
@@ -104,7 +104,7 @@
// 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)
@@ -111,7 +111,7 @@
if err != nil {
return err
}
- err, _ = unmarshal(b)
+ _, err = unmarshal(b)
return err
default:
return ns.getRemote(cache, unmarshal, req)
--- a/tpl/data/resources_test.go
+++ b/tpl/data/resources_test.go
@@ -114,9 +114,9 @@
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 @@
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)
--- a/tpl/math/math.go
+++ b/tpl/math/math.go
@@ -78,11 +78,11 @@
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
--- a/tpl/os/os.go
+++ b/tpl/os/os.go
@@ -73,7 +73,7 @@
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 @@
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
--- a/tpl/partials/partials.go
+++ b/tpl/partials/partials.go
@@ -107,7 +107,7 @@
}
- 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
--- a/tpl/template.go
+++ b/tpl/template.go
@@ -152,7 +152,7 @@
// 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 @@
// 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)
--- a/tpl/tplimpl/embedded/generate/generate.go
+++ b/tpl/tplimpl/embedded/generate/generate.go
@@ -39,6 +39,9 @@
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
--- a/tpl/transform/remarshal.go
+++ b/tpl/transform/remarshal.go
@@ -41,6 +41,9 @@
}
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 {
--- a/transform/chain_test.go
+++ b/transform/chain_test.go
@@ -58,8 +58,8 @@
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())
}
}
--- a/transform/livereloadinject/livereloadinject_test.go
+++ b/transform/livereloadinject/livereloadinject_test.go
@@ -35,7 +35,7 @@
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())
}
}
--- a/transform/urlreplacers/absurlreplacer.go
+++ b/transform/urlreplacers/absurlreplacer.go
@@ -37,8 +37,6 @@
quotes [][]byte
}
-type stateFunc func(*absurllexer) stateFunc
-
type prefix struct {
disabled bool
b []byte
@@ -52,11 +50,6 @@
{b: []byte("action="), f: checkCandidateBase},
{b: []byte("srcset="), f: checkCandidateSrcset},
}
-}
-
-type absURLMatcher struct {
- match []byte
- quote []byte
}
func (l *absurllexer) emit() {
--- a/transform/urlreplacers/absurlreplacer_test.go
+++ b/transform/urlreplacers/absurlreplacer_test.go
@@ -41,7 +41,6 @@
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