Lint fixes

This commit is contained in:
Paul Tötterman
2020-10-19 13:40:52 +03:00
parent 3cec19ee62
commit 3d924a016b
65 changed files with 884 additions and 1083 deletions

View File

@@ -2,9 +2,10 @@ package utils
import (
"fmt"
"github.com/revel/cmd/logger"
"strconv"
"regexp"
"strconv"
"github.com/revel/cmd/logger"
)
type (
@@ -15,7 +16,7 @@ type (
}
)
// Returns a new builed error
// Returns a new builed error.
func NewBuildError(message string, args ...interface{}) (b *BuildError) {
Logger.Info(message, args...)
b = &BuildError{}
@@ -26,22 +27,23 @@ func NewBuildError(message string, args ...interface{}) (b *BuildError) {
return b
}
// Returns a new BuildError if err is not nil
// Returns a new BuildError if err is not nil.
func NewBuildIfError(err error, message string, args ...interface{}) (b error) {
if err != nil {
if berr, ok := err.(*BuildError); ok {
// This is already a build error so just append the args
berr.Args = append(berr.Args, args...)
return berr
} else {
args = append(args, "error", err.Error())
b = NewBuildError(message, args...)
}
args = append(args, "error", err.Error())
b = NewBuildError(message, args...)
}
return
}
// BuildError implements Error() string
// BuildError implements Error() string.
func (b *BuildError) Error() string {
return fmt.Sprint(b.Message, b.Args)
}
@@ -70,13 +72,12 @@ func NewCompileError(importPath, errorLink string, error error) *SourceError {
Logger.Error("Build errors", "errors", error)
}
// Read the source for the offending file.
var (
relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go"
absFilename = relFilename
line, _ = strconv.Atoi(string(errorMatch[2]))
description = string(errorMatch[4])
relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go"
absFilename = relFilename
line, _ = strconv.Atoi(string(errorMatch[2]))
description = string(errorMatch[4])
compileError = &SourceError{
SourceType: "Go code",
Title: "Go Compilation Error",
@@ -95,10 +96,10 @@ func NewCompileError(importPath, errorLink string, error error) *SourceError {
fileStr, err := ReadLines(absFilename)
if err != nil {
compileError.MetaError = absFilename + ": " + err.Error()
Logger.Info("Unable to readlines " + compileError.MetaError, "error", err)
Logger.Info("Unable to readlines "+compileError.MetaError, "error", err)
return compileError
}
compileError.SourceLines = fileStr
return compileError
}
}

View File

@@ -1,15 +1,15 @@
package utils
import (
"bytes"
"go/build"
"os"
"os/exec"
"strings"
"bytes"
"path/filepath"
"strings"
)
// Initialize the command based on the GO environment
// Initialize the command based on the GO environment.
func CmdInit(c *exec.Cmd, addGoPath bool, basePath string) {
c.Dir = basePath
// Dep does not like paths that are not real, convert all paths in go to real paths
@@ -33,4 +33,4 @@ func CmdInit(c *exec.Cmd, addGoPath bool, basePath string) {
}
c.Env = append(c.Env, e)
}
}
}

View File

