Skip to content
Permalink
Browse files

all: Apply staticcheck recommendations

  • Loading branch information...
bep committed Mar 24, 2019
1 parent 3011f36 commit b5f39d23b86f9cb83c51da9fe4abb4c19c01c3b7
@@ -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
@@ -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,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 {
@@ -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")
}
}
@@ -142,6 +142,9 @@ func newContentFromDir(
}

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

_, err = io.Copy(out, in)
if err != nil {
@@ -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)
@@ -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
}
@@ -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)
}
@@ -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 {
@@ -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) {
@@ -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 == "" {
@@ -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)
@@ -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,
@@ -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
})
}
@@ -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)
}
@@ -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
@@ -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:
//
Oops, something went wrong.

0 comments on commit b5f39d2

Please sign in to comment.
You can’t perform that action at this time.