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

@@ -11,12 +11,12 @@ import (
"io"
"os"
"os/exec"
"time"
"runtime"
"sync"
"time"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"runtime"
)
// App contains the configuration for running a Revel app. (Not for the app itself)
@@ -29,9 +29,9 @@ type App struct {
Paths *model.RevelContainer
}
// NewApp returns app instance with binary path in it
// NewApp returns app instance with binary path in it.
func NewApp(binPath string, paths *model.RevelContainer, packagePathMap map[string]string) *App {
return &App{BinaryPath: binPath, Paths: paths, Port: paths.HTTPPort, PackagePathMap:packagePathMap}
return &App{BinaryPath: binPath, Paths: paths, Port: paths.HTTPPort, PackagePathMap: packagePathMap}
}
// Cmd returns a command to run the app server using the current configuration.
@@ -51,7 +51,7 @@ type AppCmd struct {
*exec.Cmd
}
// NewAppCmd returns the AppCmd with parameters initialized for running app
// NewAppCmd returns the AppCmd with parameters initialized for running app.
func NewAppCmd(binPath string, port int, runMode string, paths *model.RevelContainer) AppCmd {
cmd := exec.Command(binPath,
fmt.Sprintf("-port=%d", port),
@@ -74,9 +74,9 @@ func (cmd AppCmd) Start(c *model.CommandConfig) error {
select {
case exitState := <-cmd.waitChan():
fmt.Println("Startup failure view previous messages, \n Proxy is listening :", c.Run.Port)
err := utils.NewError("", "Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState, "")
// TODO pretiffy command line output
// err.MetaError = listeningWriter.getLastOutput()
err := utils.NewError("", "Revel Run Error", "starting your application there was an exception. See terminal output, "+exitState, "")
// TODO pretiffy command line output
// err.MetaError = listeningWriter.getLastOutput()
return err
case <-time.After(60 * time.Second):
@@ -89,7 +89,6 @@ func (cmd AppCmd) Start(c *model.CommandConfig) error {
println("Revel proxy is listening, point your browser to :", c.Run.Port)
return nil
}
}
// Run the app server inline. Never returns.
@@ -103,11 +102,10 @@ func (cmd AppCmd) Run(c *model.CommandConfig) {
// Kill terminates the app server if it's running.
func (cmd AppCmd) Kill() {
if cmd.Cmd != nil && (cmd.ProcessState == nil || !cmd.ProcessState.Exited()) {
// Windows appears to send the kill to all threads, shutting down the
// server before this can, this check will ensure the process is still running
if _, err := os.FindProcess(int(cmd.Process.Pid)); err != nil {
if _, err := os.FindProcess(cmd.Process.Pid); err != nil {
// Server has already exited
utils.Logger.Info("Server not running revel server pid", "pid", cmd.Process.Pid)
return
@@ -149,14 +147,13 @@ func (cmd AppCmd) Kill() {
return
}
// Use a timer to ensure that the process exits
utils.Logger.Info("Waiting to exit")
select {
case <-ch:
return
case <-time.After(60 * time.Second):
// Kill the process
// Kill the process
utils.Logger.Error(
"Revel app failed to exit in 60 seconds - killing.",
"processid", cmd.Process.Pid,
@@ -193,7 +190,7 @@ type startupListeningWriter struct {
buffer *bytes.Buffer
}
// Writes to this output stream
// Writes to this output stream.
func (w *startupListeningWriter) Write(p []byte) (int, error) {
if w.notifyReady != nil && bytes.Contains(p, []byte("Revel engine is listening on")) {
w.notifyReady <- true
@@ -210,10 +207,3 @@ func (w *startupListeningWriter) Write(p []byte) (int, error) {
}
return w.dest.Write(p)
}
// Returns the cleaned output from the response
// TODO clean the response more
func (w *startupListeningWriter) getLastOutput() string {
return w.buffer.String()
}

View File

@@ -19,10 +19,9 @@ import (
"time"
"github.com/revel/cmd/model"
_ "github.com/revel/cmd/parser"
"github.com/revel/cmd/utils"
"github.com/revel/cmd/parser2"
"github.com/revel/cmd/parser"
"github.com/revel/cmd/parser2"
"github.com/revel/cmd/utils"
)
var importErrorPattern = regexp.MustCompile("cannot find package \"([^\"]+)\"")
@@ -32,9 +31,11 @@ type ByString []*model.TypeInfo
func (c ByString) Len() int {
return len(c)
}
func (c ByString) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
func (c ByString) Less(i, j int) bool {
return c[i].String() < c[j].String()
}
@@ -155,7 +156,8 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
"build",
"-ldflags", versionLinkerFlags,
"-tags", buildTags,
"-o", binName}
"-o", binName,
}
} else {
if !contains(c.BuildFlags, "build") {
flags = []string{"build"}
@@ -188,7 +190,7 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
}
buildCmd.Env = append(os.Environ(),
"GOPATH=" + gopath,
"GOPATH="+gopath,
)
}
utils.CmdInit(buildCmd, !c.Vendored, c.AppPath)
@@ -232,9 +234,7 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
// Success getting the import, attempt to build again.
}
// TODO remove this unreachable code and document it
utils.Logger.Fatal("Not reachable")
return nil, nil
// unreachable
}
// Try to define a version string for the compiled app
@@ -256,10 +256,9 @@ func getAppVersion(paths *model.RevelContainer) string {
if (err != nil && os.IsNotExist(err)) || !info.IsDir() {
return ""
}
gitCmd := exec.Command(gitPath, "--git-dir=" + gitDir, "--work-tree=" + paths.BasePath, "describe", "--always", "--dirty")
gitCmd := exec.Command(gitPath, "--git-dir="+gitDir, "--work-tree="+paths.BasePath, "describe", "--always", "--dirty")
utils.Logger.Info("Exec:", "args", gitCmd.Args)
output, err := gitCmd.Output()
if err != nil {
utils.Logger.Error("Cannot determine git repository version:", "error", err)
return ""
@@ -317,7 +316,6 @@ func cleanDir(paths *model.RevelContainer, dir string) {
// genSource renders the given template to produce source code, which it writes
// to the given directory and file.
func genSource(paths *model.RevelContainer, dir, filename, templateSource string, args map[string]interface{}) error {
return utils.GenerateTemplate(filepath.Join(paths.AppPath, dir, filename), templateSource, args)
}
@@ -353,17 +351,16 @@ func calcImportAliases(src *model.SourceInfo) map[string]string {
return aliases
}
// Adds an alias to the map of alias names
// Adds an alias to the map of alias names.
func addAlias(aliases map[string]string, importPath, pkgName string) {
alias, ok := aliases[importPath]
_, ok := aliases[importPath]
if ok {
return
}
alias = makePackageAlias(aliases, pkgName)
aliases[importPath] = alias
aliases[importPath] = makePackageAlias(aliases, pkgName)
}
// Generates a package alias
// Generates a package alias.
func makePackageAlias(aliases map[string]string, pkgName string) string {
i := 0
alias := pkgName
@@ -374,7 +371,7 @@ func makePackageAlias(aliases map[string]string, pkgName string) string {
return alias
}
// Returns true if this value is in the map
// Returns true if this value is in the map.
func containsValue(m map[string]string, val string) bool {
for _, v := range m {
if v == val {
@@ -421,13 +418,12 @@ func newCompileError(paths *model.RevelContainer, output []byte) *utils.SourceEr
return newPath
}
// Read the source for the offending file.
var (
relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go"
absFilename = findInPaths(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 = findInPaths(relFilename)
line, _ = strconv.Atoi(string(errorMatch[2]))
description = string(errorMatch[4])
compileError = &utils.SourceError{
SourceType: "Go code",
Title: "Go Compilation Error",
@@ -446,7 +442,7 @@ func newCompileError(paths *model.RevelContainer, output []byte) *utils.SourceEr
fileStr, err := utils.ReadLines(absFilename)
if err != nil {
compileError.MetaError = absFilename + ": " + err.Error()
utils.Logger.Info("Unable to readlines " + compileError.MetaError, "error", err)
utils.Logger.Info("Unable to readlines "+compileError.MetaError, "error", err)
return compileError
}
@@ -454,7 +450,7 @@ func newCompileError(paths *model.RevelContainer, output []byte) *utils.SourceEr
return compileError
}
// RevelMainTemplate template for app/tmp/run/run.go
// RevelMainTemplate template for app/tmp/run/run.go.
const RevelRunTemplate = `// GENERATED CODE - DO NOT EDIT
// This file is the run file for Revel.
// It registers all the controllers and provides details for the Revel server engine to
@@ -509,6 +505,7 @@ func Register() {
}
}
`
const RevelMainTemplate = `// GENERATED CODE - DO NOT EDIT
// This file is the main file for Revel.
// It registers all the controllers and provides details for the Revel server engine to
@@ -536,7 +533,7 @@ func main() {
}
`
// RevelRoutesTemplate template for app/conf/routes
// RevelRoutesTemplate template for app/conf/routes.
const RevelRoutesTemplate = `// GENERATED CODE - DO NOT EDIT
// This file provides a way of creating URL's based on all the actions
// found in all the controllers.

View File

@@ -15,10 +15,12 @@ package harness
import (
"crypto/tls"
"encoding/json"
"fmt"
"time"
"go/build"
"html/template"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
@@ -27,15 +29,13 @@ import (
"os/signal"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"github.com/revel/cmd/watcher"
"html/template"
"io/ioutil"
"sync"
"encoding/json"
)
var (
@@ -57,7 +57,6 @@ type Harness struct {
paths *model.RevelContainer // The Revel container
config *model.CommandConfig // The configuration
runMode string // The runmode the harness is running in
isError bool // True if harness is in error state
ranOnce bool // True app compiled once
}
@@ -90,7 +89,7 @@ func (h *Harness) renderError(iw http.ResponseWriter, ir *http.Request, err erro
target := []string{seekViewOnPath("500.html"), seekViewOnPath("500-dev.html")}
if !utils.Exists(target[0]) {
fmt.Fprintf(iw, "Target template not found not found %s<br />\n", target[0])
fmt.Fprintf(iw, "An error ocurred %s", err.Error())
fmt.Fprintf(iw, "An error occurred %s", err.Error())
return
}
var revelError *utils.SourceError
@@ -156,11 +155,11 @@ func (h *Harness) ServeHTTP(w http.ResponseWriter, r *http.Request) {
func NewHarness(c *model.CommandConfig, paths *model.RevelContainer, runMode string, noProxy bool) *Harness {
// Get a template loader to render errors.
// Prefer the app's views/errors directory, and fall back to the stock error pages.
//revel.MainTemplateLoader = revel.NewTemplateLoader(
// revel.MainTemplateLoader = revel.NewTemplateLoader(
// []string{filepath.Join(revel.RevelPath, "templates")})
//if err := revel.MainTemplateLoader.Refresh(); err != nil {
// if err := revel.MainTemplateLoader.Refresh(); err != nil {
// revel.RevelLog.Error("Template loader error", "error", err)
//}
// }
addr := paths.HTTPAddr
port := paths.Config.IntDefault("harness.port", 0)
@@ -203,19 +202,19 @@ func NewHarness(c *model.CommandConfig, paths *model.RevelContainer, runMode str
}
// Refresh method rebuilds the Revel application and run it on the given port.
// called by the watcher
// called by the watcher.
func (h *Harness) Refresh() (err *utils.SourceError) {
t := time.Now();
t := time.Now()
fmt.Println("Changed detected, recompiling")
err = h.refresh()
if err!=nil && !h.ranOnce && h.useProxy {
if err != nil && !h.ranOnce && h.useProxy {
addr := fmt.Sprintf("%s:%d", h.paths.HTTPAddr, h.paths.HTTPPort)
fmt.Printf("\nError compiling code, to view error details see proxy running on http://%s\n\n",addr)
fmt.Printf("\nError compiling code, to view error details see proxy running on http://%s\n\n", addr)
}
h.ranOnce = true
fmt.Printf("\nTime to recompile %s\n",time.Now().Sub(t).String())
fmt.Printf("\nTime to recompile %s\n", time.Since(t).String())
return
}
@@ -253,15 +252,14 @@ func (h *Harness) refresh() (err *utils.SourceError) {
if !h.config.HistoricMode {
// Recalulate run mode based on the config
var paths []byte
if len(h.app.PackagePathMap)>0 {
if len(h.app.PackagePathMap) > 0 {
paths, _ = json.Marshal(h.app.PackagePathMap)
}
runMode = fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v,"packagePathMap":%s}`, h.app.Paths.RunMode, h.config.Verbose, string(paths))
}
if err2 := h.app.Cmd(runMode).Start(h.config); err2 != nil {
utils.Logger.Error("Could not start application", "error", err2)
if err,k :=err2.(*utils.SourceError);k {
if err, k := err2.(*utils.SourceError); k {
return err
}
return &utils.SourceError{
@@ -277,13 +275,13 @@ func (h *Harness) refresh() (err *utils.SourceError) {
}
// WatchDir method returns false to file matches with doNotWatch
// otheriwse true
// otheriwse true.
func (h *Harness) WatchDir(info os.FileInfo) bool {
return !utils.ContainsString(doNotWatch, info.Name())
}
// WatchFile method returns true given filename HasSuffix of ".go"
// otheriwse false - implements revel.DiscerningListener
// otheriwse false - implements revel.DiscerningListener.
func (h *Harness) WatchFile(filename string) bool {
return strings.HasSuffix(filename, ".go")
}
@@ -310,8 +308,6 @@ func (h *Harness) Run() {
}
addr := fmt.Sprintf("%s:%d", h.paths.HTTPAddr, h.paths.HTTPPort)
utils.Logger.Infof("Proxy server is listening on %s", addr)
var err error
if h.paths.HTTPSsl {
err = http.ListenAndServeTLS(
@@ -326,11 +322,11 @@ func (h *Harness) Run() {
utils.Logger.Error("Failed to start reverse proxy:", "error", err)
}
}()
}
// Make a new channel to listen for the interrupt event
ch := make(chan os.Signal)
//nolint:staticcheck // os.Kill ineffective on Unix, useful on Windows?
signal.Notify(ch, os.Interrupt, os.Kill)
<-ch
// Kill the app and exit
@@ -340,7 +336,7 @@ func (h *Harness) Run() {
os.Exit(1)
}
// Find an unused port
// Find an unused port.
func getFreePort() (port int) {
conn, err := net.Listen("tcp", ":0")
if err != nil {