Skip to content

Commit

Permalink
all: Apply staticcheck recommendations
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Mar 24, 2019
1 parent 3011f36 commit b5f39d2
Show file tree
Hide file tree
Showing 41 changed files with 98 additions and 252 deletions.
2 changes: 1 addition & 1 deletion cache/filecache/filecache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 7 additions & 7 deletions common/math/math.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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()
Expand All @@ -79,17 +79,17 @@ 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()
if bv.Kind() == reflect.String && op == '+' {
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 {
Expand Down Expand Up @@ -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")
}
}
3 changes: 3 additions & 0 deletions create/content.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ func newContentFromDir(
}

out, err := targetFs.Create(targetFilename)
if err != nil {
return err
}

_, err = io.Copy(out, in)
if err != nil {
Expand Down
8 changes: 3 additions & 5 deletions helpers/content.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion helpers/emoji_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
6 changes: 2 additions & 4 deletions helpers/general.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
}
Expand Down
17 changes: 6 additions & 11 deletions helpers/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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 {
Expand Down
17 changes: 6 additions & 11 deletions helpers/path_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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)
Expand All @@ -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) {
Expand All @@ -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()
Expand All @@ -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()
Expand All @@ -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) {
Expand Down
8 changes: 3 additions & 5 deletions helpers/pygments.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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 == "" {
Expand Down
2 changes: 1 addition & 1 deletion helpers/url.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions hugofs/language_composite_fs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
20 changes: 0 additions & 20 deletions hugolib/filesystems/basefs.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ package filesystems

import (
"errors"
"io"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -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
})
}
21 changes: 0 additions & 21 deletions hugolib/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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)
Expand All @@ -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)
}
2 changes: 1 addition & 1 deletion hugolib/paths/baseURL.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 0 additions & 3 deletions hugolib/site.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
//
Expand Down
Loading

0 comments on commit b5f39d2

Please sign in to comment.