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" "io"
"os" "os"
"os/exec" "os/exec"
"time" "runtime"
"sync" "sync"
"time"
"github.com/revel/cmd/model" "github.com/revel/cmd/model"
"github.com/revel/cmd/utils" "github.com/revel/cmd/utils"
"runtime"
) )
// App contains the configuration for running a Revel app. (Not for the app itself) // App contains the configuration for running a Revel app. (Not for the app itself)
@@ -29,7 +29,7 @@ type App struct {
Paths *model.RevelContainer 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 { 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}
} }
@@ -51,7 +51,7 @@ type AppCmd struct {
*exec.Cmd *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 { func NewAppCmd(binPath string, port int, runMode string, paths *model.RevelContainer) AppCmd {
cmd := exec.Command(binPath, cmd := exec.Command(binPath,
fmt.Sprintf("-port=%d", port), fmt.Sprintf("-port=%d", port),
@@ -89,7 +89,6 @@ func (cmd AppCmd) Start(c *model.CommandConfig) error {
println("Revel proxy is listening, point your browser to :", c.Run.Port) println("Revel proxy is listening, point your browser to :", c.Run.Port)
return nil return nil
} }
} }
// Run the app server inline. Never returns. // 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. // Kill terminates the app server if it's running.
func (cmd AppCmd) Kill() { func (cmd AppCmd) Kill() {
if cmd.Cmd != nil && (cmd.ProcessState == nil || !cmd.ProcessState.Exited()) { if cmd.Cmd != nil && (cmd.ProcessState == nil || !cmd.ProcessState.Exited()) {
// Windows appears to send the kill to all threads, shutting down the // 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 // 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 // Server has already exited
utils.Logger.Info("Server not running revel server pid", "pid", cmd.Process.Pid) utils.Logger.Info("Server not running revel server pid", "pid", cmd.Process.Pid)
return return
@@ -149,7 +147,6 @@ func (cmd AppCmd) Kill() {
return return
} }
// Use a timer to ensure that the process exits // Use a timer to ensure that the process exits
utils.Logger.Info("Waiting to exit") utils.Logger.Info("Waiting to exit")
select { select {
@@ -193,7 +190,7 @@ type startupListeningWriter struct {
buffer *bytes.Buffer buffer *bytes.Buffer
} }
// Writes to this output stream // Writes to this output stream.
func (w *startupListeningWriter) Write(p []byte) (int, error) { func (w *startupListeningWriter) Write(p []byte) (int, error) {
if w.notifyReady != nil && bytes.Contains(p, []byte("Revel engine is listening on")) { if w.notifyReady != nil && bytes.Contains(p, []byte("Revel engine is listening on")) {
w.notifyReady <- true w.notifyReady <- true
@@ -210,10 +207,3 @@ func (w *startupListeningWriter) Write(p []byte) (int, error) {
} }
return w.dest.Write(p) 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" "time"
"github.com/revel/cmd/model" "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/parser"
"github.com/revel/cmd/parser2"
"github.com/revel/cmd/utils"
) )
var importErrorPattern = regexp.MustCompile("cannot find package \"([^\"]+)\"") var importErrorPattern = regexp.MustCompile("cannot find package \"([^\"]+)\"")
@@ -32,9 +31,11 @@ type ByString []*model.TypeInfo
func (c ByString) Len() int { func (c ByString) Len() int {
return len(c) return len(c)
} }
func (c ByString) Swap(i, j int) { func (c ByString) Swap(i, j int) {
c[i], c[j] = c[j], c[i] c[i], c[j] = c[j], c[i]
} }
func (c ByString) Less(i, j int) bool { func (c ByString) Less(i, j int) bool {
return c[i].String() < c[j].String() return c[i].String() < c[j].String()
} }
@@ -155,7 +156,8 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
"build", "build",
"-ldflags", versionLinkerFlags, "-ldflags", versionLinkerFlags,
"-tags", buildTags, "-tags", buildTags,
"-o", binName} "-o", binName,
}
} else { } else {
if !contains(c.BuildFlags, "build") { if !contains(c.BuildFlags, "build") {
flags = []string{"build"} flags = []string{"build"}
@@ -232,9 +234,7 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
// Success getting the import, attempt to build again. // Success getting the import, attempt to build again.
} }
// TODO remove this unreachable code and document it // unreachable
utils.Logger.Fatal("Not reachable")
return nil, nil
} }
// Try to define a version string for the compiled app // Try to define a version string for the compiled app
@@ -259,7 +259,6 @@ func getAppVersion(paths *model.RevelContainer) string {
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) utils.Logger.Info("Exec:", "args", gitCmd.Args)
output, err := gitCmd.Output() output, err := gitCmd.Output()
if err != nil { if err != nil {
utils.Logger.Error("Cannot determine git repository version:", "error", err) utils.Logger.Error("Cannot determine git repository version:", "error", err)
return "" return ""
@@ -317,7 +316,6 @@ func cleanDir(paths *model.RevelContainer, dir string) {
// genSource renders the given template to produce source code, which it writes // genSource renders the given template to produce source code, which it writes
// to the given directory and file. // to the given directory and file.
func genSource(paths *model.RevelContainer, dir, filename, templateSource string, args map[string]interface{}) error { 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) 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 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) { func addAlias(aliases map[string]string, importPath, pkgName string) {
alias, ok := aliases[importPath] _, ok := aliases[importPath]
if ok { if ok {
return return
} }
alias = makePackageAlias(aliases, pkgName) aliases[importPath] = makePackageAlias(aliases, pkgName)
aliases[importPath] = alias
} }
// Generates a package alias // Generates a package alias.
func makePackageAlias(aliases map[string]string, pkgName string) string { func makePackageAlias(aliases map[string]string, pkgName string) string {
i := 0 i := 0
alias := pkgName alias := pkgName
@@ -374,7 +371,7 @@ func makePackageAlias(aliases map[string]string, pkgName string) string {
return alias 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 { func containsValue(m map[string]string, val string) bool {
for _, v := range m { for _, v := range m {
if v == val { if v == val {
@@ -421,7 +418,6 @@ func newCompileError(paths *model.RevelContainer, output []byte) *utils.SourceEr
return newPath return newPath
} }
// Read the source for the offending file. // Read the source for the offending file.
var ( var (
relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go" relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go"
@@ -454,7 +450,7 @@ func newCompileError(paths *model.RevelContainer, output []byte) *utils.SourceEr
return compileError 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 const RevelRunTemplate = `// GENERATED CODE - DO NOT EDIT
// This file is the run file for Revel. // This file is the run file for Revel.
// It registers all the controllers and provides details for the Revel server engine to // 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 const RevelMainTemplate = `// GENERATED CODE - DO NOT EDIT
// This file is the main file for Revel. // This file is the main file for Revel.
// It registers all the controllers and provides details for the Revel server engine to // 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 const RevelRoutesTemplate = `// GENERATED CODE - DO NOT EDIT
// This file provides a way of creating URL's based on all the actions // This file provides a way of creating URL's based on all the actions
// found in all the controllers. // found in all the controllers.

View File

@@ -15,10 +15,12 @@ package harness
import ( import (
"crypto/tls" "crypto/tls"
"encoding/json"
"fmt" "fmt"
"time"
"go/build" "go/build"
"html/template"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/http/httputil" "net/http/httputil"
@@ -27,15 +29,13 @@ import (
"os/signal" "os/signal"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
"sync/atomic" "sync/atomic"
"time"
"github.com/revel/cmd/model" "github.com/revel/cmd/model"
"github.com/revel/cmd/utils" "github.com/revel/cmd/utils"
"github.com/revel/cmd/watcher" "github.com/revel/cmd/watcher"
"html/template"
"io/ioutil"
"sync"
"encoding/json"
) )
var ( var (
@@ -57,7 +57,6 @@ type Harness struct {
paths *model.RevelContainer // The Revel container paths *model.RevelContainer // The Revel container
config *model.CommandConfig // The configuration config *model.CommandConfig // The configuration
runMode string // The runmode the harness is running in runMode string // The runmode the harness is running in
isError bool // True if harness is in error state
ranOnce bool // True app compiled once 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")} target := []string{seekViewOnPath("500.html"), seekViewOnPath("500-dev.html")}
if !utils.Exists(target[0]) { if !utils.Exists(target[0]) {
fmt.Fprintf(iw, "Target template not found not found %s<br />\n", 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 return
} }
var revelError *utils.SourceError var revelError *utils.SourceError
@@ -203,9 +202,9 @@ func NewHarness(c *model.CommandConfig, paths *model.RevelContainer, runMode str
} }
// Refresh method rebuilds the Revel application and run it on the given port. // 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) { func (h *Harness) Refresh() (err *utils.SourceError) {
t := time.Now(); t := time.Now()
fmt.Println("Changed detected, recompiling") fmt.Println("Changed detected, recompiling")
err = h.refresh() err = h.refresh()
if err != nil && !h.ranOnce && h.useProxy { if err != nil && !h.ranOnce && h.useProxy {
@@ -215,7 +214,7 @@ func (h *Harness) Refresh() (err *utils.SourceError) {
} }
h.ranOnce = true 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 return
} }
@@ -257,7 +256,6 @@ func (h *Harness) refresh() (err *utils.SourceError) {
paths, _ = json.Marshal(h.app.PackagePathMap) paths, _ = json.Marshal(h.app.PackagePathMap)
} }
runMode = fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v,"packagePathMap":%s}`, h.app.Paths.RunMode, h.config.Verbose, string(paths)) 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 { if err2 := h.app.Cmd(runMode).Start(h.config); err2 != nil {
utils.Logger.Error("Could not start application", "error", err2) utils.Logger.Error("Could not start application", "error", err2)
@@ -277,13 +275,13 @@ func (h *Harness) refresh() (err *utils.SourceError) {
} }
// WatchDir method returns false to file matches with doNotWatch // WatchDir method returns false to file matches with doNotWatch
// otheriwse true // otheriwse true.
func (h *Harness) WatchDir(info os.FileInfo) bool { func (h *Harness) WatchDir(info os.FileInfo) bool {
return !utils.ContainsString(doNotWatch, info.Name()) return !utils.ContainsString(doNotWatch, info.Name())
} }
// WatchFile method returns true given filename HasSuffix of ".go" // 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 { func (h *Harness) WatchFile(filename string) bool {
return strings.HasSuffix(filename, ".go") return strings.HasSuffix(filename, ".go")
} }
@@ -310,8 +308,6 @@ func (h *Harness) Run() {
} }
addr := fmt.Sprintf("%s:%d", h.paths.HTTPAddr, h.paths.HTTPPort) addr := fmt.Sprintf("%s:%d", h.paths.HTTPAddr, h.paths.HTTPPort)
utils.Logger.Infof("Proxy server is listening on %s", addr) utils.Logger.Infof("Proxy server is listening on %s", addr)
var err error var err error
if h.paths.HTTPSsl { if h.paths.HTTPSsl {
err = http.ListenAndServeTLS( err = http.ListenAndServeTLS(
@@ -326,11 +322,11 @@ func (h *Harness) Run() {
utils.Logger.Error("Failed to start reverse proxy:", "error", err) utils.Logger.Error("Failed to start reverse proxy:", "error", err)
} }
}() }()
} }
// Make a new channel to listen for the interrupt event // Make a new channel to listen for the interrupt event
ch := make(chan os.Signal) ch := make(chan os.Signal)
//nolint:staticcheck // os.Kill ineffective on Unix, useful on Windows?
signal.Notify(ch, os.Interrupt, os.Kill) signal.Notify(ch, os.Interrupt, os.Kill)
<-ch <-ch
// Kill the app and exit // Kill the app and exit
@@ -340,7 +336,7 @@ func (h *Harness) Run() {
os.Exit(1) os.Exit(1)
} }
// Find an unused port // Find an unused port.
func getFreePort() (port int) { func getFreePort() (port int) {
conn, err := net.Listen("tcp", ":0") conn, err := net.Listen("tcp", ":0")
if err != nil { if err != nil {

View File

@@ -1,10 +1,11 @@
package logger package logger
import ( import (
"github.com/mattn/go-colorable"
"gopkg.in/natefinch/lumberjack.v2"
"io" "io"
"os" "os"
"github.com/mattn/go-colorable"
"gopkg.in/natefinch/lumberjack.v2"
) )
type CompositeMultiHandler struct { type CompositeMultiHandler struct {
@@ -19,8 +20,8 @@ func NewCompositeMultiHandler() (*CompositeMultiHandler, LogHandler) {
cw := &CompositeMultiHandler{} cw := &CompositeMultiHandler{}
return cw, cw return cw, cw
} }
func (h *CompositeMultiHandler) Log(r *Record) (err error) {
func (h *CompositeMultiHandler) Log(r *Record) (err error) {
var handler LogHandler var handler LogHandler
switch r.Level { switch r.Level {
@@ -78,7 +79,7 @@ func (h *CompositeMultiHandler) SetHandler(handler LogHandler, replace bool, lev
} }
} }
// For the multi handler set the handler, using the LogOptions defined // For the multi handler set the handler, using the LogOptions defined.
func (h *CompositeMultiHandler) SetHandlers(handler LogHandler, options *LogOptions) { func (h *CompositeMultiHandler) SetHandlers(handler LogHandler, options *LogOptions) {
if len(options.Levels) == 0 { if len(options.Levels) == 0 {
options.Levels = LvlAllList options.Levels = LvlAllList
@@ -88,8 +89,8 @@ func (h *CompositeMultiHandler) SetHandlers(handler LogHandler, options *LogOpti
for _, lvl := range options.Levels { for _, lvl := range options.Levels {
h.SetHandler(handler, options.ReplaceExistingHandler, lvl) h.SetHandler(handler, options.ReplaceExistingHandler, lvl)
} }
} }
func (h *CompositeMultiHandler) SetJson(writer io.Writer, options *LogOptions) { func (h *CompositeMultiHandler) SetJson(writer io.Writer, options *LogOptions) {
handler := CallerFileHandler(StreamHandler(writer, JsonFormatEx( handler := CallerFileHandler(StreamHandler(writer, JsonFormatEx(
options.GetBoolDefault("pretty", false), options.GetBoolDefault("pretty", false),
@@ -101,7 +102,7 @@ func (h *CompositeMultiHandler) SetJson(writer io.Writer, options *LogOptions) {
h.SetHandlers(handler, options) h.SetHandlers(handler, options)
} }
// Use built in rolling function // Use built in rolling function.
func (h *CompositeMultiHandler) SetJsonFile(filePath string, options *LogOptions) { func (h *CompositeMultiHandler) SetJsonFile(filePath string, options *LogOptions) {
writer := &lumberjack.Logger{ writer := &lumberjack.Logger{
Filename: filePath, Filename: filePath,
@@ -141,7 +142,7 @@ func (h *CompositeMultiHandler) SetTerminal(writer io.Writer, options *LogOption
h.SetHandlers(handler, options) h.SetHandlers(handler, options)
} }
// Use built in rolling function // Use built in rolling function.
func (h *CompositeMultiHandler) SetTerminalFile(filePath string, options *LogOptions) { func (h *CompositeMultiHandler) SetTerminalFile(filePath string, options *LogOptions) {
writer := &lumberjack.Logger{ writer := &lumberjack.Logger{
Filename: filePath, Filename: filePath,

View File

@@ -8,8 +8,5 @@
2) Output handlers (log.error.output) replace any existing handlers 2) Output handlers (log.error.output) replace any existing handlers
3) Filter handlers (log.xxx.filter, log.xxx.nfilter) append to existing handlers, 3) Filter handlers (log.xxx.filter, log.xxx.nfilter) append to existing handlers,
note log.all.filter is treated as a filter handler, so it will NOT replace existing ones note log.all.filter is treated as a filter handler, so it will NOT replace existing ones
*/ */
package logger package logger

View File

@@ -11,12 +11,12 @@ type LevelFilterHandler struct {
} }
// Filters out records which do not match the level // Filters out records which do not match the level
// Uses the `log15.FilterHandler` to perform this task // Uses the `log15.FilterHandler` to perform this task.
func LevelHandler(lvl LogLevel, h LogHandler) LogHandler { func LevelHandler(lvl LogLevel, h LogHandler) LogHandler {
return &LevelFilterHandler{lvl, h} return &LevelFilterHandler{lvl, h}
} }
// The implementation of the Log // The implementation of the Log.
func (h LevelFilterHandler) Log(r *Record) error { func (h LevelFilterHandler) Log(r *Record) error {
if r.Level == h.Level { if r.Level == h.Level {
return h.h.Log(r) return h.h.Log(r)
@@ -25,7 +25,7 @@ func (h LevelFilterHandler) Log(r *Record) error {
} }
// Filters out records which do not match the level // Filters out records which do not match the level
// Uses the `log15.FilterHandler` to perform this task // Uses the `log15.FilterHandler` to perform this task.
func MinLevelHandler(lvl LogLevel, h LogHandler) LogHandler { func MinLevelHandler(lvl LogLevel, h LogHandler) LogHandler {
return FilterHandler(func(r *Record) (pass bool) { return FilterHandler(func(r *Record) (pass bool) {
return r.Level <= lvl return r.Level <= lvl
@@ -33,7 +33,7 @@ func MinLevelHandler(lvl LogLevel, h LogHandler) LogHandler {
} }
// Filters out records which match the level // Filters out records which match the level
// Uses the `log15.FilterHandler` to perform this task // Uses the `log15.FilterHandler` to perform this task.
func NotLevelHandler(lvl LogLevel, h LogHandler) LogHandler { func NotLevelHandler(lvl LogLevel, h LogHandler) LogHandler {
return FilterHandler(func(r *Record) (pass bool) { return FilterHandler(func(r *Record) (pass bool) {
return r.Level != lvl return r.Level != lvl
@@ -48,13 +48,13 @@ func CallerFileHandler(h LogHandler) LogHandler {
} }
// Adds in a context called `caller` to the record (contains file name and line number like `foo.go:12`) // Adds in a context called `caller` to the record (contains file name and line number like `foo.go:12`)
// Uses the `log15.CallerFuncHandler` to perform this task // Uses the `log15.CallerFuncHandler` to perform this task.
func CallerFuncHandler(h LogHandler) LogHandler { func CallerFuncHandler(h LogHandler) LogHandler {
return CallerFuncHandler(h) return CallerFuncHandler(h)
} }
// Filters out records which match the key value pair // Filters out records which match the key value pair
// Uses the `log15.MatchFilterHandler` to perform this task // Uses the `log15.MatchFilterHandler` to perform this task.
func MatchHandler(key string, value interface{}, h LogHandler) LogHandler { func MatchHandler(key string, value interface{}, h LogHandler) LogHandler {
return MatchFilterHandler(key, value, h) return MatchFilterHandler(key, value, h)
} }
@@ -72,7 +72,7 @@ func MatchFilterHandler(key string, value interface{}, h LogHandler) LogHandler
}, h) }, h)
} }
// If match then A handler is called otherwise B handler is called // If match then A handler is called otherwise B handler is called.
func MatchAbHandler(key string, value interface{}, a, b LogHandler) LogHandler { func MatchAbHandler(key string, value interface{}, a, b LogHandler) LogHandler {
return FuncHandler(func(r *Record) error { return FuncHandler(func(r *Record) error {
if r.Context[key] == value { if r.Context[key] == value {
@@ -85,24 +85,24 @@ func MatchAbHandler(key string, value interface{}, a, b LogHandler) LogHandler {
}) })
} }
// The nil handler is used if logging for a specific request needs to be turned off // The nil handler is used if logging for a specific request needs to be turned off.
func NilHandler() LogHandler { func NilHandler() LogHandler {
return FuncHandler(func(r *Record) error { return FuncHandler(func(r *Record) error {
return nil return nil
}) })
} }
// Match all values in map to log // Match all values in map to log.
func MatchMapHandler(matchMap map[string]interface{}, a LogHandler) LogHandler { func MatchMapHandler(matchMap map[string]interface{}, a LogHandler) LogHandler {
return matchMapHandler(matchMap, false, a) return matchMapHandler(matchMap, false, a)
} }
// Match !(Match all values in map to log) The inverse of MatchMapHandler // Match !(Match all values in map to log) The inverse of MatchMapHandler.
func NotMatchMapHandler(matchMap map[string]interface{}, a LogHandler) LogHandler { func NotMatchMapHandler(matchMap map[string]interface{}, a LogHandler) LogHandler {
return matchMapHandler(matchMap, true, a) return matchMapHandler(matchMap, true, a)
} }
// Rather then chaining multiple filter handlers, process all here // Rather then chaining multiple filter handlers, process all here.
func matchMapHandler(matchMap map[string]interface{}, inverse bool, a LogHandler) LogHandler { func matchMapHandler(matchMap map[string]interface{}, inverse bool, a LogHandler) LogHandler {
return FuncHandler(func(r *Record) error { return FuncHandler(func(r *Record) error {
matchCount := 0 matchCount := 0
@@ -114,10 +114,11 @@ func matchMapHandler(matchMap map[string]interface{}, inverse bool, a LogHandler
// Test for two failure cases // Test for two failure cases
if value == v && inverse || value != v && !inverse { if value == v && inverse || value != v && !inverse {
return nil return nil
} else { }
matchCount++ matchCount++
} }
}
if matchCount != len(matchMap) { if matchCount != len(matchMap) {
return nil return nil
} }
@@ -126,7 +127,7 @@ func matchMapHandler(matchMap map[string]interface{}, inverse bool, a LogHandler
} }
// Filters out records which do not match the key value pair // Filters out records which do not match the key value pair
// Uses the `log15.FilterHandler` to perform this task // Uses the `log15.FilterHandler` to perform this task.
func NotMatchHandler(key string, value interface{}, h LogHandler) LogHandler { func NotMatchHandler(key string, value interface{}, h LogHandler) LogHandler {
return FilterHandler(func(r *Record) (pass bool) { return FilterHandler(func(r *Record) (pass bool) {
return r.Context[key] != value return r.Context[key] != value
@@ -158,7 +159,7 @@ func StreamHandler(wr io.Writer, fmtr LogFormat) LogHandler {
return LazyHandler(SyncHandler(h)) return LazyHandler(SyncHandler(h))
} }
// Filter handler // Filter handler.
func FilterHandler(fn func(r *Record) bool, h LogHandler) LogHandler { func FilterHandler(fn func(r *Record) bool, h LogHandler) LogHandler {
return FuncHandler(func(r *Record) error { return FuncHandler(func(r *Record) error {
if fn(r) { if fn(r) {
@@ -168,18 +169,18 @@ func FilterHandler(fn func(r *Record) bool, h LogHandler) LogHandler {
}) })
} }
// List log handler handles a list of LogHandlers // List log handler handles a list of LogHandlers.
type ListLogHandler struct { type ListLogHandler struct {
handlers []LogHandler handlers []LogHandler
} }
// Create a new list of log handlers // Create a new list of log handlers.
func NewListLogHandler(h1, h2 LogHandler) *ListLogHandler { func NewListLogHandler(h1, h2 LogHandler) *ListLogHandler {
ll := &ListLogHandler{handlers: []LogHandler{h1, h2}} ll := &ListLogHandler{handlers: []LogHandler{h1, h2}}
return ll return ll
} }
// Log the record // Log the record.
func (ll *ListLogHandler) Log(r *Record) (err error) { func (ll *ListLogHandler) Log(r *Record) (err error) {
for _, handler := range ll.handlers { for _, handler := range ll.handlers {
if err == nil { if err == nil {
@@ -191,14 +192,14 @@ func (ll *ListLogHandler) Log(r *Record) (err error) {
return return
} }
// Add another log handler // Add another log handler.
func (ll *ListLogHandler) Add(h LogHandler) { func (ll *ListLogHandler) Add(h LogHandler) {
if h != nil { if h != nil {
ll.handlers = append(ll.handlers, h) ll.handlers = append(ll.handlers, h)
} }
} }
// Remove a log handler // Remove a log handler.
func (ll *ListLogHandler) Del(h LogHandler) { func (ll *ListLogHandler) Del(h LogHandler) {
if h != nil { if h != nil {
for i, handler := range ll.handlers { for i, handler := range ll.handlers {

View File

@@ -1,13 +1,14 @@
package logger package logger
// Get all handlers based on the Config (if available) // Get all handlers based on the Config (if available).
import ( import (
"fmt" "fmt"
"github.com/revel/config"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/revel/config"
) )
func InitializeFromConfig(basePath string, config *config.Context) (c *CompositeMultiHandler) { func InitializeFromConfig(basePath string, config *config.Context) (c *CompositeMultiHandler) {
@@ -43,7 +44,7 @@ func InitializeFromConfig(basePath string, config *config.Context) (c *Composite
return c return c
} }
// Init the log.all configuration options // Init the log.all configuration options.
func initAllLog(c *CompositeMultiHandler, basePath string, config *config.Context) { func initAllLog(c *CompositeMultiHandler, basePath string, config *config.Context) {
if config != nil { if config != nil {
extraLogFlag := config.BoolDefault(SPECIAL_USE_FLAG, false) extraLogFlag := config.BoolDefault(SPECIAL_USE_FLAG, false)
@@ -61,13 +62,13 @@ func initAllLog(c *CompositeMultiHandler, basePath string, config *config.Contex
// log.all.filter .... // log.all.filter ....
// log.error.filter .... // log.error.filter ....
func initFilterLog(c *CompositeMultiHandler, basePath string, config *config.Context) { func initFilterLog(c *CompositeMultiHandler, basePath string, config *config.Context) {
if config != nil { if config != nil {
extraLogFlag := config.BoolDefault(SPECIAL_USE_FLAG, false) extraLogFlag := config.BoolDefault(SPECIAL_USE_FLAG, false)
for _, logFilter := range logFilterList { for _, logFilter := range logFilterList {
// Init for all filters // Init for all filters
for _, name := range []string{"all", "debug", "info", "warn", "error", "crit", for _, name := range []string{
"all", "debug", "info", "warn", "error", "crit",
"trace", // TODO trace is deprecated "trace", // TODO trace is deprecated
} { } {
optionList := config.Options(logFilter.LogPrefix + name + logFilter.LogSuffix) optionList := config.Options(logFilter.LogPrefix + name + logFilter.LogSuffix)
@@ -94,9 +95,10 @@ func initFilterLog(c *CompositeMultiHandler, basePath string, config *config.Con
} }
} }
// Init the log.error, log.warn etc configuration options // Init the log.error, log.warn etc configuration options.
func initLogLevels(c *CompositeMultiHandler, basePath string, config *config.Context) { func initLogLevels(c *CompositeMultiHandler, basePath string, config *config.Context) {
for _, name := range []string{"debug", "info", "warn", "error", "crit", for _, name := range []string{
"debug", "info", "warn", "error", "crit",
"trace", // TODO trace is deprecated "trace", // TODO trace is deprecated
} { } {
if config != nil { if config != nil {
@@ -115,7 +117,7 @@ func initLogLevels(c *CompositeMultiHandler, basePath string, config *config.Con
} }
} }
// Init the request log options // Init the request log options.
func initRequestLog(c *CompositeMultiHandler, basePath string, config *config.Context) { func initRequestLog(c *CompositeMultiHandler, basePath string, config *config.Context) {
// Request logging to a separate output handler // Request logging to a separate output handler
// This takes the InfoHandlers and adds a MatchAbHandler handler to it to direct // This takes the InfoHandlers and adds a MatchAbHandler handler to it to direct
@@ -143,7 +145,7 @@ func initRequestLog(c *CompositeMultiHandler, basePath string, config *config.Co
// Returns a handler for the level using the output string // Returns a handler for the level using the output string
// Accept formats for output string are // Accept formats for output string are
// LogFunctionMap[value] callback function // LogFunctionMap[value] callback function
// `stdout` `stderr` `full/file/path/to/location/app.log` `full/file/path/to/location/app.json` // `stdout` `stderr` `full/file/path/to/location/app.log` `full/file/path/to/location/app.json`.
func initHandlerFor(c *CompositeMultiHandler, output, basePath string, options *LogOptions) { func initHandlerFor(c *CompositeMultiHandler, output, basePath string, options *LogOptions) {
if options.Ctx != nil { if options.Ctx != nil {
options.SetExtendedOptions( options.SetExtendedOptions(
@@ -185,5 +187,4 @@ func initHandlerFor(c *CompositeMultiHandler, output, basePath string, options *
} }
} }
} }
return
} }

View File

@@ -5,46 +5,57 @@
package logger_test package logger_test
import ( import (
"github.com/revel/config"
"github.com/revel/revel/logger"
"github.com/stretchr/testify/assert"
"os" "os"
"strings" "strings"
"testing" "testing"
"github.com/revel/cmd/logger"
"github.com/revel/config"
"github.com/stretchr/testify/assert"
) )
type ( type (
// A counter for the tester // A counter for the tester.
testCounter struct { testCounter struct {
debug, info, warn, error, critical int debug, info, warn, error, critical int
} }
// The data to tes // The data to tes.
testData struct { testData struct {
config []string config []string
result testResult result testResult
tc *testCounter tc *testCounter
} }
// The test result // The test result.
testResult struct { testResult struct {
debug, info, warn, error, critical int debug, info, warn, error, critical int
} }
) )
// Single test cases // Single test cases.
var singleCases = []testData{ var singleCases = []testData{
{config: []string{"log.crit.output"}, {
result: testResult{0, 0, 0, 0, 1}}, config: []string{"log.crit.output"},
{config: []string{"log.error.output"}, result: testResult{0, 0, 0, 0, 1},
result: testResult{0, 0, 0, 1, 1}}, },
{config: []string{"log.warn.output"}, {
result: testResult{0, 0, 1, 0, 0}}, config: []string{"log.error.output"},
{config: []string{"log.info.output"}, result: testResult{0, 0, 0, 1, 1},
result: testResult{0, 1, 0, 0, 0}}, },
{config: []string{"log.debug.output"}, {
result: testResult{1, 0, 0, 0, 0}}, config: []string{"log.warn.output"},
result: testResult{0, 0, 1, 0, 0},
},
{
config: []string{"log.info.output"},
result: testResult{0, 1, 0, 0, 0},
},
{
config: []string{"log.debug.output"},
result: testResult{1, 0, 0, 0, 0},
},
} }
// Test singles // Test singles.
func TestSingleCases(t *testing.T) { func TestSingleCases(t *testing.T) {
rootLog := logger.New() rootLog := logger.New()
for _, testCase := range singleCases { for _, testCase := range singleCases {
@@ -53,31 +64,51 @@ func TestSingleCases(t *testing.T) {
} }
} }
// Filter test cases // Filter test cases.
var filterCases = []testData{ var filterCases = []testData{
{config: []string{"log.crit.filter.module.app"}, {
result: testResult{0, 0, 0, 0, 1}}, config: []string{"log.crit.filter.module.app"},
{config: []string{"log.crit.filter.module.appa"}, result: testResult{0, 0, 0, 0, 1},
result: testResult{0, 0, 0, 0, 0}}, },
{config: []string{"log.error.filter.module.app"}, {
result: testResult{0, 0, 0, 1, 1}}, config: []string{"log.crit.filter.module.appa"},
{config: []string{"log.error.filter.module.appa"}, result: testResult{0, 0, 0, 0, 0},
result: testResult{0, 0, 0, 0, 0}}, },
{config: []string{"log.warn.filter.module.app"}, {
result: testResult{0, 0, 1, 0, 0}}, config: []string{"log.error.filter.module.app"},
{config: []string{"log.warn.filter.module.appa"}, result: testResult{0, 0, 0, 1, 1},
result: testResult{0, 0, 0, 0, 0}}, },
{config: []string{"log.info.filter.module.app"}, {
result: testResult{0, 1, 0, 0, 0}}, config: []string{"log.error.filter.module.appa"},
{config: []string{"log.info.filter.module.appa"}, result: testResult{0, 0, 0, 0, 0},
result: testResult{0, 0, 0, 0, 0}}, },
{config: []string{"log.debug.filter.module.app"}, {
result: testResult{1, 0, 0, 0, 0}}, config: []string{"log.warn.filter.module.app"},
{config: []string{"log.debug.filter.module.appa"}, result: testResult{0, 0, 1, 0, 0},
result: testResult{0, 0, 0, 0, 0}}, },
{
config: []string{"log.warn.filter.module.appa"},
result: testResult{0, 0, 0, 0, 0},
},
{
config: []string{"log.info.filter.module.app"},
result: testResult{0, 1, 0, 0, 0},
},
{
config: []string{"log.info.filter.module.appa"},
result: testResult{0, 0, 0, 0, 0},
},
{
config: []string{"log.debug.filter.module.app"},
result: testResult{1, 0, 0, 0, 0},
},
{
config: []string{"log.debug.filter.module.appa"},
result: testResult{0, 0, 0, 0, 0},
},
} }
// Filter test // Filter test.
func TestFilterCases(t *testing.T) { func TestFilterCases(t *testing.T) {
rootLog := logger.New("module", "app") rootLog := logger.New("module", "app")
for _, testCase := range filterCases { for _, testCase := range filterCases {
@@ -86,33 +117,55 @@ func TestFilterCases(t *testing.T) {
} }
} }
// Inverse test cases // Inverse test cases.
var nfilterCases = []testData{ var nfilterCases = []testData{
{config: []string{"log.crit.nfilter.module.appa"}, {
result: testResult{0, 0, 0, 0, 1}}, config: []string{"log.crit.nfilter.module.appa"},
{config: []string{"log.crit.nfilter.modules.appa"}, result: testResult{0, 0, 0, 0, 1},
result: testResult{0, 0, 0, 0, 0}}, },
{config: []string{"log.crit.nfilter.module.app"}, {
result: testResult{0, 0, 0, 0, 0}}, config: []string{"log.crit.nfilter.modules.appa"},
{config: []string{"log.error.nfilter.module.appa"}, // Special case, when error is not nill critical inherits from error result: testResult{0, 0, 0, 0, 0},
result: testResult{0, 0, 0, 1, 1}}, },
{config: []string{"log.error.nfilter.module.app"}, {
result: testResult{0, 0, 0, 0, 0}}, config: []string{"log.crit.nfilter.module.app"},
{config: []string{"log.warn.nfilter.module.appa"}, result: testResult{0, 0, 0, 0, 0},
result: testResult{0, 0, 1, 0, 0}}, },
{config: []string{"log.warn.nfilter.module.app"}, {
result: testResult{0, 0, 0, 0, 0}}, config: []string{"log.error.nfilter.module.appa"}, // Special case, when error is not nill critical inherits from error
{config: []string{"log.info.nfilter.module.appa"}, result: testResult{0, 0, 0, 1, 1},
result: testResult{0, 1, 0, 0, 0}}, },
{config: []string{"log.info.nfilter.module.app"}, {
result: testResult{0, 0, 0, 0, 0}}, config: []string{"log.error.nfilter.module.app"},
{config: []string{"log.debug.nfilter.module.appa"}, result: testResult{0, 0, 0, 0, 0},
result: testResult{1, 0, 0, 0, 0}}, },
{config: []string{"log.debug.nfilter.module.app"}, {
result: testResult{0, 0, 0, 0, 0}}, config: []string{"log.warn.nfilter.module.appa"},
result: testResult{0, 0, 1, 0, 0},
},
{
config: []string{"log.warn.nfilter.module.app"},
result: testResult{0, 0, 0, 0, 0},
},
{
config: []string{"log.info.nfilter.module.appa"},
result: testResult{0, 1, 0, 0, 0},
},
{
config: []string{"log.info.nfilter.module.app"},
result: testResult{0, 0, 0, 0, 0},
},
{
config: []string{"log.debug.nfilter.module.appa"},
result: testResult{1, 0, 0, 0, 0},
},
{
config: []string{"log.debug.nfilter.module.app"},
result: testResult{0, 0, 0, 0, 0},
},
} }
// Inverse test // Inverse test.
func TestNotFilterCases(t *testing.T) { func TestNotFilterCases(t *testing.T) {
rootLog := logger.New("module", "app") rootLog := logger.New("module", "app")
for _, testCase := range nfilterCases { for _, testCase := range nfilterCases {
@@ -121,13 +174,15 @@ func TestNotFilterCases(t *testing.T) {
} }
} }
// off test cases // off test cases.
var offCases = []testData{ var offCases = []testData{
{config: []string{"log.all.output", "log.error.output=off"}, {
result: testResult{1, 1, 1, 0, 1}}, config: []string{"log.all.output", "log.error.output=off"},
result: testResult{1, 1, 1, 0, 1},
},
} }
// Off test // Off test.
func TestOffCases(t *testing.T) { func TestOffCases(t *testing.T) {
rootLog := logger.New("module", "app") rootLog := logger.New("module", "app")
for _, testCase := range offCases { for _, testCase := range offCases {
@@ -136,13 +191,15 @@ func TestOffCases(t *testing.T) {
} }
} }
// Duplicate test cases // Duplicate test cases.
var duplicateCases = []testData{ var duplicateCases = []testData{
{config: []string{"log.all.output", "log.error.output", "log.error.filter.module.app"}, {
result: testResult{1, 1, 1, 2, 1}}, config: []string{"log.all.output", "log.error.output", "log.error.filter.module.app"},
result: testResult{1, 1, 1, 2, 1},
},
} }
// test duplicate cases // test duplicate cases.
func TestDuplicateCases(t *testing.T) { func TestDuplicateCases(t *testing.T) {
rootLog := logger.New("module", "app") rootLog := logger.New("module", "app")
for _, testCase := range duplicateCases { for _, testCase := range duplicateCases {
@@ -151,19 +208,27 @@ func TestDuplicateCases(t *testing.T) {
} }
} }
// Contradicting cases // Contradicting cases.
var contradictCases = []testData{ var contradictCases = []testData{
{config: []string{"log.all.output", "log.error.output=off", "log.all.output"}, {
result: testResult{1, 1, 1, 0, 1}}, config: []string{"log.all.output", "log.error.output=off", "log.all.output"},
{config: []string{"log.all.output", "log.error.output=off", "log.debug.filter.module.app"}, result: testResult{1, 1, 1, 0, 1},
result: testResult{2, 1, 1, 0, 1}}, },
{config: []string{"log.all.filter.module.app", "log.info.output=off", "log.info.filter.module.app"}, {
result: testResult{1, 2, 1, 1, 1}}, config: []string{"log.all.output", "log.error.output=off", "log.debug.filter.module.app"},
{config: []string{"log.all.output", "log.info.output=off", "log.info.filter.module.app"}, result: testResult{2, 1, 1, 0, 1},
result: testResult{1, 1, 1, 1, 1}}, },
{
config: []string{"log.all.filter.module.app", "log.info.output=off", "log.info.filter.module.app"},
result: testResult{1, 2, 1, 1, 1},
},
{
config: []string{"log.all.output", "log.info.output=off", "log.info.filter.module.app"},
result: testResult{1, 1, 1, 1, 1},
},
} }
// Contradiction test // Contradiction test.
func TestContradictCases(t *testing.T) { func TestContradictCases(t *testing.T) {
rootLog := logger.New("module", "app") rootLog := logger.New("module", "app")
for _, testCase := range contradictCases { for _, testCase := range contradictCases {
@@ -172,15 +237,19 @@ func TestContradictCases(t *testing.T) {
} }
} }
// All test cases // All test cases.
var allCases = []testData{ var allCases = []testData{
{config: []string{"log.all.filter.module.app"}, {
result: testResult{1, 1, 1, 1, 1}}, config: []string{"log.all.filter.module.app"},
{config: []string{"log.all.output"}, result: testResult{1, 1, 1, 1, 1},
result: testResult{2, 2, 2, 2, 2}}, },
{
config: []string{"log.all.output"},
result: testResult{2, 2, 2, 2, 2},
},
} }
// All tests // All tests.
func TestAllCases(t *testing.T) { func TestAllCases(t *testing.T) {
rootLog := logger.New("module", "app") rootLog := logger.New("module", "app")
for i, testCase := range allCases { for i, testCase := range allCases {
@@ -195,7 +264,6 @@ func TestAllCases(t *testing.T) {
for _, testCase := range allCases { for _, testCase := range allCases {
testCase.validate(t) testCase.validate(t)
} }
} }
func (c *testCounter) Log(r *logger.Record) error { func (c *testCounter) Log(r *logger.Record) error {
@@ -215,6 +283,7 @@ func (c *testCounter) Log(r *logger.Record) error {
} }
return nil return nil
} }
func (td *testData) logTest(rootLog logger.MultiLogger, t *testing.T) { func (td *testData) logTest(rootLog logger.MultiLogger, t *testing.T) {
if td.tc == nil { if td.tc == nil {
td.tc = &testCounter{} td.tc = &testCounter{}
@@ -256,7 +325,7 @@ func (td *testData) validate(t *testing.T) {
assert.Equal(t, td.result.critical, td.tc.critical, "Critical failed "+strings.Join(td.config, " ")) assert.Equal(t, td.result.critical, td.tc.critical, "Critical failed "+strings.Join(td.config, " "))
} }
// Add test to the function map // Add test to the function map.
func counterInit(tc *testCounter) { func counterInit(tc *testCounter) {
logger.LogFunctionMap["test"] = func(c *logger.CompositeMultiHandler, logOptions *logger.LogOptions) { logger.LogFunctionMap["test"] = func(c *logger.CompositeMultiHandler, logOptions *logger.LogOptions) {
// Output to the test log and the stdout // Output to the test log and the stdout

View File

@@ -4,8 +4,8 @@ import (
"os" "os"
) )
// The log function map can be added to, so that you can specify your own logging mechanism // LogFunctionMap can be added to, so that you can specify your own logging mechanism
// it has defaults for off, stdout, stderr // it has defaults for off, stdout, stderr.
var LogFunctionMap = map[string]func(*CompositeMultiHandler, *LogOptions){ var LogFunctionMap = map[string]func(*CompositeMultiHandler, *LogOptions){
// Do nothing - set the logger off // Do nothing - set the logger off
"off": func(c *CompositeMultiHandler, logOptions *LogOptions) { "off": func(c *CompositeMultiHandler, logOptions *LogOptions) {

View File

@@ -2,14 +2,15 @@ package logger
import ( import (
"fmt" "fmt"
"github.com/revel/config"
"time" "time"
"github.com/revel/config"
) )
// The LogHandler defines the interface to handle the log records // The LogHandler defines the interface to handle the log records.
type ( type (
// The Multilogger reduces the number of exposed defined logging variables, // The Multilogger reduces the number of exposed defined logging variables,
// and allows the output to be easily refined // and allows the output to be easily refined.
MultiLogger interface { MultiLogger interface {
// New returns a new Logger that has this logger's context plus the given context // New returns a new Logger that has this logger's context plus the given context
New(ctx ...interface{}) MultiLogger New(ctx ...interface{}) MultiLogger
@@ -63,32 +64,32 @@ type (
Panicf(msg string, params ...interface{}) Panicf(msg string, params ...interface{})
} }
// The log handler interface // The log handler interface.
LogHandler interface { LogHandler interface {
Log(*Record) error Log(*Record) error
// log15.Handler // log15.Handler
} }
// The log stack handler interface // The log stack handler interface.
LogStackHandler interface { LogStackHandler interface {
LogHandler LogHandler
GetStack() int GetStack() int
} }
// The log handler interface which has child logs // The log handler interface which has child logs.
ParentLogHandler interface { ParentLogHandler interface {
SetChild(handler LogHandler) LogHandler SetChild(handler LogHandler) LogHandler
} }
// The log format interface // The log format interface.
LogFormat interface { LogFormat interface {
Format(r *Record) []byte Format(r *Record) []byte
} }
// The log level type // The log level type.
LogLevel int LogLevel int
// Used for the callback to LogFunctionMap // Used for the callback to LogFunctionMap.
LogOptions struct { LogOptions struct {
Ctx *config.Context Ctx *config.Context
ReplaceExistingHandler bool ReplaceExistingHandler bool
@@ -97,7 +98,7 @@ type (
ExtendedOptions map[string]interface{} ExtendedOptions map[string]interface{}
} }
// The log record // The log record.
Record struct { Record struct {
Message string // The message Message string // The message
Time time.Time // The time Time time.Time // The time
@@ -106,13 +107,13 @@ type (
Context ContextMap // The context Context ContextMap // The context
} }
// The lazy structure to implement a function to be invoked only if needed // The lazy structure to implement a function to be invoked only if needed.
Lazy struct { Lazy struct {
Fn interface{} // the function Fn interface{} // the function
} }
// Currently the only requirement for the callstack is to support the Formatter method // Currently the only requirement for the callstack is to support the Formatter method
// which stack.Call does so we use that // which stack.Call does so we use that.
CallStack interface { CallStack interface {
fmt.Formatter // Requirement fmt.Formatter // Requirement
} }
@@ -129,6 +130,7 @@ type formatFunc func(*Record) []byte
func (f formatFunc) Format(r *Record) []byte { func (f formatFunc) Format(r *Record) []byte {
return f(r) return f(r)
} }
func NewRecord(message string, level LogLevel) *Record { func NewRecord(message string, level LogLevel) *Record {
return &Record{Message: message, Context: ContextMap{}, Level: level} return &Record{Message: message, Context: ContextMap{}, Level: level}
} }
@@ -141,25 +143,25 @@ const (
LvlDebug // Debug LvlDebug // Debug
) )
// A list of all the log levels // LvlAllList is a list of all the log levels.
var LvlAllList = []LogLevel{LvlDebug, LvlInfo, LvlWarn, LvlError, LvlCrit} var LvlAllList = []LogLevel{LvlDebug, LvlInfo, LvlWarn, LvlError, LvlCrit}
// Implements the ParentLogHandler // Implements the ParentLogHandler.
type parentLogHandler struct { type parentLogHandler struct {
setChild func(handler LogHandler) LogHandler setChild func(handler LogHandler) LogHandler
} }
// Create a new parent log handler // Create a new parent log handler.
func NewParentLogHandler(callBack func(child LogHandler) LogHandler) ParentLogHandler { func NewParentLogHandler(callBack func(child LogHandler) LogHandler) ParentLogHandler {
return &parentLogHandler{callBack} return &parentLogHandler{callBack}
} }
// Sets the child of the log handler // Sets the child of the log handler.
func (p *parentLogHandler) SetChild(child LogHandler) LogHandler { func (p *parentLogHandler) SetChild(child LogHandler) LogHandler {
return p.setChild(child) return p.setChild(child)
} }
// Create a new log options // Create a new log options.
func NewLogOptions(cfg *config.Context, replaceHandler bool, phandler ParentLogHandler, lvl ...LogLevel) (logOptions *LogOptions) { func NewLogOptions(cfg *config.Context, replaceHandler bool, phandler ParentLogHandler, lvl ...LogLevel) (logOptions *LogOptions) {
logOptions = &LogOptions{ logOptions = &LogOptions{
Ctx: cfg, Ctx: cfg,
@@ -171,14 +173,14 @@ func NewLogOptions(cfg *config.Context, replaceHandler bool, phandler ParentLogH
return return
} }
// Assumes options will be an even number and have a string, value syntax // Assumes options will be an even number and have a string, value syntax.
func (l *LogOptions) SetExtendedOptions(options ...interface{}) { func (l *LogOptions) SetExtendedOptions(options ...interface{}) {
for x := 0; x < len(options); x += 2 { for x := 0; x < len(options); x += 2 {
l.ExtendedOptions[options[x].(string)] = options[x+1] l.ExtendedOptions[options[x].(string)] = options[x+1]
} }
} }
// Gets a string option with default // Gets a string option with default.
func (l *LogOptions) GetStringDefault(option, value string) string { func (l *LogOptions) GetStringDefault(option, value string) string {
if v, found := l.ExtendedOptions[option]; found { if v, found := l.ExtendedOptions[option]; found {
return v.(string) return v.(string)
@@ -186,7 +188,7 @@ func (l *LogOptions) GetStringDefault(option, value string) string {
return value return value
} }
// Gets an int option with default // Gets an int option with default.
func (l *LogOptions) GetIntDefault(option string, value int) int { func (l *LogOptions) GetIntDefault(option string, value int) int {
if v, found := l.ExtendedOptions[option]; found { if v, found := l.ExtendedOptions[option]; found {
return v.(int) return v.(int)
@@ -194,7 +196,7 @@ func (l *LogOptions) GetIntDefault(option string, value int) int {
return value return value
} }
// Gets a boolean option with default // Gets a boolean option with default.
func (l *LogOptions) GetBoolDefault(option string, value bool) bool { func (l *LogOptions) GetBoolDefault(option string, value bool) bool {
if v, found := l.ExtendedOptions[option]; found { if v, found := l.ExtendedOptions[option]; found {
return v.(bool) return v.(bool)

View File

@@ -2,18 +2,19 @@ package logger
import ( import (
"fmt" "fmt"
"github.com/revel/log15"
"log" "log"
"os" "os"
"github.com/revel/log15"
) )
// This type implements the MultiLogger // This type implements the MultiLogger.
type RevelLogger struct { type RevelLogger struct {
log15.Logger log15.Logger
} }
// Set the systems default logger // Set the systems default logger
// Default logs will be captured and handled by revel at level info // Default logs will be captured and handled by revel at level info.
func SetDefaultLog(fromLog MultiLogger) { func SetDefaultLog(fromLog MultiLogger) {
log.SetOutput(loggerRewrite{Logger: fromLog, Level: log15.LvlInfo, hideDeprecated: true}) log.SetOutput(loggerRewrite{Logger: fromLog, Level: log15.LvlInfo, hideDeprecated: true})
// No need to show date and time, that will be logged with revel // No need to show date and time, that will be logged with revel
@@ -24,73 +25,73 @@ func (rl *RevelLogger) Debugf(msg string, param ...interface{}) {
rl.Debug(fmt.Sprintf(msg, param...)) rl.Debug(fmt.Sprintf(msg, param...))
} }
// Print a formatted info message // Print a formatted info message.
func (rl *RevelLogger) Infof(msg string, param ...interface{}) { func (rl *RevelLogger) Infof(msg string, param ...interface{}) {
rl.Info(fmt.Sprintf(msg, param...)) rl.Info(fmt.Sprintf(msg, param...))
} }
// Print a formatted warn message // Print a formatted warn message.
func (rl *RevelLogger) Warnf(msg string, param ...interface{}) { func (rl *RevelLogger) Warnf(msg string, param ...interface{}) {
rl.Warn(fmt.Sprintf(msg, param...)) rl.Warn(fmt.Sprintf(msg, param...))
} }
// Print a formatted error message // Print a formatted error message.
func (rl *RevelLogger) Errorf(msg string, param ...interface{}) { func (rl *RevelLogger) Errorf(msg string, param ...interface{}) {
rl.Error(fmt.Sprintf(msg, param...)) rl.Error(fmt.Sprintf(msg, param...))
} }
// Print a formatted critical message // Print a formatted critical message.
func (rl *RevelLogger) Critf(msg string, param ...interface{}) { func (rl *RevelLogger) Critf(msg string, param ...interface{}) {
rl.Crit(fmt.Sprintf(msg, param...)) rl.Crit(fmt.Sprintf(msg, param...))
} }
// Print a formatted fatal message // Print a formatted fatal message.
func (rl *RevelLogger) Fatalf(msg string, param ...interface{}) { func (rl *RevelLogger) Fatalf(msg string, param ...interface{}) {
rl.Fatal(fmt.Sprintf(msg, param...)) rl.Fatal(fmt.Sprintf(msg, param...))
} }
// Print a formatted panic message // Print a formatted panic message.
func (rl *RevelLogger) Panicf(msg string, param ...interface{}) { func (rl *RevelLogger) Panicf(msg string, param ...interface{}) {
rl.Panic(fmt.Sprintf(msg, param...)) rl.Panic(fmt.Sprintf(msg, param...))
} }
// Print a critical message and call os.Exit(1) // Print a critical message and call os.Exit(1).
func (rl *RevelLogger) Fatal(msg string, ctx ...interface{}) { func (rl *RevelLogger) Fatal(msg string, ctx ...interface{}) {
rl.Crit(msg, ctx...) rl.Crit(msg, ctx...)
os.Exit(1) os.Exit(1)
} }
// Print a critical message and panic // Print a critical message and panic.
func (rl *RevelLogger) Panic(msg string, ctx ...interface{}) { func (rl *RevelLogger) Panic(msg string, ctx ...interface{}) {
rl.Crit(msg, ctx...) rl.Crit(msg, ctx...)
panic(msg) panic(msg)
} }
// Override log15 method // Override log15 method.
func (rl *RevelLogger) New(ctx ...interface{}) MultiLogger { func (rl *RevelLogger) New(ctx ...interface{}) MultiLogger {
old := &RevelLogger{Logger: rl.Logger.New(ctx...)} old := &RevelLogger{Logger: rl.Logger.New(ctx...)}
return old return old
} }
// Set the stack level to check for the caller // Set the stack level to check for the caller.
func (rl *RevelLogger) SetStackDepth(amount int) MultiLogger { func (rl *RevelLogger) SetStackDepth(amount int) MultiLogger {
rl.Logger.SetStackDepth(amount) // Ignore the logger returned rl.Logger.SetStackDepth(amount) // Ignore the logger returned
return rl return rl
} }
// Create a new logger // Create a new logger.
func New(ctx ...interface{}) MultiLogger { func New(ctx ...interface{}) MultiLogger {
r := &RevelLogger{Logger: log15.New(ctx...)} r := &RevelLogger{Logger: log15.New(ctx...)}
r.SetStackDepth(0) r.SetStackDepth(0)
return r return r
} }
// Set the handler in the Logger // Set the handler in the Logger.
func (rl *RevelLogger) SetHandler(h LogHandler) { func (rl *RevelLogger) SetHandler(h LogHandler) {
rl.Logger.SetHandler(callHandler(h.Log)) rl.Logger.SetHandler(callHandler(h.Log))
} }
// The function wrapper to implement the callback // The function wrapper to implement the callback.
type callHandler func(r *Record) error type callHandler func(r *Record) error
// Log implementation, reads the record and extracts the details from the log record // Log implementation, reads the record and extracts the details from the log record
@@ -116,16 +117,16 @@ func (c callHandler) Log(log *log15.Record) error {
ctxMap[key] = value ctxMap[key] = value
} }
} else { } else {
ctxMap = make(ContextMap, 0) ctxMap = make(ContextMap)
} }
r := &Record{Message: log.Msg, Context: ctxMap, Time: log.Time, Level: LogLevel(log.Lvl), Call: CallStack(log.Call)} r := &Record{Message: log.Msg, Context: ctxMap, Time: log.Time, Level: LogLevel(log.Lvl), Call: CallStack(log.Call)}
return c(r) return c(r)
} }
// Internally used contextMap, allows conversion of map to map[string]string // Internally used contextMap, allows conversion of map to map[string]string.
type ContextMap map[string]interface{} type ContextMap map[string]interface{}
// Convert the context map to be string only values, any non string values are ignored // Convert the context map to be string only values, any non string values are ignored.
func (m ContextMap) StringMap() (newMap map[string]string) { func (m ContextMap) StringMap() (newMap map[string]string) {
if m != nil { if m != nil {
newMap = map[string]string{} newMap = map[string]string{}
@@ -137,6 +138,7 @@ func (m ContextMap) StringMap() (newMap map[string]string) {
} }
return return
} }
func (m ContextMap) Add(key string, value interface{}) { func (m ContextMap) Add(key string, value interface{}) {
m[key] = value m[key] = value
} }

View File

@@ -18,13 +18,13 @@ const (
errorKey = "REVEL_ERROR" errorKey = "REVEL_ERROR"
) )
var ( var levelString = map[LogLevel]string{
levelString = map[LogLevel]string{LvlDebug: "DEBUG", LvlDebug: "DEBUG",
LvlInfo: "INFO", LvlWarn: "WARN", LvlError: "ERROR", LvlCrit: "CRIT"} LvlInfo: "INFO", LvlWarn: "WARN", LvlError: "ERROR", LvlCrit: "CRIT",
) }
// Outputs to the terminal in a format like below // Outputs to the terminal in a format like below
// INFO 09:11:32 server-engine.go:169: Request Stats // INFO 09:11:32 server-engine.go:169: Request Stats.
func TerminalFormatHandler(noColor bool, smallDate bool) LogFormat { func TerminalFormatHandler(noColor bool, smallDate bool) LogFormat {
dateFormat := termTimeFormat dateFormat := termTimeFormat
if smallDate { if smallDate {
@@ -32,7 +32,7 @@ func TerminalFormatHandler(noColor bool, smallDate bool) LogFormat {
} }
return FormatFunc(func(r *Record) []byte { return FormatFunc(func(r *Record) []byte {
// Bash coloring http://misc.flogisoft.com/bash/tip_colors_and_formatting // Bash coloring http://misc.flogisoft.com/bash/tip_colors_and_formatting
var color = 0 color := 0
switch r.Level { switch r.Level {
case LvlCrit: case LvlCrit:
// Magenta // Magenta
@@ -54,7 +54,7 @@ func TerminalFormatHandler(noColor bool, smallDate bool) LogFormat {
b := &bytes.Buffer{} b := &bytes.Buffer{}
caller, _ := r.Context["caller"].(string) caller, _ := r.Context["caller"].(string)
module, _ := r.Context["module"].(string) module, _ := r.Context["module"].(string)
if noColor == false && color > 0 { if !noColor && color > 0 {
if len(module) > 0 { if len(module) > 0 {
fmt.Fprintf(b, "\x1b[%dm%-5s\x1b[0m %s %6s %13s: %-40s ", color, levelString[r.Level], r.Time.Format(dateFormat), module, caller, r.Message) fmt.Fprintf(b, "\x1b[%dm%-5s\x1b[0m %s %6s %13s: %-40s ", color, levelString[r.Level], r.Time.Format(dateFormat), module, caller, r.Message)
} else { } else {
@@ -77,7 +77,7 @@ func TerminalFormatHandler(noColor bool, smallDate bool) LogFormat {
v := formatLogfmtValue(v) v := formatLogfmtValue(v)
// TODO: we should probably check that all of your key bytes aren't invalid // TODO: we should probably check that all of your key bytes aren't invalid
if noColor == false && color > 0 { if !noColor && color > 0 {
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m=%s", color, k, v) fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m=%s", color, k, v)
} else { } else {
b.WriteString(k) b.WriteString(k)
@@ -92,7 +92,7 @@ func TerminalFormatHandler(noColor bool, smallDate bool) LogFormat {
}) })
} }
// formatValue formats a value for serialization // formatValue formats a value for serialization.
func formatLogfmtValue(value interface{}) string { func formatLogfmtValue(value interface{}) string {
if value == nil { if value == nil {
return "nil" return "nil"
@@ -121,7 +121,7 @@ func formatLogfmtValue(value interface{}) string {
} }
} }
// Format the value in json format // Format the value in json format.
func formatShared(value interface{}) (result interface{}) { func formatShared(value interface{}) (result interface{}) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
@@ -148,12 +148,12 @@ func formatShared(value interface{}) (result interface{}) {
} }
} }
// A reusuable buffer for outputting data // A reusuable buffer for outputting data.
var stringBufPool = sync.Pool{ var stringBufPool = sync.Pool{
New: func() interface{} { return new(bytes.Buffer) }, New: func() interface{} { return new(bytes.Buffer) },
} }
// Escape the string when needed // Escape the string when needed.
func escapeString(s string) string { func escapeString(s string) string {
needsQuotes := false needsQuotes := false
needsEscape := false needsEscape := false
@@ -165,7 +165,7 @@ func escapeString(s string) string {
needsEscape = true needsEscape = true
} }
} }
if needsEscape == false && needsQuotes == false { if !needsEscape && !needsQuotes {
return s return s
} }
e := stringBufPool.Get().(*bytes.Buffer) e := stringBufPool.Get().(*bytes.Buffer)
@@ -215,7 +215,7 @@ func JsonFormatEx(pretty, lineSeparated bool) LogFormat {
props["lvl"] = levelString[r.Level] props["lvl"] = levelString[r.Level]
props["msg"] = r.Message props["msg"] = r.Message
for k, v := range r.Context { for k, v := range r.Context {
props[k] = formatJsonValue(v) props[k] = formatJSONValue(v)
} }
b, err := jsonMarshal(props) b, err := jsonMarshal(props)
@@ -234,7 +234,7 @@ func JsonFormatEx(pretty, lineSeparated bool) LogFormat {
}) })
} }
func formatJsonValue(value interface{}) interface{} { func formatJSONValue(value interface{}) interface{} {
value = formatShared(value) value = formatShared(value)
switch value.(type) { switch value.(type) {
case int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64, string: case int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64, string:

View File

@@ -1,15 +1,17 @@
package logger package logger
import ( import (
"log"
"github.com/revel/log15" "github.com/revel/log15"
"gopkg.in/stack.v0" "gopkg.in/stack.v0"
"log"
) )
// Utility package to make existing logging backwards compatible // Utility package to make existing logging backwards compatible.
var ( var (
// Convert the string to LogLevel // Convert the string to LogLevel.
toLevel = map[string]LogLevel{"debug": LogLevel(log15.LvlDebug), toLevel = map[string]LogLevel{
"debug": LogLevel(log15.LvlDebug),
"info": LogLevel(log15.LvlInfo), "request": LogLevel(log15.LvlInfo), "warn": LogLevel(log15.LvlWarn), "info": LogLevel(log15.LvlInfo), "request": LogLevel(log15.LvlInfo), "warn": LogLevel(log15.LvlWarn),
"error": LogLevel(log15.LvlError), "crit": LogLevel(log15.LvlCrit), "error": LogLevel(log15.LvlError), "crit": LogLevel(log15.LvlCrit),
"trace": LogLevel(log15.LvlDebug), // TODO trace is deprecated, replaced by debug "trace": LogLevel(log15.LvlDebug), // TODO trace is deprecated, replaced by debug
@@ -17,13 +19,13 @@ var (
) )
const ( const (
// The test mode flag overrides the default log level and shows only errors // The test mode flag overrides the default log level and shows only errors.
TEST_MODE_FLAG = "testModeFlag" TEST_MODE_FLAG = "testModeFlag"
// The special use flag enables showing messages when the logger is setup // The special use flag enables showing messages when the logger is setup.
SPECIAL_USE_FLAG = "specialUseFlag" SPECIAL_USE_FLAG = "specialUseFlag"
) )
// Returns the logger for the name // Returns the logger for the name.
func GetLogger(name string, logger MultiLogger) (l *log.Logger) { func GetLogger(name string, logger MultiLogger) (l *log.Logger) {
switch name { switch name {
case "trace": // TODO trace is deprecated, replaced by debug case "trace": // TODO trace is deprecated, replaced by debug
@@ -41,10 +43,9 @@ func GetLogger(name string, logger MultiLogger) (l *log.Logger) {
} }
return l return l
} }
// Used by the initFilterLog to handle the filters // Used by the initFilterLog to handle the filters.
var logFilterList = []struct { var logFilterList = []struct {
LogPrefix, LogSuffix string LogPrefix, LogSuffix string
parentHandler func(map[string]interface{}) ParentLogHandler parentHandler func(map[string]interface{}) ParentLogHandler
@@ -54,7 +55,6 @@ var logFilterList = []struct {
return NewParentLogHandler(func(child LogHandler) LogHandler { return NewParentLogHandler(func(child LogHandler) LogHandler {
return MatchMapHandler(keyMap, child) return MatchMapHandler(keyMap, child)
}) })
}, },
}, { }, {
"log.", ".nfilter", "log.", ".nfilter",
@@ -65,20 +65,20 @@ var logFilterList = []struct {
}, },
}} }}
// This structure and method will handle the old output format and log it to the new format // This structure and method will handle the old output format and log it to the new format.
type loggerRewrite struct { type loggerRewrite struct {
Logger MultiLogger Logger MultiLogger
Level log15.Lvl Level log15.Lvl
hideDeprecated bool hideDeprecated bool
} }
// The message indicating that a logger is using a deprecated log mechanism // The message indicating that a logger is using a deprecated log mechanism.
var log_deprecated = []byte("* LOG DEPRECATED * ") var logDeprecated = []byte("* LOG DEPRECATED * ")
// Implements the Write of the logger // Implements the Write of the logger.
func (lr loggerRewrite) Write(p []byte) (n int, err error) { func (lr loggerRewrite) Write(p []byte) (n int, err error) {
if !lr.hideDeprecated { if !lr.hideDeprecated {
p = append(log_deprecated, p...) p = append(logDeprecated, p...)
} }
n = len(p) n = len(p)
if len(p) > 0 && p[n-1] == '\n' { if len(p) > 0 && p[n-1] == '\n' {
@@ -104,7 +104,7 @@ func (lr loggerRewrite) Write(p []byte) (n int, err error) {
// For logging purposes the call stack can be used to record the stack trace of a bad error // For logging purposes the call stack can be used to record the stack trace of a bad error
// simply pass it as a context field in your log statement like // simply pass it as a context field in your log statement like
// `controller.Log.Crit("This should not occur","stack",revel.NewCallStack())` // `controller.Log.Crit("This should not occur","stack",revel.NewCallStack())`.
func NewCallStack() interface{} { func NewCallStack() interface{} {
return stack.Trace() return stack.Trace()
} }

View File

@@ -9,29 +9,29 @@ import (
"time" "time"
) )
// Function handler wraps the declared function and returns the handler for it // Function handler wraps the declared function and returns the handler for it.
func FuncHandler(fn func(r *Record) error) LogHandler { func FuncHandler(fn func(r *Record) error) LogHandler {
return funcHandler(fn) return funcHandler(fn)
} }
// The type decleration for the function // The type declaration for the function.
type funcHandler func(r *Record) error type funcHandler func(r *Record) error
// The implementation of the Log // The implementation of the Log.
func (h funcHandler) Log(r *Record) error { func (h funcHandler) Log(r *Record) error {
return h(r) return h(r)
} }
// This function allows you to do a full declaration for the log, // This function allows you to do a full declaration for the log,
// it is recommended you use FuncHandler instead // it is recommended you use FuncHandler instead.
func HandlerFunc(log func(message string, time time.Time, level LogLevel, call CallStack, context ContextMap) error) LogHandler { func HandlerFunc(log func(message string, time time.Time, level LogLevel, call CallStack, context ContextMap) error) LogHandler {
return remoteHandler(log) return remoteHandler(log)
} }
// The type used for the HandlerFunc // The type used for the HandlerFunc.
type remoteHandler func(message string, time time.Time, level LogLevel, call CallStack, context ContextMap) error type remoteHandler func(message string, time time.Time, level LogLevel, call CallStack, context ContextMap) error
// The Log implementation // The Log implementation.
func (c remoteHandler) Log(record *Record) error { func (c remoteHandler) Log(record *Record) error {
return c(record.Message, record.Time, record.Level, record.Call, record.Context) return c(record.Message, record.Time, record.Level, record.Call, record.Context)
} }
@@ -56,11 +56,9 @@ func LazyHandler(h LogHandler) LogHandler {
return FuncHandler(func(r *Record) error { return FuncHandler(func(r *Record) error {
for k, v := range r.Context { for k, v := range r.Context {
if lz, ok := v.(Lazy); ok { if lz, ok := v.(Lazy); ok {
value, err := evaluateLazy(lz) _, err := evaluateLazy(lz)
if err != nil { if err != nil {
r.Context[errorKey] = "bad lazy " + k r.Context[errorKey] = "bad lazy " + k
} else {
v = value
} }
} }
} }
@@ -88,11 +86,12 @@ func evaluateLazy(lz Lazy) (interface{}, error) {
results := value.Call([]reflect.Value{}) results := value.Call([]reflect.Value{})
if len(results) == 1 { if len(results) == 1 {
return results[0].Interface(), nil return results[0].Interface(), nil
} else { }
values := make([]interface{}, len(results)) values := make([]interface{}, len(results))
for i, v := range results { for i, v := range results {
values[i] = v.Interface() values[i] = v.Interface()
} }
return values, nil return values, nil
} }
}

View File

@@ -1,4 +1,5 @@
package command package command
type ( type (
Build struct { Build struct {
ImportCommand ImportCommand
@@ -6,5 +7,4 @@ type (
Mode string `short:"m" long:"run-mode" description:"The mode to run the application in"` Mode string `short:"m" long:"run-mode" description:"The mode to run the application in"`
CopySource bool `short:"s" long:"include-source" description:"Copy the source code as well"` CopySource bool `short:"s" long:"include-source" description:"Copy the source code as well"`
} }
) )

View File

@@ -1,4 +1,5 @@
package command package command
type ( type (
Clean struct { Clean struct {
ImportCommand ImportCommand

View File

@@ -1,6 +1,5 @@
package command package command
type ( type (
New struct { New struct {
ImportCommand ImportCommand
@@ -10,5 +9,4 @@ type (
Run bool `short:"r" long:"run" description:"True if you want to run the application right away"` Run bool `short:"r" long:"run" description:"True if you want to run the application right away"`
Callback func() error Callback func() error
} }
) )

View File

@@ -1,4 +1,5 @@
package command package command
type ( type (
Package struct { Package struct {
ImportCommand ImportCommand

View File

@@ -1,4 +1,5 @@
package command package command
type ( type (
Run struct { Run struct {
ImportCommand ImportCommand

View File

@@ -1,4 +1,5 @@
package command package command
type ( type (
Version struct { Version struct {
ImportCommand ImportCommand

View File

@@ -2,8 +2,6 @@ package model
import ( import (
"fmt" "fmt"
"github.com/revel/cmd"
"github.com/revel/cmd/utils"
"go/ast" "go/ast"
"go/build" "go/build"
"go/parser" "go/parser"
@@ -13,10 +11,13 @@ import (
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/revel/cmd"
"github.com/revel/cmd/model/command" "github.com/revel/cmd/model/command"
"github.com/revel/cmd/utils"
) )
// The constants // The constants.
const ( const (
NEW COMMAND = iota + 1 NEW COMMAND = iota + 1
RUN RUN
@@ -28,10 +29,10 @@ const (
) )
type ( type (
// The Revel command type // The Revel command type.
COMMAND int COMMAND int
// The Command config for the line input // The Command config for the line input.
CommandConfig struct { CommandConfig struct {
Index COMMAND // The index Index COMMAND // The index
Verbose []bool `short:"v" long:"debug" description:"If set the logger is set to verbose"` // True if debug is active Verbose []bool `short:"v" long:"debug" description:"If set the logger is set to verbose"` // True if debug is active
@@ -59,7 +60,7 @@ type (
} }
) )
// Updates the import path depending on the command // Updates the import path depending on the command.
func (c *CommandConfig) UpdateImportPath() error { func (c *CommandConfig) UpdateImportPath() error {
var importPath string var importPath string
required := true required := true
@@ -109,7 +110,7 @@ func (c *CommandConfig) UpdateImportPath() error {
importPath = importPath[4:] importPath = importPath[4:]
} else if importPath == "src" { } else if importPath == "src" {
if c.Index != VERSION { if c.Index != VERSION {
return fmt.Errorf("Invlaid import path, working dir is in GOPATH root") return fmt.Errorf("invalid import path, working dir is in GOPATH root")
} }
importPath = "" importPath = ""
} }
@@ -137,7 +138,7 @@ func (c *CommandConfig) UpdateImportPath() error {
return nil return nil
} }
if len(importPath) == 0 { if len(importPath) == 0 {
return fmt.Errorf("Unable to determine import path from : %s", importPath) return fmt.Errorf("unable to determine import path from : %s", importPath)
} }
return nil return nil
} }
@@ -153,7 +154,7 @@ func (c *CommandConfig) initAppFolder() (err error) {
// First try to determine where the application is located - this should be the import value // First try to determine where the application is located - this should be the import value
appFolder := c.ImportPath appFolder := c.ImportPath
wd, err := os.Getwd() wd, _ := os.Getwd()
if len(appFolder) == 0 { if len(appFolder) == 0 {
// We will assume the working directory is the appFolder // We will assume the working directory is the appFolder
appFolder = wd appFolder = wd
@@ -216,7 +217,6 @@ func (c *CommandConfig) initAppFolder() (err error) {
c.AppPath = filepath.Join(bestpath, "src", c.ImportPath) c.AppPath = filepath.Join(bestpath, "src", c.ImportPath)
} }
// Recalculate the appFolder because we are using a GOPATH // Recalculate the appFolder because we are using a GOPATH
} else { } else {
// This is new and not vendored, so the app path is the appFolder // This is new and not vendored, so the app path is the appFolder
c.AppPath = appFolder c.AppPath = appFolder
@@ -226,7 +226,7 @@ func (c *CommandConfig) initAppFolder() (err error) {
return nil return nil
} }
// Used to initialize the package resolver // Used to initialize the package resolver.
func (c *CommandConfig) InitPackageResolver() { func (c *CommandConfig) InitPackageResolver() {
c.initGoPaths() c.initGoPaths()
utils.Logger.Info("InitPackageResolver", "useVendor", c.Vendored, "path", c.AppPath) utils.Logger.Info("InitPackageResolver", "useVendor", c.Vendored, "path", c.AppPath)
@@ -255,7 +255,7 @@ func (c *CommandConfig) InitPackageResolver() {
} }
} }
// lookup and set Go related variables // lookup and set Go related variables.
func (c *CommandConfig) initGoPaths() { func (c *CommandConfig) initGoPaths() {
utils.Logger.Info("InitGoPaths", "vendored", c.Vendored) utils.Logger.Info("InitGoPaths", "vendored", c.Vendored)
// check for go executable // check for go executable
@@ -275,10 +275,7 @@ func (c *CommandConfig) initGoPaths() {
utils.Logger.Fatal("Abort: GOPATH environment variable is not set. " + utils.Logger.Fatal("Abort: GOPATH environment variable is not set. " +
"Please refer to http://golang.org/doc/code.html to configure your Go environment.") "Please refer to http://golang.org/doc/code.html to configure your Go environment.")
} }
return
// todo determine if the rest needs to happen // todo determine if the rest needs to happen
// revel/revel#1004 choose go path relative to current working directory // revel/revel#1004 choose go path relative to current working directory
// What we want to do is to add the import to the end of the // What we want to do is to add the import to the end of the
@@ -304,10 +301,9 @@ func (c *CommandConfig) initGoPaths() {
utils.Logger.Info("Set application path", "path", c.AppPath) utils.Logger.Info("Set application path", "path", c.AppPath)
*/ */
} }
// Sets the versions on the command config // Sets the versions on the command config.
func (c *CommandConfig) SetVersions() (err error) { func (c *CommandConfig) SetVersions() (err error) {
c.CommandVersion, _ = ParseVersion(cmd.Version) c.CommandVersion, _ = ParseVersion(cmd.Version)
pathMap, err := utils.FindSrcPaths(c.AppPath, []string{RevelImportPath}, c.PackageResolver) pathMap, err := utils.FindSrcPaths(c.AppPath, []string{RevelImportPath}, c.PackageResolver)
@@ -339,7 +335,7 @@ func (c *CommandConfig) SetVersions() (err error) {
spec := a.(*ast.ValueSpec) spec := a.(*ast.ValueSpec)
r := spec.Values[0].(*ast.BasicLit) r := spec.Values[0].(*ast.BasicLit)
if spec.Names[0].Name == "Version" { if spec.Names[0].Name == "Version" {
c.FrameworkVersion, err = ParseVersion(strings.Replace(r.Value, `"`, ``, -1)) c.FrameworkVersion, err = ParseVersion(strings.ReplaceAll(r.Value, `"`, ``))
if err != nil { if err != nil {
utils.Logger.Errorf("Failed to parse version") utils.Logger.Errorf("Failed to parse version")
} else { } else {

View File

@@ -1,11 +1,11 @@
package model package model
// The embedded type name takes the import path and structure name // The embedded type name takes the import path and structure name.
type EmbeddedTypeName struct { type EmbeddedTypeName struct {
ImportPath, StructName string ImportPath, StructName string
} }
// Convert the type to a properly formatted import line // Convert the type to a properly formatted import line.
func (s *EmbeddedTypeName) String() string { func (s *EmbeddedTypeName) String() string {
return s.ImportPath + "." + s.StructName return s.ImportPath + "." + s.StructName
} }

View File

@@ -1,11 +1,11 @@
package model package model
type ( type (
// The event type // The event type.
Event int Event int
// The event response // The event response.
EventResponse int EventResponse int
// The handler signature // The handler signature.
EventHandler func(typeOf Event, value interface{}) (responseOf EventResponse) EventHandler func(typeOf Event, value interface{}) (responseOf EventResponse)
RevelCallback interface { RevelCallback interface {
FireEvent(key Event, value interface{}) (response EventResponse) FireEvent(key Event, value interface{}) (response EventResponse)
@@ -14,40 +14,40 @@ type (
) )
const ( const (
// Event type when templates are going to be refreshed (receivers are registered template engines added to the template.engine conf option) // Event type when templates are going to be refreshed (receivers are registered template engines added to the template.engine conf option).
TEMPLATE_REFRESH_REQUESTED Event = iota TEMPLATE_REFRESH_REQUESTED Event = iota
// Event type when templates are refreshed (receivers are registered template engines added to the template.engine conf option) // Event type when templates are refreshed (receivers are registered template engines added to the template.engine conf option).
TEMPLATE_REFRESH_COMPLETED TEMPLATE_REFRESH_COMPLETED
// Event type before all module loads, events thrown to handlers added to AddInitEventHandler // Event type before all module loads, events thrown to handlers added to AddInitEventHandler.
// Event type before all module loads, events thrown to handlers added to AddInitEventHandler // Event type before all module loads, events thrown to handlers added to AddInitEventHandler.
REVEL_BEFORE_MODULES_LOADED REVEL_BEFORE_MODULES_LOADED
// Event type before module loads, events thrown to handlers added to AddInitEventHandler // Event type before module loads, events thrown to handlers added to AddInitEventHandler.
REVEL_BEFORE_MODULE_LOADED REVEL_BEFORE_MODULE_LOADED
// Event type after module loads, events thrown to handlers added to AddInitEventHandler // Event type after module loads, events thrown to handlers added to AddInitEventHandler.
REVEL_AFTER_MODULE_LOADED REVEL_AFTER_MODULE_LOADED
// Event type after all module loads, events thrown to handlers added to AddInitEventHandler // Event type after all module loads, events thrown to handlers added to AddInitEventHandler.
REVEL_AFTER_MODULES_LOADED REVEL_AFTER_MODULES_LOADED
// Event type before server engine is initialized, receivers are active server engine and handlers added to AddInitEventHandler // Event type before server engine is initialized, receivers are active server engine and handlers added to AddInitEventHandler.
ENGINE_BEFORE_INITIALIZED ENGINE_BEFORE_INITIALIZED
// Event type before server engine is started, receivers are active server engine and handlers added to AddInitEventHandler // Event type before server engine is started, receivers are active server engine and handlers added to AddInitEventHandler.
ENGINE_STARTED ENGINE_STARTED
// Event type after server engine is stopped, receivers are active server engine and handlers added to AddInitEventHandler // Event type after server engine is stopped, receivers are active server engine and handlers added to AddInitEventHandler.
ENGINE_SHUTDOWN ENGINE_SHUTDOWN
// Called before routes are refreshed // Called before routes are refreshed.
ROUTE_REFRESH_REQUESTED ROUTE_REFRESH_REQUESTED
// Called after routes have been refreshed // Called after routes have been refreshed.
ROUTE_REFRESH_COMPLETED ROUTE_REFRESH_COMPLETED
// Fired when a panic is caught during the startup process // Fired when a panic is caught during the startup process.
REVEL_FAILURE REVEL_FAILURE
) )
var initEventList = []EventHandler{} // Event handler list for receiving events var initEventList = []EventHandler{} // Event handler list for receiving events
// Fires system events from revel // Fires system events from revel.
func RaiseEvent(key Event, value interface{}) (response EventResponse) { func RaiseEvent(key Event, value interface{}) (response EventResponse) {
for _, handler := range initEventList { for _, handler := range initEventList {
response |= handler(key, value) response |= handler(key, value)
@@ -55,8 +55,7 @@ func RaiseEvent(key Event, value interface{}) (response EventResponse) {
return return
} }
// Add event handler to listen for all system events // Add event handler to listen for all system events.
func AddInitEventHandler(handler EventHandler) { func AddInitEventHandler(handler EventHandler) {
initEventList = append(initEventList, handler) initEventList = append(initEventList, handler)
return
} }

View File

@@ -1,12 +1,13 @@
package model_test package model_test
import ( import (
"testing"
"github.com/revel/revel" "github.com/revel/revel"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"testing"
) )
// Test that the event handler can be attached and it dispatches the event received // Test that the event handler can be attached and it dispatches the event received.
func TestEventHandler(t *testing.T) { func TestEventHandler(t *testing.T) {
counter := 0 counter := 0
newListener := func(typeOf revel.Event, value interface{}) (responseOf revel.EventResponse) { newListener := func(typeOf revel.Event, value interface{}) (responseOf revel.EventResponse) {
@@ -21,4 +22,3 @@ func TestEventHandler(t *testing.T) {
revel.StopServer(1) revel.StopServer(1)
assert.Equal(t, counter, 2, "Expected event handler to have been called") assert.Equal(t, counter, 2, "Expected event handler to have been called")
} }

View File

@@ -8,14 +8,14 @@ type MethodCall struct {
Names []string Names []string
} }
// MethodSpec holds the information of one Method // MethodSpec holds the information of one Method.
type MethodSpec struct { type MethodSpec struct {
Name string // Name of the method, e.g. "Index" Name string // Name of the method, e.g. "Index"
Args []*MethodArg // Argument descriptors Args []*MethodArg // Argument descriptors
RenderCalls []*MethodCall // Descriptions of Render() invocations from this Method. RenderCalls []*MethodCall // Descriptions of Render() invocations from this Method.
} }
// MethodArg holds the information of one argument // MethodArg holds the information of one argument.
type MethodArg struct { type MethodArg struct {
Name string // Name of the argument. Name string // Name of the argument.
TypeExpr TypeExpr // The name of the type, e.g. "int", "*pkg.UserType" TypeExpr TypeExpr // The name of the type, e.g. "int", "*pkg.UserType"

View File

@@ -2,18 +2,19 @@
package model package model
import ( import (
"github.com/revel/cmd/utils"
"github.com/revel/config"
"errors" "errors"
"fmt" "fmt"
"path/filepath" "path/filepath"
"sort" "sort"
"strings" "strings"
"github.com/revel/cmd/utils"
"github.com/revel/config"
"golang.org/x/tools/go/packages" "golang.org/x/tools/go/packages"
) )
type ( type (
// The container object for describing all Revels variables // The container object for describing all Revels variables.
RevelContainer struct { RevelContainer struct {
BuildPaths struct { BuildPaths struct {
Revel string Revel string
@@ -77,25 +78,28 @@ type (
} }
) )
// Simple Wrapped RevelCallback // Simple Wrapped RevelCallback.
func NewWrappedRevelCallback(fe func(key Event, value interface{}) (response EventResponse), ie func(pkgName string) error) RevelCallback { func NewWrappedRevelCallback(fe func(key Event, value interface{}) (response EventResponse), ie func(pkgName string) error) RevelCallback {
return &WrappedRevelCallback{fe, ie} return &WrappedRevelCallback{fe, ie}
} }
// Function to implement the FireEvent // Function to implement the FireEvent.
func (w *WrappedRevelCallback) FireEvent(key Event, value interface{}) (response EventResponse) { func (w *WrappedRevelCallback) FireEvent(key Event, value interface{}) (response EventResponse) {
if w.FireEventFunction != nil { if w.FireEventFunction != nil {
response = w.FireEventFunction(key, value) response = w.FireEventFunction(key, value)
} }
return return
} }
func (w *WrappedRevelCallback) PackageResolver(pkgName string) error { func (w *WrappedRevelCallback) PackageResolver(pkgName string) error {
return w.ImportFunction(pkgName) return w.ImportFunction(pkgName)
} }
// RevelImportPath Revel framework import path // RevelImportPath Revel framework import path.
var RevelImportPath = "github.com/revel/revel" var (
var RevelModulesImportPath = "github.com/revel/modules" RevelImportPath = "github.com/revel/revel"
RevelModulesImportPath = "github.com/revel/modules"
)
// This function returns a container object describing the revel application // This function returns a container object describing the revel application
// eventually this type of function will replace the global variables. // eventually this type of function will replace the global variables.
@@ -119,10 +123,10 @@ func NewRevelPaths(mode, importPath, appSrcPath string, callback RevelCallback)
// Sanity check , ensure app and conf paths exist // Sanity check , ensure app and conf paths exist
if !utils.DirExists(rp.AppPath) { if !utils.DirExists(rp.AppPath) {
return rp, fmt.Errorf("No application found at path %s", rp.AppPath) return rp, fmt.Errorf("no application found at path %s", rp.AppPath)
} }
if !utils.DirExists(filepath.Join(rp.BasePath, "conf")) { if !utils.DirExists(filepath.Join(rp.BasePath, "conf")) {
return rp, fmt.Errorf("No configuration found at path %s", filepath.Join(rp.BasePath, "conf")) return rp, fmt.Errorf("no configuration found at path %s", filepath.Join(rp.BasePath, "conf"))
} }
rp.ViewsPath = filepath.Join(rp.AppPath, "views") rp.ViewsPath = filepath.Join(rp.AppPath, "views")
@@ -146,7 +150,7 @@ func NewRevelPaths(mode, importPath, appSrcPath string, callback RevelCallback)
rp.Config, err = config.LoadContext("app.conf", rp.ConfPaths) rp.Config, err = config.LoadContext("app.conf", rp.ConfPaths)
if err != nil { if err != nil {
return rp, fmt.Errorf("Unable to load configuartion file %s", err) return rp, fmt.Errorf("unable to load configuration file %s", err)
} }
// Ensure that the selected runmode appears in app.conf. // Ensure that the selected runmode appears in app.conf.
@@ -168,10 +172,10 @@ func NewRevelPaths(mode, importPath, appSrcPath string, callback RevelCallback)
rp.HTTPSslKey = rp.Config.StringDefault("http.sslkey", "") rp.HTTPSslKey = rp.Config.StringDefault("http.sslkey", "")
if rp.HTTPSsl { if rp.HTTPSsl {
if rp.HTTPSslCert == "" { if rp.HTTPSslCert == "" {
return rp, errors.New("No http.sslcert provided.") return rp, errors.New("no http.sslcert provided")
} }
if rp.HTTPSslKey == "" { if rp.HTTPSslKey == "" {
return rp, errors.New("No http.sslkey provided.") return rp, errors.New("no http.sslkey provided")
} }
} }
// //
@@ -197,7 +201,7 @@ func NewRevelPaths(mode, importPath, appSrcPath string, callback RevelCallback)
func (rp *RevelContainer) LoadMimeConfig() (err error) { func (rp *RevelContainer) LoadMimeConfig() (err error) {
rp.MimeConfig, err = config.LoadContext("mime-types.conf", rp.ConfPaths) rp.MimeConfig, err = config.LoadContext("mime-types.conf", rp.ConfPaths)
if err != nil { if err != nil {
return fmt.Errorf("Failed to load mime type config: %s %s", "error", err) return fmt.Errorf("failed to load mime type config: %s %s", "error", err)
} }
return return
} }
@@ -206,12 +210,10 @@ func (rp *RevelContainer) LoadMimeConfig() (err error) {
// This will fire the REVEL_BEFORE_MODULE_LOADED, REVEL_AFTER_MODULE_LOADED // This will fire the REVEL_BEFORE_MODULE_LOADED, REVEL_AFTER_MODULE_LOADED
// for each module loaded. The callback will receive the RevelContainer, name, moduleImportPath and modulePath // for each module loaded. The callback will receive the RevelContainer, name, moduleImportPath and modulePath
// It will automatically add in the code paths for the module to the // It will automatically add in the code paths for the module to the
// container object // container object.
func (rp *RevelContainer) loadModules(callback RevelCallback) (err error) { func (rp *RevelContainer) loadModules(callback RevelCallback) (err error) {
keys := []string{} keys := []string{}
for _, key := range rp.Config.Options("module.") { keys = append(keys, rp.Config.Options("module.")...)
keys = append(keys, key)
}
// Reorder module order by key name, a poor mans sort but at least it is consistent // Reorder module order by key name, a poor mans sort but at least it is consistent
sort.Strings(keys) sort.Strings(keys)
@@ -227,7 +229,7 @@ func (rp *RevelContainer) loadModules(callback RevelCallback) (err error) {
callback.PackageResolver(moduleImportPath) callback.PackageResolver(moduleImportPath)
modulePath, err = rp.ResolveImportPath(moduleImportPath) modulePath, err = rp.ResolveImportPath(moduleImportPath)
if err != nil { if err != nil {
return fmt.Errorf("Failed to load module. Import of path failed %s:%s %s:%s ", "modulePath", moduleImportPath, "error", err) return fmt.Errorf("failed to load module. Import of path failed %s:%s %s:%s ", "modulePath", moduleImportPath, "error", err)
} }
} }
// Drop anything between module.???.<name of module> // Drop anything between module.???.<name of module>
@@ -242,7 +244,7 @@ func (rp *RevelContainer) loadModules(callback RevelCallback) (err error) {
return return
} }
// Adds a module paths to the container object // Adds a module paths to the container object.
func (rp *RevelContainer) addModulePaths(name, importPath, modulePath string) { func (rp *RevelContainer) addModulePaths(name, importPath, modulePath string) {
utils.Logger.Info("Adding module path", "name", name, "import path", importPath, "system path", modulePath) utils.Logger.Info("Adding module path", "name", name, "import path", importPath, "system path", modulePath)
if codePath := filepath.Join(modulePath, "app"); utils.DirExists(codePath) { if codePath := filepath.Join(modulePath, "app"); utils.DirExists(codePath) {
@@ -271,6 +273,8 @@ func (rp *RevelContainer) ResolveImportPath(importPath string) (string, error) {
return filepath.Join(rp.SourcePath, importPath), nil return filepath.Join(rp.SourcePath, importPath), nil
} }
config := &packages.Config{ config := &packages.Config{
// TODO: packages.LoadSyntax deprecated, Need instead
//nolint:staticcheck
Mode: packages.LoadSyntax, Mode: packages.LoadSyntax,
Dir: rp.AppPath, Dir: rp.AppPath,
} }

View File

@@ -3,10 +3,11 @@ package model
// SourceInfo is the top-level struct containing all extracted information // SourceInfo is the top-level struct containing all extracted information
// about the app source code, used to generate main.go. // about the app source code, used to generate main.go.
import ( import (
"github.com/revel/cmd/utils"
"path/filepath" "path/filepath"
"strings" "strings"
"unicode" "unicode"
"github.com/revel/cmd/utils"
) )
type SourceInfo struct { type SourceInfo struct {
@@ -35,7 +36,7 @@ type SourceInfo struct {
// TypesThatEmbed returns all types that (directly or indirectly) embed the // TypesThatEmbed returns all types that (directly or indirectly) embed the
// target type, which must be a fully qualified type name, // target type, which must be a fully qualified type name,
// e.g. "github.com/revel/revel.Controller" // e.g. "github.com/revel/revel.Controller".
func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered []*TypeInfo) { func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered []*TypeInfo) {
// Do a search in the "embedded type graph", starting with the target type. // Do a search in the "embedded type graph", starting with the target type.
var ( var (
@@ -76,6 +77,7 @@ func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered
"type", filteredItem.StructName, "type", filteredItem.StructName,
"package", filteredItem.ImportPath) "package", filteredItem.ImportPath)
filtered = append(filtered[:i], filtered[i+1:]...) filtered = append(filtered[:i], filtered[i+1:]...)
//nolint:ineffassign // huh?
exit = false exit = false
break break
} }
@@ -108,7 +110,7 @@ func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered
} }
// ControllerSpecs returns the all the controllers that embeds // ControllerSpecs returns the all the controllers that embeds
// `revel.Controller` // `revel.Controller`.
func (s *SourceInfo) ControllerSpecs() []*TypeInfo { func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
utils.Logger.Info("Scanning controller specifications for types ", "typePath", RevelImportPath+".Controller", "speclen", len(s.controllerSpecs)) utils.Logger.Info("Scanning controller specifications for types ", "typePath", RevelImportPath+".Controller", "speclen", len(s.controllerSpecs))
if s.controllerSpecs == nil { if s.controllerSpecs == nil {
@@ -118,7 +120,7 @@ func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
} }
// TestSuites returns the all the Application tests that embeds // TestSuites returns the all the Application tests that embeds
// `testing.TestSuite` // `testing.TestSuite`.
func (s *SourceInfo) TestSuites() []*TypeInfo { func (s *SourceInfo) TestSuites() []*TypeInfo {
if s.testSuites == nil { if s.testSuites == nil {
s.testSuites = s.TypesThatEmbed(RevelImportPath+"/testing.TestSuite", "testsuite") s.testSuites = s.TypesThatEmbed(RevelImportPath+"/testing.TestSuite", "testsuite")

View File

@@ -13,7 +13,7 @@ type TypeExpr struct {
Valid bool Valid bool
} }
// Returns a new type from the data // Returns a new type from the data.
func NewTypeExprFromData(expr, pkgName string, pkgIndex int, valid bool) TypeExpr { func NewTypeExprFromData(expr, pkgName string, pkgIndex int, valid bool) TypeExpr {
return TypeExpr{expr, pkgName, pkgIndex, valid} return TypeExpr{expr, pkgName, pkgIndex, valid}
} }
@@ -47,7 +47,6 @@ func NewTypeExprFromAst(pkgName string, expr ast.Expr) TypeExpr {
return NewTypeExprFromData("[]"+e.Expr, e.PkgName, e.pkgIndex+2, e.Valid) return NewTypeExprFromData("[]"+e.Expr, e.PkgName, e.pkgIndex+2, e.Valid)
default: default:
error = fmt.Sprintf("Failed to generate name for field: %v Package: %v. Make sure the field name is valid.", expr, pkgName) error = fmt.Sprintf("Failed to generate name for field: %v Package: %v. Make sure the field name is valid.", expr, pkgName)
} }
return NewTypeExprFromData(error, "", 0, false) return NewTypeExprFromData(error, "", 0, false)
} }
@@ -85,13 +84,13 @@ var builtInTypes = map[string]struct{}{
"uintptr": {}, "uintptr": {},
} }
// IsBuiltinType checks the given type is built-in types of Go // IsBuiltinType checks the given type is built-in types of Go.
func IsBuiltinType(name string) bool { func IsBuiltinType(name string) bool {
_, ok := builtInTypes[name] _, ok := builtInTypes[name]
return ok return ok
} }
// Returns the first non empty string from a list of arguements // Returns the first non empty string from a list of arguments.
func FirstNonEmpty(strs ...string) string { func FirstNonEmpty(strs ...string) string {
for _, str := range strs { for _, str := range strs {
if len(str) > 0 { if len(str) > 0 {

View File

@@ -9,7 +9,7 @@ type TypeInfo struct {
EmbeddedTypes []*EmbeddedTypeName // Used internally to identify controllers that indirectly embed *revel.Controller. EmbeddedTypes []*EmbeddedTypeName // Used internally to identify controllers that indirectly embed *revel.Controller.
} }
// Return the type information as a properly formatted import string // Return the type information as a properly formatted import string.
func (s *TypeInfo) String() string { func (s *TypeInfo) String() string {
return s.ImportPath + "." + s.StructName return s.ImportPath + "." + s.StructName
} }

View File

@@ -2,9 +2,10 @@ package model
import ( import (
"fmt" "fmt"
"github.com/pkg/errors"
"regexp" "regexp"
"strconv" "strconv"
"github.com/pkg/errors"
) )
type Version struct { type Version struct {
@@ -17,26 +18,24 @@ type Version struct {
MinGoVersion string MinGoVersion string
} }
// The compatibility list // The compatibility list.
var frameworkCompatibleRangeList = [][]string{ var frameworkCompatibleRangeList = [][]string{
{"0.0.0", "0.20.0"}, // minimum Revel version to use with this version of the tool {"0.0.0", "0.20.0"}, // minimum Revel version to use with this version of the tool
{"0.19.99", "0.30.0"}, // Compatible with Framework V 0.19.99 - 0.30.0 {"0.19.99", "0.30.0"}, // Compatible with Framework V 0.19.99 - 0.30.0
{"1.0.0", "1.9.0"}, // Compatible with Framework V 1.0 - 1.9 {"1.0.0", "1.9.0"}, // Compatible with Framework V 1.0 - 1.9
} }
// Parses a version like v1.2.3a or 1.2 // Parses a version like v1.2.3a or 1.2.
var versionRegExp = regexp.MustCompile(`([^\d]*)?([0-9]*)\.([0-9]*)(\.([0-9]*))?(.*)`) var versionRegExp = regexp.MustCompile(`([^\d]*)?([0-9]*)\.([0-9]*)(\.([0-9]*))?(.*)`)
// Parse the version and return it as a Version object // Parse the version and return it as a Version object.
func ParseVersion(version string) (v *Version, err error) { func ParseVersion(version string) (v *Version, err error) {
v = &Version{} v = &Version{}
return v, v.ParseVersion(version) return v, v.ParseVersion(version)
} }
// Parse the version and return it as a Version object // Parse the version and return it as a Version object.
func (v *Version) ParseVersion(version string) (err error) { func (v *Version) ParseVersion(version string) (err error) {
parsedResult := versionRegExp.FindAllStringSubmatch(version, -1) parsedResult := versionRegExp.FindAllStringSubmatch(version, -1)
if len(parsedResult) != 1 { if len(parsedResult) != 1 {
err = errors.Errorf("Invalid version %s", version) err = errors.Errorf("Invalid version %s", version)
@@ -55,7 +54,8 @@ func (v *Version)ParseVersion(version string) (err error) {
return return
} }
// Returns 0 or an int value for the string, errors are returned as 0
// Returns 0 or an int value for the string, errors are returned as 0.
func (v *Version) intOrZero(input string) (value int) { func (v *Version) intOrZero(input string) (value int) {
if input != "" { if input != "" {
value, _ = strconv.Atoi(input) value, _ = strconv.Atoi(input)
@@ -63,7 +63,7 @@ func (v *Version) intOrZero(input string) (value int) {
return value return value
} }
// Returns true if this major revision is compatible // Returns true if this major revision is compatible.
func (v *Version) CompatibleFramework(c *CommandConfig) error { func (v *Version) CompatibleFramework(c *CommandConfig) error {
for i, rv := range frameworkCompatibleRangeList { for i, rv := range frameworkCompatibleRangeList {
start, _ := ParseVersion(rv[0]) start, _ := ParseVersion(rv[0])
@@ -81,7 +81,7 @@ func (v *Version) CompatibleFramework(c *CommandConfig) error {
return errors.New("Tool out of date - do a 'go get -u github.com/revel/cmd/revel'") return errors.New("Tool out of date - do a 'go get -u github.com/revel/cmd/revel'")
} }
// Returns true if this major revision is newer then the passed in // Returns true if this major revision is newer then the passed in.
func (v *Version) MajorNewer(o *Version) bool { func (v *Version) MajorNewer(o *Version) bool {
if v.Major != o.Major { if v.Major != o.Major {
return v.Major > o.Major return v.Major > o.Major
@@ -89,7 +89,7 @@ func (v *Version) MajorNewer(o *Version) bool {
return false return false
} }
// Returns true if this major or major and minor revision is newer then the value passed in // Returns true if this major or major and minor revision is newer then the value passed in.
func (v *Version) MinorNewer(o *Version) bool { func (v *Version) MinorNewer(o *Version) bool {
if v.Major != o.Major { if v.Major != o.Major {
return v.Major > o.Major return v.Major > o.Major
@@ -100,7 +100,7 @@ func (v *Version) MinorNewer(o *Version) bool {
return false return false
} }
// Returns true if the version is newer then the current on // Returns true if the version is newer then the current on.
func (v *Version) Newer(o *Version) bool { func (v *Version) Newer(o *Version) bool {
if v.Major != o.Major { if v.Major != o.Major {
return v.Major > o.Major return v.Major > o.Major
@@ -114,13 +114,13 @@ func (v *Version) Newer(o *Version) bool {
return true return true
} }
// Convert the version to a string // Convert the version to a string.
func (v *Version) VersionString() string { func (v *Version) VersionString() string {
return fmt.Sprintf("%s%d.%d.%d%s", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix) return fmt.Sprintf("%s%d.%d.%d%s", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix)
} }
// Convert the version build date and go version to a string // Convert the version build date and go version to a string.
func (v *Version) String() string { func (v *Version) String() string {
return fmt.Sprintf("Version: %s%d.%d.%d%s\nBuild Date: %s\n Minimium Go Version: %s", return fmt.Sprintf("Version: %s%d.%d.%d%s\nBuild Date: %s\n Minimum Go Version: %s",
v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix, v.BuildDate, v.MinGoVersion) v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix, v.BuildDate, v.MinGoVersion)
} }

View File

@@ -1,9 +1,10 @@
package model_test package model_test
import ( import (
"github.com/stretchr/testify/assert"
"testing" "testing"
"github.com/revel/cmd/model" "github.com/revel/cmd/model"
"github.com/stretchr/testify/assert"
) )
var versionTests = [][]string{ var versionTests = [][]string{
@@ -12,7 +13,8 @@ var versionTests = [][]string{
{"v0.20.", "v0.20.0"}, {"v0.20.", "v0.20.0"},
{"2.0", "2.0.0"}, {"2.0", "2.0.0"},
} }
// Test that the event handler can be attached and it dispatches the event received
// Test that the event handler can be attached and it dispatches the event received.
func TestVersion(t *testing.T) { func TestVersion(t *testing.T) {
for _, v := range versionTests { for _, v := range versionTests {
p, e := model.ParseVersion(v[0]) p, e := model.ParseVersion(v[0])
@@ -21,7 +23,7 @@ func TestVersion(t *testing.T) {
} }
} }
// test the ranges // test the ranges.
func TestVersionRange(t *testing.T) { func TestVersionRange(t *testing.T) {
a, _ := model.ParseVersion("0.1.2") a, _ := model.ParseVersion("0.1.2")
b, _ := model.ParseVersion("0.2.1") b, _ := model.ParseVersion("0.2.1")

View File

@@ -2,9 +2,10 @@ package parser
import ( import (
"go/ast" "go/ast"
"github.com/revel/cmd/utils"
"github.com/revel/cmd/model"
"go/token" "go/token"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
) )
// If this Decl is a struct type definition, it is summarized and added to specs. // If this Decl is a struct type definition, it is summarized and added to specs.
@@ -91,7 +92,7 @@ func appendStruct(fileName string, specs []*model.TypeInfo, pkgImportPath string
// If decl is a Method declaration, it is summarized and added to the array // If decl is a Method declaration, it is summarized and added to the array
// underneath its receiver type. // underneath its receiver type.
// e.g. "Login" => {MethodSpec, MethodSpec, ..} // e.g. "Login" => {MethodSpec, MethodSpec, ..}.
func appendAction(fset *token.FileSet, mm methodMap, decl ast.Decl, pkgImportPath, pkgName string, imports map[string]string) { func appendAction(fset *token.FileSet, mm methodMap, decl ast.Decl, pkgImportPath, pkgName string, imports map[string]string) {
// Func declaration? // Func declaration?
funcDecl, ok := decl.(*ast.FuncDecl) funcDecl, ok := decl.(*ast.FuncDecl)
@@ -194,7 +195,7 @@ func appendAction(fset *token.FileSet, mm methodMap, decl ast.Decl, pkgImportPat
}) })
var recvTypeName string var recvTypeName string
var recvType = funcDecl.Recv.List[0].Type recvType := funcDecl.Recv.List[0].Type
if recvStarType, ok := recvType.(*ast.StarExpr); ok { if recvStarType, ok := recvType.(*ast.StarExpr); ok {
recvTypeName = recvStarType.X.(*ast.Ident).Name recvTypeName = recvStarType.X.(*ast.Ident).Name
} else { } else {
@@ -204,7 +205,7 @@ func appendAction(fset *token.FileSet, mm methodMap, decl ast.Decl, pkgImportPat
mm[recvTypeName] = append(mm[recvTypeName], method) mm[recvTypeName] = append(mm[recvTypeName], method)
} }
// Combine the 2 source info models into one // Combine the 2 source info models into one.
func appendSourceInfo(srcInfo1, srcInfo2 *model.SourceInfo) *model.SourceInfo { func appendSourceInfo(srcInfo1, srcInfo2 *model.SourceInfo) *model.SourceInfo {
if srcInfo1 == nil { if srcInfo1 == nil {
return srcInfo2 return srcInfo2

View File

@@ -1,15 +1,16 @@
package parser package parser
import ( import (
"github.com/revel/cmd/utils"
"go/ast" "go/ast"
"go/build" "go/build"
"go/token" "go/token"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/revel/cmd/utils"
) )
// Add imports to the map from the source dir // Add imports to the map from the source dir.
func addImports(imports map[string]string, decl ast.Decl, srcDir string) { func addImports(imports map[string]string, decl ast.Decl, srcDir string) {
genDecl, ok := decl.(*ast.GenDecl) genDecl, ok := decl.(*ast.GenDecl)
if !ok { if !ok {
@@ -42,7 +43,6 @@ func addImports(imports map[string]string, decl ast.Decl, srcDir string) {
// 2. Exempt the standard library; their directories always match the package name. // 2. Exempt the standard library; their directories always match the package name.
// 3. Can use build.FindOnly and then use parser.ParseDir with mode PackageClauseOnly // 3. Can use build.FindOnly and then use parser.ParseDir with mode PackageClauseOnly
if pkgAlias == "" { if pkgAlias == "" {
utils.Logger.Debug("Reading from build", "path", fullPath, "srcPath", srcDir, "gopath", build.Default.GOPATH) utils.Logger.Debug("Reading from build", "path", fullPath, "srcPath", srcDir, "gopath", build.Default.GOPATH)
pkg, err := build.Import(fullPath, srcDir, 0) pkg, err := build.Import(fullPath, srcDir, 0)
if err != nil { if err != nil {
@@ -63,7 +63,7 @@ func addImports(imports map[string]string, decl ast.Decl, srcDir string) {
} }
// Returns a valid import string from the path // Returns a valid import string from the path
// using the build.Defaul.GOPATH to determine the root // using the build.Defaul.GOPATH to determine the root.
func importPathFromPath(root, basePath string) string { func importPathFromPath(root, basePath string) string {
vendorTest := filepath.Join(basePath, "vendor") vendorTest := filepath.Join(basePath, "vendor")
if len(root) > len(vendorTest) && root[:len(vendorTest)] == vendorTest { if len(root) > len(vendorTest) && root[:len(vendorTest)] == vendorTest {

View File

@@ -20,7 +20,7 @@ import (
"github.com/revel/cmd/utils" "github.com/revel/cmd/utils"
) )
// A container used to support the reflection package // A container used to support the reflection package.
type processContainer struct { type processContainer struct {
root, rootImportPath string // The paths root, rootImportPath string // The paths
paths *model.RevelContainer // The Revel paths paths *model.RevelContainer // The Revel paths
@@ -54,7 +54,7 @@ func ProcessSource(paths *model.RevelContainer) (_ *model.SourceInfo, compileErr
return pc.srcInfo, compileError return pc.srcInfo, compileError
} }
// Called during the "walk process" // Called during the "walk process".
func (pc *processContainer) processPath(path string, info os.FileInfo, err error) error { func (pc *processContainer) processPath(path string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
utils.Logger.Error("Error scanning app source:", "error", err) utils.Logger.Error("Error scanning app source:", "error", err)
@@ -84,7 +84,7 @@ func (pc *processContainer) processPath(path string, info os.FileInfo, err error
if err != nil { if err != nil {
if errList, ok := err.(scanner.ErrorList); ok { if errList, ok := err.(scanner.ErrorList); ok {
var pos = errList[0].Pos pos := errList[0].Pos
newError := &utils.SourceError{ newError := &utils.SourceError{
SourceType: ".go source", SourceType: ".go source",
Title: "Go Compilation Error", Title: "Go Compilation Error",
@@ -114,7 +114,7 @@ func (pc *processContainer) processPath(path string, info os.FileInfo, err error
// These cannot be included in source code that is not generated specifically as a test // These cannot be included in source code that is not generated specifically as a test
for i := range pkgs { for i := range pkgs {
if len(i) > 6 { if len(i) > 6 {
if string(i[len(i)-5:]) == "_test" { if i[len(i)-5:] == "_test" {
delete(pkgs, i) delete(pkgs, i)
} }
} }
@@ -146,7 +146,7 @@ func (pc *processContainer) processPath(path string, info os.FileInfo, err error
return nil return nil
} }
// Process a single package within a file // Process a single package within a file.
func processPackage(fset *token.FileSet, pkgImportPath, pkgPath string, pkg *ast.Package) *model.SourceInfo { func processPackage(fset *token.FileSet, pkgImportPath, pkgPath string, pkg *ast.Package) *model.SourceInfo {
var ( var (
structSpecs []*model.TypeInfo structSpecs []*model.TypeInfo

View File

@@ -67,7 +67,7 @@ var expectedValidationKeys = []map[int]string{
}, },
} }
// This tests the recording of line number to validation key of the preceeding // This tests the recording of line number to validation key of the preceding
// example source. // example source.
func TestGetValidationKeys(t *testing.T) { func TestGetValidationKeys(t *testing.T) {
fset := token.NewFileSet() fset := token.NewFileSet()

View File

@@ -1,10 +1,11 @@
package parser package parser
import ( import (
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"go/ast" "go/ast"
"go/token" "go/token"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
) )
// Scan app source code for calls to X.Y(), where X is of type *Validation. // Scan app source code for calls to X.Y(), where X is of type *Validation.

View File

@@ -1,14 +1,15 @@
package parser2 package parser2
import ( import (
"github.com/revel/cmd/utils"
"golang.org/x/tools/go/packages"
"github.com/revel/cmd/model"
"go/ast" "go/ast"
"go/token" "go/token"
"strings"
"path/filepath" "path/filepath"
"strings"
"github.com/revel/cmd/logger" "github.com/revel/cmd/logger"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"golang.org/x/tools/go/packages"
) )
type ( type (
@@ -37,7 +38,6 @@ func (s *SourceInfoProcessor) processPackage(p *packages.Package) (sourceInfo *m
log.Info("Processing package") log.Info("Processing package")
for _, tree := range p.Syntax { for _, tree := range p.Syntax {
for _, decl := range tree.Decls { for _, decl := range tree.Decls {
s.sourceProcessor.packageMap[p.PkgPath] = filepath.Dir(p.Fset.Position(decl.Pos()).Filename) s.sourceProcessor.packageMap[p.PkgPath] = filepath.Dir(p.Fset.Position(decl.Pos()).Filename)
if !s.addImport(decl, p, localImportMap, log) { if !s.addImport(decl, p, localImportMap, log) {
continue continue
@@ -85,6 +85,7 @@ func (s *SourceInfoProcessor) processPackage(p *packages.Package) (sourceInfo *m
return return
} }
// Scan app source code for calls to X.Y(), where X is of type *Validation. // Scan app source code for calls to X.Y(), where X is of type *Validation.
// //
// Recognize these scenarios: // Recognize these scenarios:
@@ -99,7 +100,7 @@ func (s *SourceInfoProcessor) processPackage(p *packages.Package) (sourceInfo *m
// //
// The end result is that we can set the default validation key for each call to // The end result is that we can set the default validation key for each call to
// be the same as the local variable. // be the same as the local variable.
func (s *SourceInfoProcessor) getValidation(funcDecl *ast.FuncDecl, p *packages.Package) (map[int]string) { func (s *SourceInfoProcessor) getValidation(funcDecl *ast.FuncDecl, p *packages.Package) map[int]string {
var ( var (
lineKeys = make(map[int]string) lineKeys = make(map[int]string)
@@ -165,8 +166,8 @@ func (s *SourceInfoProcessor) getValidation(funcDecl *ast.FuncDecl, p *packages.
}) })
return lineKeys return lineKeys
} }
// Check to see if there is a *revel.Validation as an argument. // Check to see if there is a *revel.Validation as an argument.
func (s *SourceInfoProcessor) getValidationParameter(funcDecl *ast.FuncDecl) *ast.Object { func (s *SourceInfoProcessor) getValidationParameter(funcDecl *ast.FuncDecl) *ast.Object {
for _, field := range funcDecl.Type.Params.List { for _, field := range funcDecl.Type.Params.List {
@@ -191,6 +192,7 @@ func (s *SourceInfoProcessor) getValidationParameter(funcDecl *ast.FuncDecl) *a
} }
return nil return nil
} }
func (s *SourceInfoProcessor) getControllerFunc(funcDecl *ast.FuncDecl, p *packages.Package, localImportMap map[string]string) (method *model.MethodSpec, recvTypeName string) { func (s *SourceInfoProcessor) getControllerFunc(funcDecl *ast.FuncDecl, p *packages.Package, localImportMap map[string]string) (method *model.MethodSpec, recvTypeName string) {
selExpr, ok := funcDecl.Type.Results.List[0].Type.(*ast.SelectorExpr) selExpr, ok := funcDecl.Type.Results.List[0].Type.(*ast.SelectorExpr)
if !ok { if !ok {
@@ -274,7 +276,7 @@ func (s *SourceInfoProcessor) getControllerFunc(funcDecl *ast.FuncDecl, p *packa
return true return true
}) })
var recvType = funcDecl.Recv.List[0].Type recvType := funcDecl.Recv.List[0].Type
if recvStarType, ok := recvType.(*ast.StarExpr); ok { if recvStarType, ok := recvType.(*ast.StarExpr); ok {
recvTypeName = recvStarType.X.(*ast.Ident).Name recvTypeName = recvStarType.X.(*ast.Ident).Name
} else { } else {
@@ -282,6 +284,7 @@ func (s *SourceInfoProcessor) getControllerFunc(funcDecl *ast.FuncDecl, p *packa
} }
return return
} }
func (s *SourceInfoProcessor) getControllerSpec(spec *ast.TypeSpec, p *packages.Package, localImportMap map[string]string) (controllerSpec *model.TypeInfo) { func (s *SourceInfoProcessor) getControllerSpec(spec *ast.TypeSpec, p *packages.Package, localImportMap map[string]string) (controllerSpec *model.TypeInfo) {
structType := spec.Type.(*ast.StructType) structType := spec.Type.(*ast.StructType)
@@ -342,9 +345,9 @@ func (s *SourceInfoProcessor) getControllerSpec(spec *ast.TypeSpec, p *packages.
} else { } else {
var ok bool var ok bool
if importPath, ok = localImportMap[pkgName]; !ok { if importPath, ok = localImportMap[pkgName]; !ok {
log.Debug("Debug: Unusual, failed to find package locally ", "package", pkgName, "type", typeName, "map", s.sourceProcessor.importMap, "usedin", ) log.Debug("Debug: Unusual, failed to find package locally ", "package", pkgName, "type", typeName, "map", s.sourceProcessor.importMap, "usedin")
if importPath, ok = s.sourceProcessor.importMap[pkgName]; !ok { if importPath, ok = s.sourceProcessor.importMap[pkgName]; !ok {
log.Error("Error: Failed to find import path for ", "package", pkgName, "type", typeName, "map", s.sourceProcessor.importMap, "usedin", ) log.Error("Error: Failed to find import path for ", "package", pkgName, "type", typeName, "map", s.sourceProcessor.importMap, "usedin")
continue continue
} }
} }
@@ -358,6 +361,7 @@ func (s *SourceInfoProcessor) getControllerSpec(spec *ast.TypeSpec, p *packages.
s.sourceProcessor.log.Info("Added controller spec", "name", controllerSpec.StructName, "package", controllerSpec.ImportPath) s.sourceProcessor.log.Info("Added controller spec", "name", controllerSpec.StructName, "package", controllerSpec.ImportPath)
return return
} }
func (s *SourceInfoProcessor) getStructTypeDecl(decl ast.Decl, fset *token.FileSet) (spec *ast.TypeSpec, found bool) { func (s *SourceInfoProcessor) getStructTypeDecl(decl ast.Decl, fset *token.FileSet) (spec *ast.TypeSpec, found bool) {
genDecl, ok := decl.(*ast.GenDecl) genDecl, ok := decl.(*ast.GenDecl)
if !ok { if !ok {
@@ -377,8 +381,8 @@ func (s *SourceInfoProcessor) getStructTypeDecl(decl ast.Decl, fset *token.FileS
_, found = spec.Type.(*ast.StructType) _, found = spec.Type.(*ast.StructType)
return return
} }
func (s *SourceInfoProcessor) getFuncName(funcDecl *ast.FuncDecl) string { func (s *SourceInfoProcessor) getFuncName(funcDecl *ast.FuncDecl) string {
prefix := "" prefix := ""
if funcDecl.Recv != nil { if funcDecl.Recv != nil {
@@ -392,6 +396,7 @@ func (s *SourceInfoProcessor) getFuncName(funcDecl *ast.FuncDecl) string {
} }
return prefix + funcDecl.Name.Name return prefix + funcDecl.Name.Name
} }
func (s *SourceInfoProcessor) addImport(decl ast.Decl, p *packages.Package, localImportMap map[string]string, log logger.MultiLogger) (shouldContinue bool) { func (s *SourceInfoProcessor) addImport(decl ast.Decl, p *packages.Package, localImportMap map[string]string, log logger.MultiLogger) (shouldContinue bool) {
shouldContinue = true shouldContinue = true
genDecl, ok := decl.(*ast.GenDecl) genDecl, ok := decl.(*ast.GenDecl)
@@ -421,7 +426,6 @@ func (s *SourceInfoProcessor) addImport(decl ast.Decl, p *packages.Package, loca
} }
localImportMap[pkgAlias] = fullPath localImportMap[pkgAlias] = fullPath
} }
} }
return return
} }

View File

@@ -1,17 +1,18 @@
package parser2 package parser2
import ( import (
"github.com/revel/cmd/model" "go/ast"
"golang.org/x/tools/go/packages"
"github.com/revel/cmd/utils"
"go/parser" "go/parser"
"strings" "go/scanner"
"github.com/revel/cmd/logger" "go/token"
"os" "os"
"path/filepath" "path/filepath"
"go/ast" "strings"
"go/token"
"go/scanner" "github.com/revel/cmd/logger"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"golang.org/x/tools/go/packages"
) )
type ( type (
@@ -77,7 +78,7 @@ func (s *SourceProcessor) parse() (compileError error) {
} }
// Using the packages.Load function load all the packages and type specifications (forces compile). // Using the packages.Load function load all the packages and type specifications (forces compile).
// this sets the SourceProcessor.packageList []*packages.Package // this sets the SourceProcessor.packageList []*packages.Package.
func (s *SourceProcessor) addPackages() (err error) { func (s *SourceProcessor) addPackages() (err error) {
allPackages := []string{model.RevelImportPath + "/..."} allPackages := []string{model.RevelImportPath + "/..."}
for _, module := range s.revelContainer.ModulePathMap { for _, module := range s.revelContainer.ModulePathMap {
@@ -88,8 +89,7 @@ func (s *SourceProcessor) addPackages() (err error) {
config := &packages.Config{ config := &packages.Config{
// ode: packages.NeedSyntax | packages.NeedCompiledGoFiles, // ode: packages.NeedSyntax | packages.NeedCompiledGoFiles,
Mode: Mode: packages.NeedTypes | // For compile error
packages.NeedTypes | // For compile error
packages.NeedDeps | // To load dependent files packages.NeedDeps | // To load dependent files
packages.NeedName | // Loads the full package name packages.NeedName | // Loads the full package name
packages.NeedSyntax, // To load ast tree (for end points) packages.NeedSyntax, // To load ast tree (for end points)
@@ -118,7 +118,7 @@ func (s *SourceProcessor) addPackages() (err error) {
// This callback is used to build the packages for the "app" package. This allows us to // This callback is used to build the packages for the "app" package. This allows us to
// parse the source files without doing a full compile on them // parse the source files without doing a full compile on them
// This callback only processes folders, so any files passed to this will return a nil // This callback only processes folders, so any files passed to this will return a nil.
func (s *SourceProcessor) processPath(path string, info os.FileInfo, err error) error { func (s *SourceProcessor) processPath(path string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
s.log.Error("Error scanning app source:", "error", err) s.log.Error("Error scanning app source:", "error", err)
@@ -151,7 +151,7 @@ func (s *SourceProcessor) processPath(path string, info os.FileInfo, err error)
if err != nil { if err != nil {
if errList, ok := err.(scanner.ErrorList); ok { if errList, ok := err.(scanner.ErrorList); ok {
var pos = errList[0].Pos pos := errList[0].Pos
newError := &utils.SourceError{ newError := &utils.SourceError{
SourceType: ".go source", SourceType: ".go source",
Title: "Go Compilation Error", Title: "Go Compilation Error",
@@ -181,7 +181,7 @@ func (s *SourceProcessor) processPath(path string, info os.FileInfo, err error)
// These cannot be included in source code that is not generated specifically as a test // These cannot be included in source code that is not generated specifically as a test
for i := range pkgMap { for i := range pkgMap {
if len(i) > 6 { if len(i) > 6 {
if string(i[len(i) - 5:]) == "_test" { if i[len(i)-5:] == "_test" {
delete(pkgMap, i) delete(pkgMap, i)
} }
} }
@@ -218,12 +218,11 @@ func (s *SourceProcessor) processPath(path string, info os.FileInfo, err error)
} }
// This function is used to populate a map so that we can lookup controller embedded types in order to determine // This function is used to populate a map so that we can lookup controller embedded types in order to determine
// if a Struct inherits from from revel.Controller // if a Struct inherits from from revel.Controller.
func (s *SourceProcessor) addImportMap() (err error) { func (s *SourceProcessor) addImportMap() (err error) {
s.importMap = map[string]string{} s.importMap = map[string]string{}
s.packageMap = map[string]string{} s.packageMap = map[string]string{}
for _, p := range s.packageList { for _, p := range s.packageList {
if len(p.Errors) > 0 { if len(p.Errors) > 0 {
// Generate a compile error // Generate a compile error
for _, e := range p.Errors { for _, e := range p.Errors {

View File

@@ -9,5 +9,4 @@
// 2. Monitor the user source and restart the program when necessary. // 2. Monitor the user source and restart the program when necessary.
// //
// Source files are generated in the app/tmp directory. // Source files are generated in the app/tmp directory.
package proxy package proxy

View File

@@ -5,11 +5,11 @@
package main package main
import ( import (
"fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"fmt"
"github.com/revel/cmd/harness" "github.com/revel/cmd/harness"
"github.com/revel/cmd/model" "github.com/revel/cmd/model"
"github.com/revel/cmd/utils" "github.com/revel/cmd/utils"
@@ -34,7 +34,7 @@ func init() {
cmdBuild.UpdateConfig = updateBuildConfig cmdBuild.UpdateConfig = updateBuildConfig
} }
// The update config updates the configuration command so that it can run // The update config updates the configuration command so that it can run.
func updateBuildConfig(c *model.CommandConfig, args []string) bool { func updateBuildConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.BUILD c.Index = model.BUILD
if c.Build.TargetPath == "" { if c.Build.TargetPath == "" {
@@ -57,9 +57,8 @@ func updateBuildConfig(c *model.CommandConfig, args []string) bool {
return true return true
} }
// The main entry point to build application from command line // The main entry point to build application from command line.
func buildApp(c *model.CommandConfig) (err error) { func buildApp(c *model.CommandConfig) (err error) {
appImportPath, destPath, mode := c.ImportPath, c.Build.TargetPath, DefaultRunMode appImportPath, destPath, mode := c.ImportPath, c.Build.TargetPath, DefaultRunMode
if len(c.Build.Mode) > 0 { if len(c.Build.Mode) > 0 {
mode = c.Build.Mode mode = c.Build.Mode
@@ -70,7 +69,7 @@ func buildApp(c *model.CommandConfig) (err error) {
c.Build.Mode = mode c.Build.Mode = mode
c.Build.ImportPath = appImportPath c.Build.ImportPath = appImportPath
revel_paths, err := model.NewRevelPaths(mode, appImportPath, c.AppPath, model.NewWrappedRevelCallback(nil, c.PackageResolver)) revelPaths, err := model.NewRevelPaths(mode, appImportPath, c.AppPath, model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil { if err != nil {
return return
} }
@@ -80,7 +79,7 @@ func buildApp(c *model.CommandConfig) (err error) {
} }
// Ensure the application can be built, this generates the main file // Ensure the application can be built, this generates the main file
app, err := harness.Build(c, revel_paths) app, err := harness.Build(c, revelPaths)
if err != nil { if err != nil {
return err return err
} }
@@ -91,11 +90,11 @@ func buildApp(c *model.CommandConfig) (err error) {
// - revel // - revel
// - app // - app
packageFolders, err := buildCopyFiles(c, app, revel_paths) packageFolders, err := buildCopyFiles(c, app, revelPaths)
if err != nil { if err != nil {
return return
} }
err = buildCopyModules(c, revel_paths, packageFolders, app) err = buildCopyModules(c, revelPaths, packageFolders, app)
if err != nil { if err != nil {
return return
} }
@@ -106,36 +105,36 @@ func buildApp(c *model.CommandConfig) (err error) {
return return
} }
// Copy the files to the target // Copy the files to the target.
func buildCopyFiles(c *model.CommandConfig, app *harness.App, revel_paths *model.RevelContainer) (packageFolders []string, err error) { func buildCopyFiles(c *model.CommandConfig, app *harness.App, revelPaths *model.RevelContainer) (packageFolders []string, err error) {
appImportPath, destPath := c.ImportPath, c.Build.TargetPath appImportPath, destPath := c.ImportPath, c.Build.TargetPath
// Revel and the app are in a directory structure mirroring import path // Revel and the app are in a directory structure mirroring import path
srcPath := filepath.Join(destPath, "src") srcPath := filepath.Join(destPath, "src")
destBinaryPath := filepath.Join(destPath, filepath.Base(app.BinaryPath)) destBinaryPath := filepath.Join(destPath, filepath.Base(app.BinaryPath))
tmpRevelPath := filepath.Join(srcPath, filepath.FromSlash(model.RevelImportPath)) tmpRevelPath := filepath.Join(srcPath, filepath.FromSlash(model.RevelImportPath))
if err = utils.CopyFile(destBinaryPath, filepath.Join(revel_paths.BasePath, app.BinaryPath)); err != nil { if err = utils.CopyFile(destBinaryPath, filepath.Join(revelPaths.BasePath, app.BinaryPath)); err != nil {
return return
} }
utils.MustChmod(destBinaryPath, 0755) utils.MustChmod(destBinaryPath, 0755)
// Copy the templates from the revel // Copy the templates from the revel
if err = utils.CopyDir(filepath.Join(tmpRevelPath, "conf"), filepath.Join(revel_paths.RevelPath, "conf"), nil); err != nil { if err = utils.CopyDir(filepath.Join(tmpRevelPath, "conf"), filepath.Join(revelPaths.RevelPath, "conf"), nil); err != nil {
return return
} }
if err = utils.CopyDir(filepath.Join(tmpRevelPath, "templates"), filepath.Join(revel_paths.RevelPath, "templates"), nil); err != nil { if err = utils.CopyDir(filepath.Join(tmpRevelPath, "templates"), filepath.Join(revelPaths.RevelPath, "templates"), nil); err != nil {
return return
} }
// Get the folders to be packaged // Get the folders to be packaged
packageFolders = strings.Split(revel_paths.Config.StringDefault("package.folders", "conf,public,app/views"), ",") packageFolders = strings.Split(revelPaths.Config.StringDefault("package.folders", "conf,public,app/views"), ",")
for i, p := range packageFolders { for i, p := range packageFolders {
// Clean spaces, reformat slash to filesystem // Clean spaces, reformat slash to filesystem
packageFolders[i] = filepath.FromSlash(strings.TrimSpace(p)) packageFolders[i] = filepath.FromSlash(strings.TrimSpace(p))
} }
if c.Build.CopySource { if c.Build.CopySource {
err = utils.CopyDir(filepath.Join(srcPath, filepath.FromSlash(appImportPath)), revel_paths.BasePath, nil) err = utils.CopyDir(filepath.Join(srcPath, filepath.FromSlash(appImportPath)), revelPaths.BasePath, nil)
if err != nil { if err != nil {
return return
} }
@@ -143,7 +142,7 @@ func buildCopyFiles(c *model.CommandConfig, app *harness.App, revel_paths *model
for _, folder := range packageFolders { for _, folder := range packageFolders {
err = utils.CopyDir( err = utils.CopyDir(
filepath.Join(srcPath, filepath.FromSlash(appImportPath), folder), filepath.Join(srcPath, filepath.FromSlash(appImportPath), folder),
filepath.Join(revel_paths.BasePath, folder), filepath.Join(revelPaths.BasePath, folder),
nil) nil)
if err != nil { if err != nil {
return return
@@ -154,11 +153,11 @@ func buildCopyFiles(c *model.CommandConfig, app *harness.App, revel_paths *model
return return
} }
// Based on the section copy over the build modules // Based on the section copy over the build modules.
func buildCopyModules(c *model.CommandConfig, revel_paths *model.RevelContainer, packageFolders []string, app *harness.App) (err error) { func buildCopyModules(c *model.CommandConfig, revelPaths *model.RevelContainer, packageFolders []string, app *harness.App) (err error) {
destPath := filepath.Join(c.Build.TargetPath, "src") destPath := filepath.Join(c.Build.TargetPath, "src")
// Find all the modules used and copy them over. // Find all the modules used and copy them over.
config := revel_paths.Config.Raw() config := revelPaths.Config.Raw()
// We should only copy over the section of options what the build is targeted for // We should only copy over the section of options what the build is targeted for
// We will default to prod // We will default to prod
@@ -178,7 +177,6 @@ func buildCopyModules(c *model.CommandConfig, revel_paths *model.RevelContainer,
continue continue
} }
moduleImportList = append(moduleImportList, moduleImportPath) moduleImportList = append(moduleImportList, moduleImportPath)
} }
} }
@@ -207,7 +205,7 @@ func buildCopyModules(c *model.CommandConfig, revel_paths *model.RevelContainer,
return return
} }
// Write the run scripts for the build // Write the run scripts for the build.
func buildWriteScripts(c *model.CommandConfig, app *harness.App) (err error) { func buildWriteScripts(c *model.CommandConfig, app *harness.App) (err error) {
tmplData := map[string]interface{}{ tmplData := map[string]interface{}{
"BinName": filepath.Base(app.BinaryPath), "BinName": filepath.Base(app.BinaryPath),
@@ -238,9 +236,8 @@ func buildWriteScripts(c *model.CommandConfig, app *harness.App) (err error) {
return return
} }
// Checks to see if the target folder exists and can be created // Checks to see if the target folder exists and can be created.
func buildSafetyCheck(destPath string) error { func buildSafetyCheck(destPath string) error {
// First, verify that it is either already empty or looks like a previous // First, verify that it is either already empty or looks like a previous
// build (to avoid clobbering anything) // build (to avoid clobbering anything)
if utils.Exists(destPath) && !utils.Empty(destPath) && !utils.Exists(filepath.Join(destPath, "run.sh")) { if utils.Exists(destPath) && !utils.Empty(destPath) && !utils.Exists(filepath.Join(destPath, "run.sh")) {
@@ -262,6 +259,7 @@ const PACKAGE_RUN_SH = `#!/bin/sh
SCRIPTPATH=$(cd "$(dirname "$0")"; pwd) SCRIPTPATH=$(cd "$(dirname "$0")"; pwd)
"$SCRIPTPATH/{{.BinName}}" -importPath {{.ImportPath}} -srcPath "$SCRIPTPATH/src" -runMode {{.Mode}} "$SCRIPTPATH/{{.BinName}}" -importPath {{.ImportPath}} -srcPath "$SCRIPTPATH/src" -runMode {{.Mode}}
` `
const PACKAGE_RUN_BAT = `@echo off const PACKAGE_RUN_BAT = `@echo off
{{.BinName}} -importPath {{.ImportPath}} -srcPath "%CD%\src" -runMode {{.Mode}} {{.BinName}} -importPath {{.ImportPath}} -srcPath "%CD%\src" -runMode {{.Mode}}

View File

@@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
// test the commands // test the commands.
func TestBuild(t *testing.T) { func TestBuild(t *testing.T) {
a := assert.New(t) a := assert.New(t)
gopath := setup("revel-test-build", a) gopath := setup("revel-test-build", a)

View File

@@ -6,11 +6,11 @@ package main
import ( import (
"fmt" "fmt"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"os" "os"
"path/filepath" "path/filepath"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
) )
var cmdClean = &Command{ var cmdClean = &Command{
@@ -34,7 +34,7 @@ func init() {
cmdClean.RunWith = cleanApp cmdClean.RunWith = cleanApp
} }
// Update the clean command configuration, using old method // Update the clean command configuration, using old method.
func updateCleanConfig(c *model.CommandConfig, args []string) bool { func updateCleanConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.CLEAN c.Index = model.CLEAN
if len(args) == 0 && c.Clean.ImportPath != "" { if len(args) == 0 && c.Clean.ImportPath != "" {
@@ -48,9 +48,8 @@ func updateCleanConfig(c *model.CommandConfig, args []string) bool {
return true return true
} }
// Clean the source directory of generated files // Clean the source directory of generated files.
func cleanApp(c *model.CommandConfig) (err error) { func cleanApp(c *model.CommandConfig) (err error) {
purgeDirs := []string{ purgeDirs := []string{
filepath.Join(c.AppPath, "app", "tmp"), filepath.Join(c.AppPath, "app", "tmp"),
filepath.Join(c.AppPath, "app", "routes"), filepath.Join(c.AppPath, "app", "routes"),

View File

@@ -1,21 +1,21 @@
package main_test package main_test
import ( import (
"github.com/revel/cmd/model"
"github.com/revel/cmd/revel"
"github.com/revel/cmd/utils"
"github.com/stretchr/testify/assert"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/revel/cmd/model"
main "github.com/revel/cmd/revel"
"github.com/revel/cmd/utils"
"github.com/stretchr/testify/assert"
) )
// test the commands // test the commands.
func TestClean(t *testing.T) { func TestClean(t *testing.T) {
a := assert.New(t) a := assert.New(t)
gopath := setup("revel-test-clean", a) gopath := setup("revel-test-clean", a)
t.Run("Clean", func(t *testing.T) { t.Run("Clean", func(t *testing.T) {
a := assert.New(t) a := assert.New(t)
c := newApp("clean-test", model.NEW, nil, a) c := newApp("clean-test", model.NEW, nil, a)

View File

@@ -1,19 +1,20 @@
package main_test package main_test
import ( import (
"github.com/revel/cmd/logger" "fmt"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"github.com/stretchr/testify/assert"
"go/build" "go/build"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"fmt"
"github.com/revel/cmd/logger"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"github.com/stretchr/testify/assert"
) )
// Test that the event handler can be attached and it dispatches the event received // Test that the event handler can be attached and it dispatches the event received.
func setup(suffix string, a *assert.Assertions) (string) { func setup(suffix string, a *assert.Assertions) string {
temp := os.TempDir() temp := os.TempDir()
wd, _ := os.Getwd() wd, _ := os.Getwd()
utils.InitLogger(wd, logger.LvlInfo) utils.InitLogger(wd, logger.LvlInfo)
@@ -43,7 +44,7 @@ func setup(suffix string, a *assert.Assertions) (string) {
return gopath return gopath
} }
// Create a new app for the name // Create a new app for the name.
func newApp(name string, command model.COMMAND, precall func(c *model.CommandConfig), a *assert.Assertions) *model.CommandConfig { func newApp(name string, command model.COMMAND, precall func(c *model.CommandConfig), a *assert.Assertions) *model.CommandConfig {
c := &model.CommandConfig{Vendored: true} c := &model.CommandConfig{Vendored: true}
switch command { switch command {
@@ -62,7 +63,6 @@ func newApp(name string, command model.COMMAND, precall func(c *model.CommandCon
getOutput, _ = goModCmd.CombinedOutput() getOutput, _ = goModCmd.CombinedOutput()
fmt.Printf("Calling go mod edit %v", string(getOutput)) fmt.Printf("Calling go mod edit %v", string(getOutput))
return nil return nil
} }
case model.BUILD: case model.BUILD:

View File

@@ -8,6 +8,7 @@ import (
"fmt" "fmt"
"go/build" "go/build"
"math/rand" "math/rand"
"net/url"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@@ -15,7 +16,6 @@ import (
"github.com/revel/cmd/model" "github.com/revel/cmd/model"
"github.com/revel/cmd/utils" "github.com/revel/cmd/utils"
"net/url"
) )
var cmdNew = &Command{ var cmdNew = &Command{
@@ -43,7 +43,7 @@ func init() {
cmdNew.UpdateConfig = updateNewConfig cmdNew.UpdateConfig = updateNewConfig
} }
// Called when unable to parse the command line automatically and assumes an old launch // Called when unable to parse the command line automatically and assumes an old launch.
func updateNewConfig(c *model.CommandConfig, args []string) bool { func updateNewConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.NEW c.Index = model.NEW
if len(c.New.Package) > 0 { if len(c.New.Package) > 0 {
@@ -64,10 +64,9 @@ func updateNewConfig(c *model.CommandConfig, args []string) bool {
} }
return true return true
} }
// Call to create a new application // Call to create a new application.
func newApp(c *model.CommandConfig) (err error) { func newApp(c *model.CommandConfig) (err error) {
// Check for an existing folder so we don't clobber it // Check for an existing folder so we don't clobber it
_, err = build.Import(c.ImportPath, "", build.FindOnly) _, err = build.Import(c.ImportPath, "", build.FindOnly)
@@ -124,7 +123,6 @@ func newApp(c *model.CommandConfig) (err error) {
} }
func createModVendor(c *model.CommandConfig) (err error) { func createModVendor(c *model.CommandConfig) (err error) {
utils.Logger.Info("Creating a new mod app") utils.Logger.Info("Creating a new mod app")
goModCmd := exec.Command("go", "mod", "init", filepath.Join(c.New.Package, c.AppName)) goModCmd := exec.Command("go", "mod", "init", filepath.Join(c.New.Package, c.AppName))
@@ -141,69 +139,21 @@ func createModVendor(c *model.CommandConfig) (err error) {
return return
} }
func createDepVendor(c *model.CommandConfig) (err error) { // Used to generate a new secret key.
utils.Logger.Info("Creating a new vendor app")
vendorPath := filepath.Join(c.AppPath, "vendor")
if !utils.DirExists(vendorPath) {
if err := os.MkdirAll(vendorPath, os.ModePerm); err != nil {
return utils.NewBuildError("Failed to create " + vendorPath, "error", err)
}
}
// In order for dep to run there needs to be a source file in the folder
tempPath := filepath.Join(c.AppPath, "tmp")
utils.Logger.Info("Checking for temp folder for source code", "path", tempPath)
if !utils.DirExists(tempPath) {
if err := os.MkdirAll(tempPath, os.ModePerm); err != nil {
return utils.NewBuildIfError(err, "Failed to create " + vendorPath)
}
if err = utils.GenerateTemplate(filepath.Join(tempPath, "main.go"), NEW_MAIN_FILE, nil); err != nil {
return utils.NewBuildIfError(err, "Failed to create main file " + vendorPath)
}
}
// Create a package template file if it does not exist
packageFile := filepath.Join(c.AppPath, "Gopkg.toml")
utils.Logger.Info("Checking for Gopkg.toml", "path", packageFile)
if !utils.Exists(packageFile) {
utils.Logger.Info("Generating Gopkg.toml", "path", packageFile)
if err := utils.GenerateTemplate(packageFile, VENDOR_GOPKG, nil); err != nil {
return utils.NewBuildIfError(err, "Failed to generate template")
}
} else {
utils.Logger.Info("Package file exists in skeleto, skipping adding")
}
getCmd := exec.Command("dep", "ensure", "-v")
utils.CmdInit(getCmd, !c.Vendored, c.AppPath)
utils.Logger.Info("Exec:", "args", getCmd.Args, "env", getCmd.Env, "workingdir", getCmd.Dir)
getOutput, err := getCmd.CombinedOutput()
if err != nil {
return utils.NewBuildIfError(err, string(getOutput))
}
return
}
// Used to generate a new secret key
const alphaNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" const alphaNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
// Generate a secret key // Generate a secret key.
func generateSecret() string { func generateSecret() string {
chars := make([]byte, 64) chars := make([]byte, 64)
for i := 0; i < 64; i++ { for i := 0; i < 64; i++ {
chars[i] = alphaNumeric[rand.Intn(len(alphaNumeric))] chars[i] = alphaNumeric[rand.Intn(len(alphaNumeric))]
} }
return string(chars) return string(chars)
} }
// Sets the applicaiton path // Sets the application path.
func setApplicationPath(c *model.CommandConfig) (err error) { func setApplicationPath(c *model.CommandConfig) (err error) {
// revel/revel#1014 validate relative path, we cannot use built-in functions // revel/revel#1014 validate relative path, we cannot use built-in functions
// since Go import path is valid relative path too. // since Go import path is valid relative path too.
// so check basic part of the path, which is "." // so check basic part of the path, which is "."
@@ -216,7 +166,7 @@ func setApplicationPath(c *model.CommandConfig) (err error) {
} }
_, err = build.Import(model.RevelImportPath, "", build.FindOnly) _, err = build.Import(model.RevelImportPath, "", build.FindOnly)
if err != nil { if err != nil {
//// Go get the revel project // Go get the revel project
err = c.PackageResolver(model.RevelImportPath) err = c.PackageResolver(model.RevelImportPath)
if err != nil { if err != nil {
return utils.NewBuildIfError(err, "Failed to fetch revel "+model.RevelImportPath) return utils.NewBuildIfError(err, "Failed to fetch revel "+model.RevelImportPath)
@@ -229,7 +179,7 @@ func setApplicationPath(c *model.CommandConfig) (err error) {
return nil return nil
} }
// Set the skeleton path // Set the skeleton path.
func setSkeletonPath(c *model.CommandConfig) (err error) { func setSkeletonPath(c *model.CommandConfig) (err error) {
if len(c.New.SkeletonPath) == 0 { if len(c.New.SkeletonPath) == 0 {
c.New.SkeletonPath = "https://" + RevelSkeletonsImportPath + ":basic/bootstrap4" c.New.SkeletonPath = "https://" + RevelSkeletonsImportPath + ":basic/bootstrap4"
@@ -256,7 +206,7 @@ func setSkeletonPath(c *model.CommandConfig) (err error) {
c.New.SkeletonPath = fullpath c.New.SkeletonPath = fullpath
utils.Logger.Info("Set skeleton path to ", fullpath) utils.Logger.Info("Set skeleton path to ", fullpath)
if !utils.DirExists(fullpath) { if !utils.DirExists(fullpath) {
return fmt.Errorf("Failed to find skeleton in filepath %s %s", fullpath, sp.String()) return fmt.Errorf("failed to find skeleton in filepath %s %s", fullpath, sp.String())
} }
case "git": case "git":
fallthrough fallthrough
@@ -268,7 +218,6 @@ func setSkeletonPath(c *model.CommandConfig) (err error) {
} }
default: default:
utils.Logger.Fatal("Unsupported skeleton schema ", "path", c.New.SkeletonPath) utils.Logger.Fatal("Unsupported skeleton schema ", "path", c.New.SkeletonPath)
} }
// TODO check to see if the path needs to be extracted // TODO check to see if the path needs to be extracted
} else { } else {
@@ -277,7 +226,7 @@ func setSkeletonPath(c *model.CommandConfig) (err error) {
return return
} }
// Load skeleton from git // Load skeleton from git.
func newLoadFromGit(c *model.CommandConfig, sp *url.URL) (err error) { func newLoadFromGit(c *model.CommandConfig, sp *url.URL) (err error) {
// This method indicates we need to fetch from a repository using git // This method indicates we need to fetch from a repository using git
// Execute "git clone get <pkg>" // Execute "git clone get <pkg>"
@@ -323,68 +272,4 @@ func copyNewAppFiles(c *model.CommandConfig) (err error) {
// Dotfiles are skipped by mustCopyDir, so we have to explicitly copy the .gitignore. // Dotfiles are skipped by mustCopyDir, so we have to explicitly copy the .gitignore.
gitignore := ".gitignore" gitignore := ".gitignore"
return utils.CopyFile(filepath.Join(c.AppPath, gitignore), filepath.Join(c.New.SkeletonPath, gitignore)) return utils.CopyFile(filepath.Join(c.AppPath, gitignore), filepath.Join(c.New.SkeletonPath, gitignore))
} }
const (
VENDOR_GOPKG = `#
# Revel Gopkg.toml
#
# If you want to use a specific version of Revel change the branches below
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
required = ["github.com/revel/revel", "github.com/revel/modules"]
# Note to use a specific version changes this to
#
# [[override]]
# version = "0.20.1"
# name = "github.com/revel/modules"
[[override]]
branch = "master"
name = "github.com/revel/modules"
# Note to use a specific version changes this to
#
# [[override]]
# version = "0.20.0"
# name = "github.com/revel/revel"
[[override]]
branch = "master"
name = "github.com/revel/revel"
[[override]]
branch = "master"
name = "github.com/revel/log15"
[[override]]
branch = "master"
name = "github.com/revel/cron"
[[override]]
branch = "master"
name = "github.com/xeonx/timeago"
`
NEW_MAIN_FILE = `package main
`
)

View File

@@ -1,14 +1,15 @@
package main_test package main_test
import ( import (
"github.com/revel/cmd/model"
"github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
"os" "os"
"testing" "testing"
"github.com/revel/cmd/model"
main "github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
) )
// test the commands // test the commands.
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
a := assert.New(t) a := assert.New(t)
gopath := setup("revel-test-new", a) gopath := setup("revel-test-new", a)
@@ -52,4 +53,3 @@ func TestNew(t *testing.T) {
} }
} }
} }

View File

@@ -37,7 +37,7 @@ func init() {
cmdPackage.UpdateConfig = updatePackageConfig cmdPackage.UpdateConfig = updatePackageConfig
} }
// Called when unable to parse the command line automatically and assumes an old launch // Called when unable to parse the command line automatically and assumes an old launch.
func updatePackageConfig(c *model.CommandConfig, args []string) bool { func updatePackageConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.PACKAGE c.Index = model.PACKAGE
if len(args) == 0 && c.Package.ImportPath != "" { if len(args) == 0 && c.Package.ImportPath != "" {
@@ -48,26 +48,21 @@ func updatePackageConfig(c *model.CommandConfig, args []string) bool {
c.Package.Mode = args[1] c.Package.Mode = args[1]
} }
return true return true
} }
// Called to package the app // Called to package the app.
func packageApp(c *model.CommandConfig) (err error) { func packageApp(c *model.CommandConfig) (err error) {
// Determine the run mode. // Determine the run mode.
mode := DefaultRunMode mode := c.Package.Mode
if len(c.Package.Mode) >= 0 {
mode = c.Package.Mode
}
appImportPath := c.ImportPath appImportPath := c.ImportPath
revel_paths, err := model.NewRevelPaths(mode, appImportPath, c.AppPath, model.NewWrappedRevelCallback(nil, c.PackageResolver)) revelPaths, err := model.NewRevelPaths(mode, appImportPath, c.AppPath, model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil { if err != nil {
return return
} }
// Remove the archive if it already exists. // Remove the archive if it already exists.
destFile := filepath.Join(c.AppPath, filepath.Base(revel_paths.BasePath)+".tar.gz") destFile := filepath.Join(c.AppPath, filepath.Base(revelPaths.BasePath)+".tar.gz")
if c.Package.TargetPath != "" { if c.Package.TargetPath != "" {
if filepath.IsAbs(c.Package.TargetPath) { if filepath.IsAbs(c.Package.TargetPath) {
destFile = c.Package.TargetPath destFile = c.Package.TargetPath
@@ -80,13 +75,11 @@ func packageApp(c *model.CommandConfig) (err error) {
} }
// Collect stuff in a temp directory. // Collect stuff in a temp directory.
tmpDir, err := ioutil.TempDir("", filepath.Base(revel_paths.BasePath)) tmpDir, err := ioutil.TempDir("", filepath.Base(revelPaths.BasePath))
utils.PanicOnError(err, "Failed to get temp dir") utils.PanicOnError(err, "Failed to get temp dir")
// Build expects the command the build to contain the proper data // Build expects the command the build to contain the proper data
if len(c.Package.Mode) >= 0 {
c.Build.Mode = c.Package.Mode c.Build.Mode = c.Package.Mode
}
c.Build.TargetPath = tmpDir c.Build.TargetPath = tmpDir
c.Build.CopySource = c.Package.CopySource c.Build.CopySource = c.Package.CopySource
if err = buildApp(c); err != nil { if err = buildApp(c); err != nil {

View File

@@ -1,14 +1,15 @@
package main_test package main_test
import ( import (
"github.com/revel/cmd/model"
"github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
"os" "os"
"testing" "testing"
"github.com/revel/cmd/model"
main "github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
) )
// test the commands // test the commands.
func TestPackage(t *testing.T) { func TestPackage(t *testing.T) {
a := assert.New(t) a := assert.New(t)
gopath := setup("revel-test-package", a) gopath := setup("revel-test-package", a)

View File

@@ -6,6 +6,7 @@
package main package main
import ( import (
"bytes"
"flag" "flag"
"fmt" "fmt"
"math/rand" "math/rand"
@@ -14,23 +15,18 @@ import (
"strings" "strings"
"time" "time"
"github.com/jessevdk/go-flags"
"github.com/agtorre/gocolorize" "github.com/agtorre/gocolorize"
"github.com/jessevdk/go-flags"
"github.com/revel/cmd/logger" "github.com/revel/cmd/logger"
"github.com/revel/cmd/model" "github.com/revel/cmd/model"
"github.com/revel/cmd/utils" "github.com/revel/cmd/utils"
"bytes"
) )
const ( const (
// RevelCmdImportPath Revel framework cmd tool import path // RevelCmdImportPath Revel framework cmd tool import path.
RevelCmdImportPath = "github.com/revel/cmd"
// RevelCmdImportPath Revel framework cmd tool import path
RevelSkeletonsImportPath = "github.com/revel/skeletons" RevelSkeletonsImportPath = "github.com/revel/skeletons"
// DefaultRunMode for revel's application // DefaultRunMode for revel's application.
DefaultRunMode = "dev" DefaultRunMode = "dev"
) )
@@ -41,7 +37,7 @@ type Command struct {
UsageLine, Short, Long string UsageLine, Short, Long string
} }
// Name returns command name from usage line // Name returns command name from usage line.
func (cmd *Command) Name() string { func (cmd *Command) Name() string {
name := cmd.UsageLine name := cmd.UsageLine
i := strings.Index(name, " ") i := strings.Index(name, " ")
@@ -51,7 +47,7 @@ func (cmd *Command) Name() string {
return name return name
} }
// The commands // Commands defines the available commands.
var Commands = []*Command{ var Commands = []*Command{
nil, // Safety net, prevent missing index from running nil, // Safety net, prevent missing index from running
cmdNew, cmdNew,
@@ -109,7 +105,7 @@ func main() {
} }
} }
// Parse the arguments passed into the model.CommandConfig // Parse the arguments passed into the model.CommandConfig.
func ParseArgs(c *model.CommandConfig, parser *flags.Parser, args []string) (err error) { func ParseArgs(c *model.CommandConfig, parser *flags.Parser, args []string) (err error) {
var extraArgs []string var extraArgs []string
if ini := flag.String("ini", "none", ""); *ini != "none" { if ini := flag.String("ini", "none", ""); *ini != "none" {
@@ -119,7 +115,8 @@ func ParseArgs(c *model.CommandConfig, parser *flags.Parser, args []string) (err
} else { } else {
if extraArgs, err = parser.ParseArgs(args); err != nil { if extraArgs, err = parser.ParseArgs(args); err != nil {
return return
} else { }
switch parser.Active.Name { switch parser.Active.Name {
case "new": case "new":
c.Index = model.NEW c.Index = model.NEW
@@ -137,12 +134,11 @@ func ParseArgs(c *model.CommandConfig, parser *flags.Parser, args []string) (err
c.Index = model.VERSION c.Index = model.VERSION
} }
} }
}
if !Commands[c.Index].UpdateConfig(c, extraArgs) { if !Commands[c.Index].UpdateConfig(c, extraArgs) {
buffer := &bytes.Buffer{} buffer := &bytes.Buffer{}
parser.WriteHelp(buffer) parser.WriteHelp(buffer)
err = fmt.Errorf("Invalid command line arguements %v\n%s", extraArgs, buffer.String()) err = fmt.Errorf("invalid command line arguments %v\n%s", extraArgs, buffer.String())
} }
return return

View File

@@ -5,13 +5,14 @@
package main package main
import ( import (
"strconv"
"encoding/json" "encoding/json"
"fmt" "fmt"
"os"
"strconv"
"github.com/revel/cmd/harness" "github.com/revel/cmd/harness"
"github.com/revel/cmd/model" "github.com/revel/cmd/model"
"github.com/revel/cmd/utils" "github.com/revel/cmd/utils"
"os"
) )
var cmdRun = &Command{ var cmdRun = &Command{
@@ -34,13 +35,6 @@ You can set a port as well. For example:
revel run -m prod -p 8080 github.com/revel/examples/chat `, revel run -m prod -p 8080 github.com/revel/examples/chat `,
} }
// RunArgs holds revel run parameters
type RunArgs struct {
ImportPath string
Mode string
Port int
}
func init() { func init() {
cmdRun.RunWith = runApp cmdRun.RunWith = runApp
cmdRun.UpdateConfig = updateRunConfig cmdRun.UpdateConfig = updateRunConfig
@@ -112,55 +106,55 @@ func updateRunConfig(c *model.CommandConfig, args []string) bool {
return true return true
} }
// Returns true if this is an absolute path or a relative gopath // Returns true if this is an absolute path or a relative gopath.
func runIsImportPath(pathToCheck string) bool { func runIsImportPath(pathToCheck string) bool {
return utils.DirExists(pathToCheck) return utils.DirExists(pathToCheck)
} }
// Called to run the app // Called to run the app.
func runApp(c *model.CommandConfig) (err error) { func runApp(c *model.CommandConfig) (err error) {
if c.Run.Mode == "" { if c.Run.Mode == "" {
c.Run.Mode = "dev" c.Run.Mode = "dev"
} }
revel_path, err := model.NewRevelPaths(c.Run.Mode, c.ImportPath, c.AppPath, model.NewWrappedRevelCallback(nil, c.PackageResolver)) revelPath, err := model.NewRevelPaths(c.Run.Mode, c.ImportPath, c.AppPath, model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil { if err != nil {
return utils.NewBuildIfError(err, "Revel paths") return utils.NewBuildIfError(err, "Revel paths")
} }
if c.Run.Port > -1 { if c.Run.Port > -1 {
revel_path.HTTPPort = c.Run.Port revelPath.HTTPPort = c.Run.Port
} else { } else {
c.Run.Port = revel_path.HTTPPort c.Run.Port = revelPath.HTTPPort
} }
utils.Logger.Infof("Running %s (%s) in %s mode\n", revel_path.AppName, revel_path.ImportPath, revel_path.RunMode) utils.Logger.Infof("Running %s (%s) in %s mode\n", revelPath.AppName, revelPath.ImportPath, revelPath.RunMode)
utils.Logger.Debug("Base path:", "path", revel_path.BasePath) utils.Logger.Debug("Base path:", "path", revelPath.BasePath)
// If the app is run in "watched" mode, use the harness to run it. // If the app is run in "watched" mode, use the harness to run it.
if revel_path.Config.BoolDefault("watch", true) && revel_path.Config.BoolDefault("watch.code", true) { if revelPath.Config.BoolDefault("watch", true) && revelPath.Config.BoolDefault("watch.code", true) {
utils.Logger.Info("Running in watched mode.") utils.Logger.Info("Running in watched mode.")
runMode := fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v}`, revel_path.RunMode, c.Verbose) runMode := fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v}`, revelPath.RunMode, c.Verbose)
if c.HistoricMode { if c.HistoricMode {
runMode = revel_path.RunMode runMode = revelPath.RunMode
} }
// **** Never returns. // **** Never returns.
harness.NewHarness(c, revel_path, runMode, c.Run.NoProxy).Run() harness.NewHarness(c, revelPath, runMode, c.Run.NoProxy).Run()
} }
// Else, just build and run the app. // Else, just build and run the app.
utils.Logger.Debug("Running in live build mode.") utils.Logger.Debug("Running in live build mode.")
app, err := harness.Build(c, revel_path) app, err := harness.Build(c, revelPath)
if err != nil { if err != nil {
utils.Logger.Errorf("Failed to build app: %s", err) utils.Logger.Errorf("Failed to build app: %s", err)
} }
app.Port = revel_path.HTTPPort app.Port = revelPath.HTTPPort
var paths []byte var paths []byte
if len(app.PackagePathMap) > 0 { if len(app.PackagePathMap) > 0 {
paths, _ = json.Marshal(app.PackagePathMap) paths, _ = json.Marshal(app.PackagePathMap)
} }
runMode := fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v,"packagePathMap":%s}`, app.Paths.RunMode, c.Verbose, string(paths)) runMode := fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v,"packagePathMap":%s}`, app.Paths.RunMode, c.Verbose, string(paths))
if c.HistoricMode { if c.HistoricMode {
runMode = revel_path.RunMode runMode = revelPath.RunMode
} }
app.Cmd(runMode).Run(c) app.Cmd(runMode).Run(c)
return return

View File

@@ -1,12 +1,13 @@
package main_test package main_test
import ( import (
"github.com/stretchr/testify/assert"
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
// test the commands // test the commands.
func TestRun(t *testing.T) { func TestRun(t *testing.T) {
a := assert.New(t) a := assert.New(t)
gopath := setup("revel-test-run", a) gopath := setup("revel-test-run", a)

View File

@@ -52,7 +52,7 @@ func init() {
cmdTest.UpdateConfig = updateTestConfig cmdTest.UpdateConfig = updateTestConfig
} }
// Called to update the config command with from the older stype // Called to update the config command with from the older stype.
func updateTestConfig(c *model.CommandConfig, args []string) bool { func updateTestConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.TEST c.Index = model.TEST
if len(args) == 0 && c.Test.ImportPath != "" { if len(args) == 0 && c.Test.ImportPath != "" {
@@ -74,7 +74,7 @@ func updateTestConfig(c *model.CommandConfig, args []string) bool {
return true return true
} }
// Called to test the application // Called to test the application.
func testApp(c *model.CommandConfig) (err error) { func testApp(c *model.CommandConfig) (err error) {
mode := DefaultRunMode mode := DefaultRunMode
if c.Test.Mode != "" { if c.Test.Mode != "" {
@@ -82,7 +82,7 @@ func testApp(c *model.CommandConfig) (err error) {
} }
// Find and parse app.conf // Find and parse app.conf
revel_path, err := model.NewRevelPaths(mode, c.ImportPath, c.AppPath, model.NewWrappedRevelCallback(nil, c.PackageResolver)) revelPath, err := model.NewRevelPaths(mode, c.ImportPath, c.AppPath, model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil { if err != nil {
return return
} }
@@ -90,7 +90,7 @@ func testApp(c *model.CommandConfig) (err error) {
// todo Ensure that the testrunner is loaded in this mode. // todo Ensure that the testrunner is loaded in this mode.
// Create a directory to hold the test result files. // Create a directory to hold the test result files.
resultPath := filepath.Join(revel_path.BasePath, "test-results") resultPath := filepath.Join(revelPath.BasePath, "test-results")
if err = os.RemoveAll(resultPath); err != nil { if err = os.RemoveAll(resultPath); err != nil {
return utils.NewBuildError("Failed to remove test result directory ", "path", resultPath, "error", err) return utils.NewBuildError("Failed to remove test result directory ", "path", resultPath, "error", err)
} }
@@ -104,7 +104,7 @@ func testApp(c *model.CommandConfig) (err error) {
return utils.NewBuildError("Failed to create test result log file: ", "error", err) return utils.NewBuildError("Failed to create test result log file: ", "error", err)
} }
app, reverr := harness.Build(c, revel_path) app, reverr := harness.Build(c, revelPath)
if reverr != nil { if reverr != nil {
return utils.NewBuildIfError(reverr, "Error building: ") return utils.NewBuildIfError(reverr, "Error building: ")
} }
@@ -128,20 +128,20 @@ func testApp(c *model.CommandConfig) (err error) {
} }
defer cmd.Kill() defer cmd.Kill()
var httpAddr = revel_path.HTTPAddr httpAddr := revelPath.HTTPAddr
if httpAddr == "" { if httpAddr == "" {
httpAddr = "localhost" httpAddr = "localhost"
} }
var httpProto = "http" httpProto := "http"
if revel_path.HTTPSsl { if revelPath.HTTPSsl {
httpProto = "https" httpProto = "https"
} }
// Get a list of tests // Get a list of tests
var baseURL = fmt.Sprintf("%s://%s:%d", httpProto, httpAddr, revel_path.HTTPPort) baseURL := fmt.Sprintf("%s://%s:%d", httpProto, httpAddr, revelPath.HTTPPort)
utils.Logger.Infof("Testing %s (%s) in %s mode URL %s \n", revel_path.AppName, revel_path.ImportPath, mode, baseURL) utils.Logger.Infof("Testing %s (%s) in %s mode URL %s \n", revelPath.AppName, revelPath.ImportPath, mode, baseURL)
testSuites, _ := getTestsList(baseURL) testSuites, _ := getTestsList(baseURL)
// If a specific TestSuite[.Method] is specified, only run that suite/test // If a specific TestSuite[.Method] is specified, only run that suite/test
@@ -154,7 +154,7 @@ func testApp(c *model.CommandConfig) (err error) {
fmt.Println() fmt.Println()
// Run each suite. // Run each suite.
failedResults, overallSuccess := runTestSuites(revel_path, baseURL, resultPath, testSuites) failedResults, overallSuccess := runTestSuites(revelPath, baseURL, resultPath, testSuites)
fmt.Println() fmt.Println()
if overallSuccess { if overallSuccess {
@@ -177,14 +177,14 @@ func testApp(c *model.CommandConfig) (err error) {
return return
} }
// Outputs the results to a file // Outputs the results to a file.
func writeResultFile(resultPath, name, content string) { func writeResultFile(resultPath, name, content string) {
if err := ioutil.WriteFile(filepath.Join(resultPath, name), []byte(content), 0666); err != nil { if err := ioutil.WriteFile(filepath.Join(resultPath, name), []byte(content), 0666); err != nil {
utils.Logger.Errorf("Failed to write result file %s: %s", filepath.Join(resultPath, name), err) utils.Logger.Errorf("Failed to write result file %s: %s", filepath.Join(resultPath, name), err)
} }
} }
// Determines if response should be plural // Determines if response should be plural.
func pluralize(num int, singular, plural string) string { func pluralize(num int, singular, plural string) string {
if num == 1 { if num == 1 {
return singular return singular
@@ -193,7 +193,7 @@ func pluralize(num int, singular, plural string) string {
} }
// Filters test suites and individual tests to match // Filters test suites and individual tests to match
// the parsed command line parameter // the parsed command line parameter.
func filterTestSuites(suites *[]tests.TestSuiteDesc, suiteArgument string) *[]tests.TestSuiteDesc { func filterTestSuites(suites *[]tests.TestSuiteDesc, suiteArgument string) *[]tests.TestSuiteDesc {
var suiteName, testName string var suiteName, testName string
argArray := strings.Split(suiteArgument, ".") argArray := strings.Split(suiteArgument, ".")
@@ -263,9 +263,8 @@ func getTestsList(baseURL string) (*[]tests.TestSuiteDesc, error) {
return &testSuites, err return &testSuites, err
} }
// Run the testsuites using the container // Run the testsuites using the container.
func runTestSuites(paths *model.RevelContainer, baseURL, resultPath string, testSuites *[]tests.TestSuiteDesc) (*[]tests.TestSuiteResult, bool) { func runTestSuites(paths *model.RevelContainer, baseURL, resultPath string, testSuites *[]tests.TestSuiteDesc) (*[]tests.TestSuiteResult, bool) {
// We can determine the testsuite location by finding the test module and extracting the data from it // We can determine the testsuite location by finding the test module and extracting the data from it
resultFilePath := filepath.Join(paths.ModulePathMap["testrunner"].Path, "app", "views", "TestRunner/SuiteResult.html") resultFilePath := filepath.Join(paths.ModulePathMap["testrunner"].Path, "app", "views", "TestRunner/SuiteResult.html")

View File

@@ -1,15 +1,15 @@
package main_test package main_test
import ( import (
"github.com/revel/cmd/model"
"github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
"os" "os"
"testing" "testing"
"github.com/revel/cmd/model"
main "github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
) )
// test the commands.
// test the commands
func TestRevelTest(t *testing.T) { func TestRevelTest(t *testing.T) {
a := assert.New(t) a := assert.New(t)
gopath := setup("revel-test-test", a) gopath := setup("revel-test-test", a)

View File

@@ -9,11 +9,8 @@
package main package main
import ( import (
"bytes"
"fmt" "fmt"
"github.com/revel/cmd"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"go/ast" "go/ast"
"go/parser" "go/parser"
"go/token" "go/token"
@@ -23,11 +20,14 @@ import (
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
"bytes"
"github.com/revel/cmd"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
) )
type ( type (
// The version container // The version container.
VersionCommand struct { VersionCommand struct {
Command *model.CommandConfig // The command Command *model.CommandConfig // The command
revelVersion *model.Version // The Revel framework version revelVersion *model.Version // The Revel framework version
@@ -54,7 +54,7 @@ func init() {
cmdVersion.RunWith = v.RunWith cmdVersion.RunWith = v.RunWith
} }
// Update the version // Update the version.
func (v *VersionCommand) UpdateConfig(c *model.CommandConfig, args []string) bool { func (v *VersionCommand) UpdateConfig(c *model.CommandConfig, args []string) bool {
if len(args) > 0 { if len(args) > 0 {
c.Version.ImportPath = args[0] c.Version.ImportPath = args[0]
@@ -62,7 +62,7 @@ func (v *VersionCommand) UpdateConfig(c *model.CommandConfig, args []string) boo
return true return true
} }
// Displays the version of go and Revel // Displays the version of go and Revel.
func (v *VersionCommand) RunWith(c *model.CommandConfig) (err error) { func (v *VersionCommand) RunWith(c *model.CommandConfig) (err error) {
utils.Logger.Info("Requesting version information", "config", c) utils.Logger.Info("Requesting version information", "config", c)
v.Command = c v.Command = c
@@ -73,7 +73,6 @@ func (v *VersionCommand) RunWith(c *model.CommandConfig) (err error) {
needsUpdates := true needsUpdates := true
versionInfo := "" versionInfo := ""
for x := 0; x < 2 && needsUpdates; x++ { for x := 0; x < 2 && needsUpdates; x++ {
needsUpdates = false
versionInfo, needsUpdates = v.doRepoCheck(x == 0) versionInfo, needsUpdates = v.doRepoCheck(x == 0)
} }
@@ -89,7 +88,7 @@ func (v *VersionCommand) RunWith(c *model.CommandConfig) (err error) {
return return
} }
// Checks the Revel repos for the latest version // Checks the Revel repos for the latest version.
func (v *VersionCommand) doRepoCheck(updateLibs bool) (versionInfo string, needsUpdate bool) { func (v *VersionCommand) doRepoCheck(updateLibs bool) (versionInfo string, needsUpdate bool) {
var ( var (
title string title string
@@ -110,25 +109,12 @@ func (v *VersionCommand) doRepoCheck(updateLibs bool) (versionInfo string, needs
} }
// Only do an update on the first loop, and if specified to update // Only do an update on the first loop, and if specified to update
versionInfo = versionInfo + v.outputVersion(title, repo, localVersion, versonFromRepo) versionInfo += v.outputVersion(title, repo, localVersion, versonFromRepo)
} }
return return
} }
// Checks for updates if needed // Prints out the local and remote versions, calls update if needed.
func (v *VersionCommand) doUpdate(title, repo string, local, remote *model.Version) {
utils.Logger.Info("Updating package", "package", title, "repo", repo)
fmt.Println("Attempting to update package", title)
if err := v.Command.PackageResolver(repo); err != nil {
utils.Logger.Error("Unable to update repo", "repo", repo, "error", err)
} else if repo == "github.com/revel/cmd/revel" {
// One extra step required here to run the install for the command
utils.Logger.Fatal("Revel command tool was updated, you must manually run the following command before continuing\ngo install github.com/revel/cmd/revel")
}
return
}
// Prints out the local and remote versions, calls update if needed
func (v *VersionCommand) outputVersion(title, repo string, local, remote *model.Version) (output string) { func (v *VersionCommand) outputVersion(title, repo string, local, remote *model.Version) (output string) {
buffer := &bytes.Buffer{} buffer := &bytes.Buffer{}
remoteVersion := "Unknown" remoteVersion := "Unknown"
@@ -144,7 +130,7 @@ func (v *VersionCommand) outputVersion(title, repo string, local, remote *model.
return buffer.String() return buffer.String()
} }
// Returns the version from the repository // Returns the version from the repository.
func (v *VersionCommand) versionFromRepo(repoName, branchName, fileName string) (version *model.Version, err error) { func (v *VersionCommand) versionFromRepo(repoName, branchName, fileName string) (version *model.Version, err error) {
if branchName == "" { if branchName == "" {
branchName = "master" branchName = "master"
@@ -166,10 +152,6 @@ func (v *VersionCommand) versionFromRepo(repoName, branchName, fileName string)
return v.versionFromBytes(body) return v.versionFromBytes(body)
} }
// Returns version information from a file called version on the gopath
func (v *VersionCommand) compareAndUpdateVersion(remoteVersion *model.Version, localVersion *model.Version) (err error) {
return
}
func (v *VersionCommand) versionFromFilepath(sourcePath string) (version *model.Version, err error) { func (v *VersionCommand) versionFromFilepath(sourcePath string) (version *model.Version, err error) {
utils.Logger.Info("Fullpath to revel", "dir", sourcePath) utils.Logger.Info("Fullpath to revel", "dir", sourcePath)
@@ -180,7 +162,7 @@ func (v *VersionCommand) versionFromFilepath(sourcePath string) (version *model.
return v.versionFromBytes(sourceStream) return v.versionFromBytes(sourceStream)
} }
// Returns version information from a file called version on the gopath // Returns version information from a file called version on the gopath.
func (v *VersionCommand) versionFromBytes(sourceStream []byte) (version *model.Version, err error) { func (v *VersionCommand) versionFromBytes(sourceStream []byte) (version *model.Version, err error) {
fset := token.NewFileSet() // positions are relative to fset fset := token.NewFileSet() // positions are relative to fset
@@ -206,7 +188,7 @@ func (v *VersionCommand) versionFromBytes(sourceStream []byte) (version *model.V
r := spec.Values[0].(*ast.BasicLit) r := spec.Values[0].(*ast.BasicLit)
switch spec.Names[0].Name { switch spec.Names[0].Name {
case "Version": case "Version":
version.ParseVersion(strings.Replace(r.Value, `"`, "", -1)) version.ParseVersion(strings.ReplaceAll(r.Value, `"`, ""))
case "BuildDate": case "BuildDate":
version.BuildDate = r.Value version.BuildDate = r.Value
case "MinimumGoVersion": case "MinimumGoVersion":
@@ -217,7 +199,7 @@ func (v *VersionCommand) versionFromBytes(sourceStream []byte) (version *model.V
return return
} }
// Fetch the local version of revel from the file system // Fetch the local version of revel from the file system.
func (v *VersionCommand) updateLocalVersions() { func (v *VersionCommand) updateLocalVersions() {
v.cmdVersion = &model.Version{} v.cmdVersion = &model.Version{}
v.cmdVersion.ParseVersion(cmd.Version) v.cmdVersion.ParseVersion(cmd.Version)
@@ -243,6 +225,4 @@ func (v *VersionCommand) updateLocalVersions() {
if err != nil { if err != nil {
utils.Logger.Warn("Unable to extract version information from Revel Modules", "path", pathMap[model.RevelModulesImportPath], "error", err) utils.Logger.Warn("Unable to extract version information from Revel Modules", "path", pathMap[model.RevelModulesImportPath], "error", err)
} }
return
} }

View File

@@ -1,15 +1,16 @@
package main_test package main_test
import ( import (
"github.com/revel/cmd/model"
"github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/revel/cmd/model"
main "github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
) )
// test the commands // test the commands.
func TestVersion(t *testing.T) { func TestVersion(t *testing.T) {
a := assert.New(t) a := assert.New(t)
gopath := setup("revel-test-version", a) gopath := setup("revel-test-version", a)

View File

@@ -5,12 +5,8 @@
package tests package tests
import ( import (
"fmt"
"html/template" "html/template"
"reflect" "reflect"
"strings"
"github.com/revel/cmd/utils"
) )
// TestSuiteDesc is used for storing information about a single test suite. // TestSuiteDesc is used for storing information about a single test suite.
@@ -46,111 +42,3 @@ type TestResult struct {
ErrorHTML template.HTML ErrorHTML template.HTML
ErrorSummary string ErrorSummary string
} }
var (
testSuites []TestSuiteDesc // A list of all available tests.
none = []reflect.Value{} // It is used as input for reflect call in a few places.
// registeredTests simplifies the search of test suites by their name.
// "TestSuite.TestName" is used as a key. Value represents index in testSuites.
registeredTests map[string]int
)
/*
Below are helper functions.
*/
// describeSuite expects testsuite interface as input parameter
// and returns its description in a form of TestSuiteDesc structure.
func describeSuite(testSuite interface{}) TestSuiteDesc {
t := reflect.TypeOf(testSuite)
// Get a list of methods of the embedded test type.
// It will be used to make sure the same tests are not included in multiple test suites.
super := t.Elem().Field(0).Type
superMethods := map[string]bool{}
for i := 0; i < super.NumMethod(); i++ {
// Save the current method's name.
superMethods[super.Method(i).Name] = true
}
// Get a list of methods on the test suite that take no parameters, return
// no results, and were not part of the embedded type's method set.
var tests []TestDesc
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
mt := m.Type
// Make sure the test method meets the criterias:
// - method of testSuite without input parameters;
// - nothing is returned;
// - has "Test" prefix;
// - doesn't belong to the embedded structure.
methodWithoutParams := (mt.NumIn() == 1 && mt.In(0) == t)
nothingReturned := (mt.NumOut() == 0)
hasTestPrefix := (strings.HasPrefix(m.Name, "Test"))
if methodWithoutParams && nothingReturned && hasTestPrefix && !superMethods[m.Name] {
// Register the test suite's index so we can quickly find it by test's name later.
registeredTests[t.Elem().Name()+"."+m.Name] = len(testSuites)
// Add test to the list of tests.
tests = append(tests, TestDesc{m.Name})
}
}
return TestSuiteDesc{
Name: t.Elem().Name(),
Tests: tests,
Elem: t.Elem(),
}
}
// errorSummary gets an error and returns its summary in human readable format.
func errorSummary(err *utils.SourceError) (message string) {
expectedPrefix := "(expected)"
actualPrefix := "(actual)"
errDesc := err.Description
//strip the actual/expected stuff to provide more condensed display.
if strings.Index(errDesc, expectedPrefix) == 0 {
errDesc = errDesc[len(expectedPrefix):]
}
if strings.LastIndex(errDesc, actualPrefix) > 0 {
errDesc = errDesc[0 : len(errDesc)-len(actualPrefix)]
}
errFile := err.Path
slashIdx := strings.LastIndex(errFile, "/")
if slashIdx > 0 {
errFile = errFile[slashIdx+1:]
}
message = fmt.Sprintf("%s %s#%d", errDesc, errFile, err.Line)
/*
// If line of error isn't known return the message as is.
if err.Line == 0 {
return
}
// Otherwise, include info about the line number and the relevant
// source code lines.
message += fmt.Sprintf(" (around line %d): ", err.Line)
for _, line := range err.ContextSource() {
if line.IsError {
message += line.Source
}
}
*/
return
}
//sortbySuiteName sorts the testsuites by name.
type sortBySuiteName []interface{}
func (a sortBySuiteName) Len() int { return len(a) }
func (a sortBySuiteName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a sortBySuiteName) Less(i, j int) bool {
return reflect.TypeOf(a[i]).Elem().Name() < reflect.TypeOf(a[j]).Elem().Name()
}

View File

@@ -2,9 +2,10 @@ package utils
import ( import (
"fmt" "fmt"
"github.com/revel/cmd/logger"
"strconv"
"regexp" "regexp"
"strconv"
"github.com/revel/cmd/logger"
) )
type ( type (
@@ -15,7 +16,7 @@ type (
} }
) )
// Returns a new builed error // Returns a new builed error.
func NewBuildError(message string, args ...interface{}) (b *BuildError) { func NewBuildError(message string, args ...interface{}) (b *BuildError) {
Logger.Info(message, args...) Logger.Info(message, args...)
b = &BuildError{} b = &BuildError{}
@@ -26,22 +27,23 @@ func NewBuildError(message string, args ...interface{}) (b *BuildError) {
return b 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) { func NewBuildIfError(err error, message string, args ...interface{}) (b error) {
if err != nil { if err != nil {
if berr, ok := err.(*BuildError); ok { if berr, ok := err.(*BuildError); ok {
// This is already a build error so just append the args // This is already a build error so just append the args
berr.Args = append(berr.Args, args...) berr.Args = append(berr.Args, args...)
return berr return berr
} else { }
args = append(args, "error", err.Error()) args = append(args, "error", err.Error())
b = NewBuildError(message, args...) b = NewBuildError(message, args...)
} }
}
return return
} }
// BuildError implements Error() string // BuildError implements Error() string.
func (b *BuildError) Error() string { func (b *BuildError) Error() string {
return fmt.Sprint(b.Message, b.Args) return fmt.Sprint(b.Message, b.Args)
} }
@@ -70,7 +72,6 @@ func NewCompileError(importPath, errorLink string, error error) *SourceError {
Logger.Error("Build errors", "errors", error) Logger.Error("Build errors", "errors", error)
} }
// Read the source for the offending file. // Read the source for the offending file.
var ( var (
relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go" relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go"

View File

@@ -1,15 +1,15 @@
package utils package utils
import ( import (
"bytes"
"go/build" "go/build"
"os" "os"
"os/exec" "os/exec"
"strings"
"bytes"
"path/filepath" "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) { func CmdInit(c *exec.Cmd, addGoPath bool, basePath string) {
c.Dir = basePath c.Dir = basePath
// Dep does not like paths that are not real, convert all paths in go to real paths // Dep does not like paths that are not real, convert all paths in go to real paths

View File

@@ -6,7 +6,7 @@ import (
"strings" "strings"
) )
// The error is a wrapper for the // The error is a wrapper for the.
type ( type (
SourceError struct { SourceError struct {
SourceType string // The type of source that failed to build. SourceType string // The type of source that failed to build.
@@ -23,7 +23,8 @@ type (
IsError bool IsError bool
} }
) )
// Return a new error object
// Return a new error object.
func NewError(source, title, path, description string) *SourceError { func NewError(source, title, path, description string) *SourceError {
return &SourceError{ return &SourceError{
SourceType: source, SourceType: source,
@@ -33,17 +34,17 @@ func NewError(source, title, path, description string) *SourceError {
} }
} }
// 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) { func (e *SourceError) SetLink(errorLink string) {
errorLink = strings.Replace(errorLink, "{{Path}}", e.Path, -1) errorLink = strings.ReplaceAll(errorLink, "{{Path}}", e.Path)
errorLink = strings.Replace(errorLink, "{{Line}}", strconv.Itoa(e.Line), -1) errorLink = strings.ReplaceAll(errorLink, "{{Line}}", strconv.Itoa(e.Line))
e.Link = "<a href=" + errorLink + ">" + e.Path + ":" + strconv.Itoa(e.Line) + "</a>" e.Link = "<a href=" + errorLink + ">" + e.Path + ":" + strconv.Itoa(e.Line) + "</a>"
} }
// Error method constructs a plaintext version of the error, taking // Error method constructs a plaintext version of the error, taking
// account that fields are optionally set. Returns e.g. Compilation Error // 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 { func (e *SourceError) Error() string {
if e == nil { if e == nil {
panic("opps") panic("opps")

View File

@@ -4,14 +4,15 @@ import (
"archive/tar" "archive/tar"
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"fmt"
"errors" "errors"
"fmt"
"html/template" "html/template"
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"golang.org/x/tools/go/packages" "golang.org/x/tools/go/packages"
) )
@@ -39,9 +40,8 @@ func ReadLines(filename string) ([]string, error) {
return strings.Split(string(dataBytes), "\n"), nil return strings.Split(string(dataBytes), "\n"), nil
} }
// Copy file returns error // Copy file returns error.
func CopyFile(destFilename, srcFilename string) (err error) { func CopyFile(destFilename, srcFilename string) (err error) {
destFile, err := os.Create(destFilename) destFile, err := os.Create(destFilename)
if err != nil { if err != nil {
return NewBuildIfError(err, "Failed to create file", "file", destFilename) return NewBuildIfError(err, "Failed to create file", "file", destFilename)
@@ -105,7 +105,7 @@ func GenerateTemplate(filename, templateSource string, args map[string]interface
return 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) { func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
tmpl, err := template.ParseFiles(srcPath) tmpl, err := template.ParseFiles(srcPath)
if err != nil { if err != nil {
@@ -129,7 +129,7 @@ func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
return 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) { func RenderTemplateToStream(output io.Writer, srcPath []string, data interface{}) (err error) {
tmpl, err := template.ParseFiles(srcPath...) tmpl, err := template.ParseFiles(srcPath...)
if err != nil { if err != nil {
@@ -148,7 +148,7 @@ func MustChmod(filename string, mode os.FileMode) {
PanicOnError(err, fmt.Sprintf("Failed to chmod %d %q", mode, filename)) PanicOnError(err, fmt.Sprintf("Failed to chmod %d %q", mode, filename))
} }
// Called if panic // Called if panic.
func PanicOnError(err error, msg string) { func PanicOnError(err error, msg string) {
if revErr, ok := err.(*SourceError); (ok && revErr != nil) || (!ok && err != nil) { if revErr, ok := err.(*SourceError); (ok && revErr != nil) || (!ok && err != nil) {
Logger.Panicf("Abort: %s: %s %s", msg, revErr, err) Logger.Panicf("Abort: %s: %s %s", msg, revErr, err)
@@ -188,7 +188,6 @@ func CopyDir(destDir, srcDir string, data map[string]interface{}) error {
// If this file ends in ".template", render it as a template. // If this file ends in ".template", render it as a template.
if strings.HasSuffix(relSrcPath, ".template") { if strings.HasSuffix(relSrcPath, ".template") {
return RenderTemplate(destPath[:len(destPath)-len(".template")], srcPath, data) return RenderTemplate(destPath[:len(destPath)-len(".template")], srcPath, data)
} }
@@ -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 { func Walk(root string, walkFn filepath.WalkFunc) error {
return fsWalk(root, root, walkFn) return fsWalk(root, root, walkFn)
} }
// Walk the path tree using the function // 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 { func fsWalk(fname string, linkName string, walkFn filepath.WalkFunc) error {
fsWalkFunc := func(path string, info os.FileInfo, err error) error { fsWalkFunc := func(path string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
@@ -244,7 +243,7 @@ func fsWalk(fname string, linkName string, walkFn filepath.WalkFunc) error {
return err return err
} }
// Tar gz the folder // Tar gz the folder.
func TarGzDir(destFilename, srcDir string) (name string, err error) { func TarGzDir(destFilename, srcDir string) (name string, err error) {
zipFile, err := os.Create(destFilename) zipFile, err := os.Create(destFilename)
if err != nil { 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 { 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() { if info.IsDir() {
return nil return nil
} }
@@ -300,7 +303,7 @@ func TarGzDir(destFilename, srcDir string) (name string, err error) {
return zipFile.Name(), err return zipFile.Name(), err
} }
// Return true if the file exists // Return true if the file exists.
func Exists(filename string) bool { func Exists(filename string) bool {
_, err := os.Stat(filename) _, err := os.Stat(filename)
return err == nil return err == nil
@@ -324,7 +327,7 @@ func Empty(dirname string) bool {
return len(results) == 0 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) { func FindSrcPaths(appPath string, packageList []string, packageResolver func(pkgName string) error) (sourcePathsmap map[string]string, err error) {
sourcePathsmap, missingList, err := findSrcPaths(appPath, packageList) sourcePathsmap, missingList, err := findSrcPaths(appPath, packageList)
if err != nil && packageResolver != nil || len(missingList) > 0 { if err != nil && packageResolver != nil || len(missingList) > 0 {
@@ -345,10 +348,12 @@ func FindSrcPaths(appPath string, packageList []string, packageResolver func(pkg
return return
} }
var NO_APP_FOUND = errors.New("No app found") var (
var NO_REVEL_FOUND = errors.New("No revel found") 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 // 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) { func findSrcPaths(appPath string, packagesList []string) (sourcePathsmap map[string]string, missingList []string, err error) {
// Use packages to fetch // Use packages to fetch
// by not specifying env, we will use the default env // by not specifying env, we will use the default env
@@ -371,7 +376,6 @@ func findSrcPaths(appPath string, packagesList []string) (sourcePathsmap map[str
if pck.Errors != nil && len(pck.Errors) > 0 { 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) log.Error("Error ", "count", len(pck.Errors), "App Import Path", pck.ID, "filesystem path", pck.PkgPath, "errors", pck.Errors)
// continue // continue
} }
// a,_ := pck.MarshalJSON() // a,_ := pck.MarshalJSON()
log.Info("Found ", "count", len(pck.GoFiles), "App Import Path", pck.ID, "apppath", appPath) log.Info("Found ", "count", len(pck.GoFiles), "App Import Path", pck.ID, "apppath", appPath)

View File

@@ -2,10 +2,11 @@ package utils
import ( import (
"fmt" "fmt"
"github.com/revel/cmd/logger"
"github.com/revel/config"
"os" "os"
"strings" "strings"
"github.com/revel/cmd/logger"
"github.com/revel/config"
) )
var Logger = logger.New() 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 // 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{}) { func Retry(format string, args ...interface{}) {
// Ensure the user's command prompt starts on the next line. // Ensure the user's command prompt starts on the next line.
if !strings.HasSuffix(format, "\n") { if !strings.HasSuffix(format, "\n") {

View File

@@ -1,6 +1,6 @@
package utils 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 { func ContainsString(list []string, target string) bool {
for _, el := range list { for _, el := range list {
if el == target { if el == target {

View File

@@ -5,12 +5,12 @@
package cmd package cmd
const ( const (
// Version current Revel version // Version current Revel version.
Version = "1.0.0" Version = "1.0.0"
// BuildDate latest commit/release date // BuildDate latest commit/release date.
BuildDate = "2020-07-11" BuildDate = "2020-07-11"
// MinimumGoVersion minimum required Go version for Revel // MinimumGoVersion minimum required Go version for Revel.
MinimumGoVersion = ">= go1.12" MinimumGoVersion = ">= go1.12"
) )

View File

@@ -9,11 +9,11 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"sync" "sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/revel/cmd/model" "github.com/revel/cmd/model"
"github.com/revel/cmd/utils" "github.com/revel/cmd/utils"
"github.com/fsnotify/fsnotify"
"time"
) )
// Listener is an interface for receivers of filesystem events. // Listener is an interface for receivers of filesystem events.
@@ -49,7 +49,7 @@ type Watcher struct {
refreshTimerMS time.Duration // The number of milliseconds between refreshing builds refreshTimerMS time.Duration // The number of milliseconds between refreshing builds
} }
// Creates a new watched based on the container // Creates a new watched based on the container.
func NewWatcher(paths *model.RevelContainer, eagerRefresh bool) *Watcher { func NewWatcher(paths *model.RevelContainer, eagerRefresh bool) *Watcher {
return &Watcher{ return &Watcher{
forceRefresh: false, forceRefresh: false,
@@ -109,9 +109,7 @@ func (w *Watcher) Listen(listener Listener, roots ...string) {
continue continue
} }
var watcherWalker func(path string, info os.FileInfo, err error) error watcherWalker := func(path string, info os.FileInfo, err error) error {
watcherWalker = func(path string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
utils.Logger.Fatal("Watcher: Error walking path:", "error", err) utils.Logger.Fatal("Watcher: Error walking path:", "error", err)
return nil return nil
@@ -150,7 +148,6 @@ func (w *Watcher) Listen(listener Listener, roots ...string) {
// NotifyWhenUpdated notifies the watcher when a file event is received. // NotifyWhenUpdated notifies the watcher when a file event is received.
func (w *Watcher) NotifyWhenUpdated(listener Listener, watcher *fsnotify.Watcher) { func (w *Watcher) NotifyWhenUpdated(listener Listener, watcher *fsnotify.Watcher) {
for { for {
select { select {
case ev := <-watcher.Events: case ev := <-watcher.Events:
@@ -218,18 +215,18 @@ func (w *Watcher) Notify() *utils.SourceError {
w.lastError = i w.lastError = i
w.forceRefresh = true w.forceRefresh = true
return err return err
} else { }
w.lastError = -1 w.lastError = -1
w.forceRefresh = false w.forceRefresh = false
} }
} }
}
return nil return nil
} }
// Build a queue for refresh notifications // Build a queue for refresh notifications
// this will not return until one of the queue completes // this will not return until one of the queue completes.
func (w *Watcher) notifyInProcess(listener Listener) (err *utils.SourceError) { func (w *Watcher) notifyInProcess(listener Listener) (err *utils.SourceError) {
shouldReturn := false shouldReturn := false
// This code block ensures that either a timer is created // This code block ensures that either a timer is created
@@ -292,4 +289,3 @@ func (w *Watcher) rebuildRequired(ev fsnotify.Event, listener Listener) bool {
} }
return true return true
} }