@@ -6,7 +6,7 @@ import (
"strings"
)
// The error is a wrapper for the
// The error is a wrapper for the.
type (
SourceError struct {
SourceType string // The type of source that failed to build.
@@ -23,27 +23,28 @@ type (
IsError bool
}
)
// Return a new error object
// Return a new error object.
func NewError(source, title, path, description string) *SourceError {
return &SourceError{
SourceType:source,
Title:title,
Path:path,
Description:description,
SourceType: source,
Title: title,
Path: path,
Description: description,
}
}
// Creates a link based on the configuration setting "errors.link"
// Creates a link based on the configuration setting "errors.link".
func (e *SourceError) SetLink(errorLink string) {
errorLink = strings.Replace(errorLink, "{{Path}}", e.Path, -1)
errorLink = strings.Replace(errorLink, "{{Line}}", strconv.Itoa(e.Line), -1)
errorLink = strings.ReplaceAll(errorLink, "{{Path}}", e.Path)
errorLink = strings.ReplaceAll(errorLink, "{{Line}}", strconv.Itoa(e.Line))
e.Link = "<a href=" + errorLink + ">" + e.Path + ":" + strconv.Itoa(e.Line) + "</a>"
}
// Error method constructs a plaintext version of the error, taking
// account that fields are optionally set. Returns e.g. Compilation Error
// (in views/header.html:51): expected right delim in end; got "}"
// (in views/header.html:51): expected right delim in end; got "}".
func (e *SourceError) Error() string {
if e == nil {
panic("opps")
@@ -82,7 +83,7 @@ func (e *SourceError) ContextSource() []SourceLine {
end = len(e.SourceLines)
}
lines := make([]SourceLine, end - start)
lines := make([]SourceLine, end-start)
for i, src := range e.SourceLines[start:end] {
fileLine := start + i + 1
lines[i] = SourceLine{src, fileLine, fileLine == e.Line}

View File

@@ -4,14 +4,15 @@ import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"golang.org/x/tools/go/packages"
)
@@ -39,9 +40,8 @@ func ReadLines(filename string) ([]string, error) {
return strings.Split(string(dataBytes), "\n"), nil
}
// Copy file returns error
// Copy file returns error.
func CopyFile(destFilename, srcFilename string) (err error) {
destFile, err := os.Create(destFilename)
if err != nil {
return NewBuildIfError(err, "Failed to create file", "file", destFilename)
@@ -105,11 +105,11 @@ func GenerateTemplate(filename, templateSource string, args map[string]interface
return
}
// Given the target path and source path and data. A template
// Given the target path and source path and data. A template.
func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
tmpl, err := template.ParseFiles(srcPath)
if err != nil {
return NewBuildIfError(err, "Failed to parse template " + srcPath)
return NewBuildIfError(err, "Failed to parse template "+srcPath)
}
f, err := os.Create(destPath)
@@ -119,26 +119,26 @@ func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
err = tmpl.Execute(f, data)
if err != nil {
return NewBuildIfError(err, "Failed to Render template " + srcPath)
return NewBuildIfError(err, "Failed to Render template "+srcPath)
}
err = f.Close()
if err != nil {
return NewBuildIfError(err, "Failed to close file stream " + destPath)
return NewBuildIfError(err, "Failed to close file stream "+destPath)
}
return
}
// Given the target path and source path and data. A template
// Given the target path and source path and data. A template.
func RenderTemplateToStream(output io.Writer, srcPath []string, data interface{}) (err error) {
tmpl, err := template.ParseFiles(srcPath...)
if err != nil {
return NewBuildIfError(err, "Failed to parse template " + srcPath[0])
return NewBuildIfError(err, "Failed to parse template "+srcPath[0])
}
err = tmpl.Execute(output, data)
if err != nil {
return NewBuildIfError(err, "Failed to render template " + srcPath[0])
return NewBuildIfError(err, "Failed to render template "+srcPath[0])
}
return
}
@@ -148,7 +148,7 @@ func MustChmod(filename string, mode os.FileMode) {
PanicOnError(err, fmt.Sprintf("Failed to chmod %d %q", mode, filename))
}
// Called if panic
// Called if panic.
func PanicOnError(err error, msg string) {
if revErr, ok := err.(*SourceError); (ok && revErr != nil) || (!ok && err != nil) {
Logger.Panicf("Abort: %s: %s %s", msg, revErr, err)
@@ -181,15 +181,14 @@ func CopyDir(destDir, srcDir string, data map[string]interface{}) error {
if info.IsDir() {
err := os.MkdirAll(filepath.Join(destDir, relSrcPath), 0777)
if !os.IsExist(err) {
return NewBuildIfError(err, "Failed to create directory", "path", destDir + "/" + relSrcPath)
return NewBuildIfError(err, "Failed to create directory", "path", destDir+"/"+relSrcPath)
}
return nil
}
// If this file ends in ".template", render it as a template.
if strings.HasSuffix(relSrcPath, ".template") {
return RenderTemplate(destPath[:len(destPath) - len(".template")], srcPath, data)
return RenderTemplate(destPath[:len(destPath)-len(".template")], srcPath, data)
}
// Else, just copy it over.
@@ -198,13 +197,13 @@ func CopyDir(destDir, srcDir string, data map[string]interface{}) error {
})
}
// Shortcut to fsWalk
// Shortcut to fsWalk.
func Walk(root string, walkFn filepath.WalkFunc) error {
return fsWalk(root, root, walkFn)
}
// Walk the path tree using the function
// Every file found will call the function
// Every file found will call the function.
func fsWalk(fname string, linkName string, walkFn filepath.WalkFunc) error {
fsWalkFunc := func(path string, info os.FileInfo, err error) error {
if err != nil {
@@ -219,7 +218,7 @@ func fsWalk(fname string, linkName string, walkFn filepath.WalkFunc) error {
path = filepath.Join(linkName, name)
if err == nil && info.Mode() & os.ModeSymlink == os.ModeSymlink {
if err == nil && info.Mode()&os.ModeSymlink == os.ModeSymlink {
var symlinkPath string
symlinkPath, err = filepath.EvalSymlinks(path)
if err != nil {
@@ -244,7 +243,7 @@ func fsWalk(fname string, linkName string, walkFn filepath.WalkFunc) error {
return err
}
// Tar gz the folder
// Tar gz the folder.
func TarGzDir(destFilename, srcDir string) (name string, err error) {
zipFile, err := os.Create(destFilename)
if err != nil {
@@ -266,6 +265,10 @@ func TarGzDir(destFilename, srcDir string) (name string, err error) {
}()
err = fsWalk(srcDir, srcDir, func(srcPath string, info os.FileInfo, err error) error {
if err != nil {
Logger.Debugf("error in walkFn: %s", err)
}
if info.IsDir() {
return nil
}
@@ -300,7 +303,7 @@ func TarGzDir(destFilename, srcDir string) (name string, err error) {
return zipFile.Name(), err
}
// Return true if the file exists
// Return true if the file exists.
func Exists(filename string) bool {
_, err := os.Stat(filename)
return err == nil
@@ -324,7 +327,7 @@ func Empty(dirname string) bool {
return len(results) == 0
}
// Find the full source dir for the import path, uses the build.Default.GOPATH to search for the directory
// Find the full source dir for the import path, uses the build.Default.GOPATH to search for the directory.
func FindSrcPaths(appPath string, packageList []string, packageResolver func(pkgName string) error) (sourcePathsmap map[string]string, err error) {
sourcePathsmap, missingList, err := findSrcPaths(appPath, packageList)
if err != nil && packageResolver != nil || len(missingList) > 0 {
@@ -345,16 +348,18 @@ func FindSrcPaths(appPath string, packageList []string, packageResolver func(pkg
return
}
var NO_APP_FOUND = errors.New("No app found")
var NO_REVEL_FOUND = errors.New("No revel found")
var (
NO_APP_FOUND = errors.New("no app found")
NO_REVEL_FOUND = errors.New("no revel found")
)
// Find the full source dir for the import path, uses the build.Default.GOPATH to search for the directory
func findSrcPaths(appPath string, packagesList []string) (sourcePathsmap map[string]string, missingList[] string, err error) {
// Find the full source dir for the import path, uses the build.Default.GOPATH to search for the directory.
func findSrcPaths(appPath string, packagesList []string) (sourcePathsmap map[string]string, missingList []string, err error) {
// Use packages to fetch
// by not specifying env, we will use the default env
config := &packages.Config{
Mode: packages.NeedName | packages.NeedFiles,
Dir:appPath,
Dir: appPath,
}
sourcePathsmap = map[string]string{}
Logger.Infof("Environment path %s root %s config env %s", os.Getenv("GOPATH"), os.Getenv("GOROOT"), config.Env)
@@ -371,9 +376,8 @@ func findSrcPaths(appPath string, packagesList []string) (sourcePathsmap map[str
if pck.Errors != nil && len(pck.Errors) > 0 {
log.Error("Error ", "count", len(pck.Errors), "App Import Path", pck.ID, "filesystem path", pck.PkgPath, "errors", pck.Errors)
// continue
}
//a,_ := pck.MarshalJSON()
// a,_ := pck.MarshalJSON()
log.Info("Found ", "count", len(pck.GoFiles), "App Import Path", pck.ID, "apppath", appPath)
if len(pck.GoFiles) > 0 {
sourcePathsmap[packageName] = filepath.Dir(pck.GoFiles[0])

View File

@@ -2,10 +2,11 @@ package utils
import (
"fmt"
"github.com/revel/cmd/logger"
"github.com/revel/config"
"os"
"strings"
"github.com/revel/cmd/logger"
"github.com/revel/config"
)
var Logger = logger.New()
@@ -31,7 +32,7 @@ func InitLogger(basePath string, logLevel logger.LogLevel) {
}
// This function is to throw a panic that may be caught by the packger so it can perform the needed
// imports
// imports.
func Retry(format string, args ...interface{}) {
// Ensure the user's command prompt starts on the next line.
if !strings.HasSuffix(format, "\n") {

View File

@@ -1,6 +1,6 @@
package utils
// Return true if the target string is in the list
// Return true if the target string is in the list.
func ContainsString(list []string, target string) bool {
for _, el := range list {
if el == target {