diff options
author | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2019-03-24 10:11:16 +0100 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2019-03-24 16:14:51 +0100 |
commit | b5f39d23b86f9cb83c51da9fe4abb4c19c01c3b7 (patch) | |
tree | cf23180dc07698391cf47c2fe525755417729020 | |
parent | 3011f36c27ecde309325e6c75ca377f4f87fa97a (diff) |
all: Apply staticcheck recommendations
41 files changed, 98 insertions, 252 deletions
diff --git a/cache/filecache/filecache.go b/cache/filecache/filecache.go index d4e3f5d6a..6ad417117 100644 --- a/cache/filecache/filecache.go +++ b/cache/filecache/filecache.go @@ -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 diff --git a/common/math/math.go b/common/math/math.go index 3c5ef1f9d..cd06379aa 100644 --- a/common/math/math.go +++ b/common/math/math.go @@ -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") } } diff --git a/create/content.go b/create/content.go index 264a0f3ac..e48dfc078 100644 --- a/create/content.go +++ b/create/content.go @@ -142,6 +142,9 @@ func newContentFromDir( } out, err := targetFs.Create(targetFilename) + if err != nil { + return err + } _, err = io.Copy(out, in) if err != nil { diff --git a/helpers/content.go b/helpers/content.go index bc19f6559..be5090c21 100644 --- a/helpers/content.go +++ b/helpers/content.go @@ -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) diff --git a/helpers/emoji_test.go b/helpers/emoji_test.go index f9189eb43..89f9df5fa 100644 --- a/helpers/emoji_test.go +++ b/helpers/emoji_test.go @@ -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 } diff --git a/helpers/general.go b/helpers/general.go index 962b35bc6..3cf7ba8af 100644 --- a/helpers/general.go +++ b/helpers/general.go @@ -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) } diff --git a/helpers/path.go b/helpers/path.go index de2c9b0a0..36bd3269b 100644 --- a/helpers/path.go +++ b/helpers/path.go @@ -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 { diff --git a/helpers/path_test.go b/helpers/path_test.go index c249a519d..98291936c 100644 --- a/helpers/path_test.go +++ b/helpers/path_test.go @@ -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) { diff --git a/helpers/pygments.go b/helpers/pygments.go index 64c5b3ea8..0fe1e7592 100644 --- a/helpers/pygments.go +++ b/helpers/pygments.go @@ -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 == "" { diff --git a/helpers/url.go b/helpers/url.go index a24f05b12..6dbdea299 100644 --- a/helpers/url.go +++ b/helpers/url.go @@ -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) diff --git a/hugofs/language_composite_fs_test.go b/hugofs/language_composite_fs_test.go index bb4ddf701..ab4e25fc0 100644 --- a/hugofs/language_composite_fs_test.go +++ b/hugofs/language_composite_fs_test.go @@ -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, diff --git a/hugolib/filesystems/basefs.go b/hugolib/filesystems/basefs.go index ee1c870d9..d88141efd 100644 --- a/hugolib/filesystems/basefs.go +++ b/hugolib/filesystems/basefs.go @@ -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 - }) -} diff --git a/hugolib/page.go b/hugolib/page.go index 24d659fb1..576342cfa 100644 --- a/hugolib/page.go +++ b/hugolib/page.go @@ -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) -} diff --git a/hugolib/paths/baseURL.go b/hugolib/paths/baseURL.go index de36c8636..a3c7e9d27 100644 --- a/hugolib/paths/baseURL.go +++ b/hugolib/paths/baseURL.go @@ -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 diff --git a/hugolib/site.go b/hugolib/site.go index be70db5ee..145ae2d49 100644 --- a/hugolib/site.go +++ b/hugolib/site.go @@ -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: // diff --git a/hugolib/site_test.go b/hugolib/site_test.go index 98fe1ff4f..21575072d 100644 --- a/hugolib/site_test.go +++ b/hugolib/site_test.go @@ -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() diff --git a/hugolib/testhelpers_test.go b/hugolib/testhelpers_test.go index 7de2280c7..0a8fbe7f5 100644 --- a/hugolib/testhelpers_test.go +++ b/hugolib/testhelpers_test.go @@ -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)) - } -} diff --git a/minifiers/minifiers.go b/minifiers/minifiers.go index db2251b68..9533ebb69 100644 --- a/minifiers/minifiers.go +++ b/minifiers/minifiers.go @@ -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) diff --git a/parser/frontmatter.go b/parser/frontmatter.go index ab1bc4d55..4965d3fe8 100644 --- a/parser/frontmatter.go +++ b/ |