mirror of
https://github.com/kevin-DL/revel-cmd.git
synced 2026-01-11 18:54:31 +00:00
Updated formating
Ran through testing individually for vendored Revel applications
This commit is contained in:
@@ -1,13 +1,13 @@
|
|||||||
{
|
{
|
||||||
"GOLANG": {
|
"GOLANG": {
|
||||||
"ABC":[25, 35, 50, 70],
|
"ABC":[33, 38, 50, 70],
|
||||||
"ARITY":[5,6,7,8],
|
"ARITY":[5,6,7,8],
|
||||||
"BLOCK_NESTING":[7, 9, 11, 13],
|
"BLOCK_NESTING":[9, 10, 12, 13],
|
||||||
"CYCLO":[20, 30, 45, 60],
|
"CYCLO":[30, 35, 45, 60],
|
||||||
"TOO_MANY_IVARS": [20, 25, 40, 45],
|
"TOO_MANY_IVARS": [20, 25, 40, 45],
|
||||||
"TOO_MANY_FUNCTIONS": [20, 30, 40, 50],
|
"TOO_MANY_FUNCTIONS": [20, 30, 40, 50],
|
||||||
"TOTAL_COMPLEXITY": [150, 250, 400, 500],
|
"TOTAL_COMPLEXITY": [150, 250, 400, 500],
|
||||||
"LOC": [100, 175, 250, 320],
|
"LOC": [100, 175, 250, 320],
|
||||||
"TOTAL_LOC": [300, 400, 500, 600]
|
"TOTAL_LOC": [300, 400, 500, 600]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,11 +21,11 @@ import (
|
|||||||
// 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)
|
||||||
// Its only purpose is constructing the command to execute.
|
// Its only purpose is constructing the command to execute.
|
||||||
type App struct {
|
type App struct {
|
||||||
BinaryPath string // Path to the app executable
|
BinaryPath string // Path to the app executable
|
||||||
Port int // Port to pass as a command line argument.
|
Port int // Port to pass as a command line argument.
|
||||||
cmd AppCmd // The last cmd returned.
|
cmd AppCmd // The last cmd returned.
|
||||||
PackagePathMap map[string]string // Package to directory path map
|
PackagePathMap map[string]string // Package to directory path map
|
||||||
Paths *model.RevelContainer
|
Paths *model.RevelContainer
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewApp returns app instance with binary path in it
|
// NewApp returns app instance with binary path in it
|
||||||
@@ -65,7 +65,7 @@ func (cmd AppCmd) Start(c *model.CommandConfig) error {
|
|||||||
listeningWriter := &startupListeningWriter{os.Stdout, make(chan bool), c, &bytes.Buffer{}}
|
listeningWriter := &startupListeningWriter{os.Stdout, make(chan bool), c, &bytes.Buffer{}}
|
||||||
cmd.Stdout = listeningWriter
|
cmd.Stdout = listeningWriter
|
||||||
utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args, "dir", cmd.Dir, "env", cmd.Env)
|
utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args, "dir", cmd.Dir, "env", cmd.Env)
|
||||||
utils.CmdInit(cmd.Cmd, c.AppPath)
|
utils.CmdInit(cmd.Cmd, !c.Vendored, c.AppPath)
|
||||||
if err := cmd.Cmd.Start(); err != nil {
|
if err := cmd.Cmd.Start(); err != nil {
|
||||||
utils.Logger.Fatal("Error running:", "error", err)
|
utils.Logger.Fatal("Error running:", "error", err)
|
||||||
}
|
}
|
||||||
@@ -73,9 +73,9 @@ func (cmd AppCmd) Start(c *model.CommandConfig) error {
|
|||||||
select {
|
select {
|
||||||
case exitState := <-cmd.waitChan():
|
case exitState := <-cmd.waitChan():
|
||||||
fmt.Println("Startup failure view previous messages, \n Proxy is listening :", c.Run.Port)
|
fmt.Println("Startup failure view previous messages, \n Proxy is listening :", c.Run.Port)
|
||||||
err := utils.NewError("","Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState,"")
|
err := utils.NewError("", "Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState, "")
|
||||||
// TODO pretiffy command line output
|
// TODO pretiffy command line output
|
||||||
// err.MetaError = listeningWriter.getLastOutput()
|
// err.MetaError = listeningWriter.getLastOutput()
|
||||||
return err
|
return err
|
||||||
|
|
||||||
case <-time.After(60 * time.Second):
|
case <-time.After(60 * time.Second):
|
||||||
@@ -150,7 +150,7 @@ func (cmd AppCmd) Kill() {
|
|||||||
case <-ch:
|
case <-ch:
|
||||||
return
|
return
|
||||||
case <-time.After(60 * time.Second):
|
case <-time.After(60 * time.Second):
|
||||||
// Kill the process
|
// Kill the process
|
||||||
utils.Logger.Error(
|
utils.Logger.Error(
|
||||||
"Revel app failed to exit in 60 seconds - killing.",
|
"Revel app failed to exit in 60 seconds - killing.",
|
||||||
"processid", cmd.Process.Pid,
|
"processid", cmd.Process.Pid,
|
||||||
@@ -199,7 +199,7 @@ func (w *startupListeningWriter) Write(p []byte) (int, error) {
|
|||||||
w.notifyReady = nil
|
w.notifyReady = nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if w.notifyReady!=nil {
|
if w.notifyReady != nil {
|
||||||
w.buffer.Write(p)
|
w.buffer.Write(p)
|
||||||
}
|
}
|
||||||
return w.dest.Write(p)
|
return w.dest.Write(p)
|
||||||
|
|||||||
@@ -29,9 +29,15 @@ var importErrorPattern = regexp.MustCompile("cannot find package \"([^\"]+)\"")
|
|||||||
|
|
||||||
type ByString []*model.TypeInfo
|
type ByString []*model.TypeInfo
|
||||||
|
|
||||||
func (c ByString) Len() int { return len(c) }
|
func (c ByString) Len() int {
|
||||||
func (c ByString) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
|
return len(c)
|
||||||
func (c ByString) Less(i, j int) bool { return c[i].String() < c[j].String() }
|
}
|
||||||
|
func (c ByString) Swap(i, j int) {
|
||||||
|
c[i], c[j] = c[j], c[i]
|
||||||
|
}
|
||||||
|
func (c ByString) Less(i, j int) bool {
|
||||||
|
return c[i].String() < c[j].String()
|
||||||
|
}
|
||||||
|
|
||||||
// Build the app:
|
// Build the app:
|
||||||
// 1. Generate the the main.go file.
|
// 1. Generate the the main.go file.
|
||||||
@@ -116,8 +122,8 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Binary path is a combination of BasePath/target directory, app's import path and its name.
|
// Binary path is a combination of BasePath/target/app directory, app's import path and its name.
|
||||||
binName := filepath.Join(paths.BasePath, "target", paths.ImportPath, filepath.Base(paths.BasePath))
|
binName := filepath.Join(paths.BasePath, "target", "app", paths.ImportPath, filepath.Base(paths.BasePath))
|
||||||
|
|
||||||
// Change binary path for Windows build
|
// Change binary path for Windows build
|
||||||
goos := runtime.GOOS
|
goos := runtime.GOOS
|
||||||
@@ -139,14 +145,10 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
|
|||||||
}
|
}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
|
|
||||||
appVersion := getAppVersion(paths)
|
appVersion := getAppVersion(paths)
|
||||||
if appVersion == "" {
|
|
||||||
appVersion = "noVersionProvided"
|
|
||||||
}
|
|
||||||
|
|
||||||
buildTime := time.Now().UTC().Format(time.RFC3339)
|
buildTime := time.Now().UTC().Format(time.RFC3339)
|
||||||
versionLinkerFlags := fmt.Sprintf("-X '%s/app.AppVersion=%s' -X '%s/app.BuildTime=%s'",
|
versionLinkerFlags := fmt.Sprintf("-X %s/app.AppVersion=%s -X %s/app.BuildTime=%s",
|
||||||
paths.ImportPath, appVersion, paths.ImportPath, buildTime)
|
paths.ImportPath, appVersion, paths.ImportPath, buildTime)
|
||||||
|
|
||||||
// Append any build flags specified, they will override existing flags
|
// Append any build flags specified, they will override existing flags
|
||||||
@@ -161,13 +163,9 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
|
|||||||
if !contains(c.BuildFlags, "build") {
|
if !contains(c.BuildFlags, "build") {
|
||||||
flags = []string{"build"}
|
flags = []string{"build"}
|
||||||
}
|
}
|
||||||
|
flags = append(flags, c.BuildFlags...)
|
||||||
if !contains(flags, "-ldflags") {
|
if !contains(flags, "-ldflags") {
|
||||||
ldflags := "-ldflags= " + versionLinkerFlags
|
flags = append(flags, "-ldflags", versionLinkerFlags)
|
||||||
// Add in build flags
|
|
||||||
for i := range c.BuildFlags {
|
|
||||||
ldflags += "-X '" + c.BuildFlags[i] + "'"
|
|
||||||
}
|
|
||||||
flags = append(flags, ldflags)
|
|
||||||
}
|
}
|
||||||
if !contains(flags, "-tags") {
|
if !contains(flags, "-tags") {
|
||||||
flags = append(flags, "-tags", buildTags)
|
flags = append(flags, "-tags", buildTags)
|
||||||
@@ -177,31 +175,38 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// This is Go main path
|
// Add in build flags
|
||||||
gopath := c.GoPath
|
flags = append(flags, c.BuildFlags...)
|
||||||
for _, o := range paths.ModulePathMap {
|
|
||||||
gopath += string(filepath.ListSeparator) + o.Path
|
|
||||||
}
|
|
||||||
|
|
||||||
// Note: It's not applicable for filepath.* usage
|
// Note: It's not applicable for filepath.* usage
|
||||||
flags = append(flags, path.Join(paths.ImportPath, "app", "tmp"))
|
flags = append(flags, path.Join(paths.ImportPath, "app", "tmp"))
|
||||||
|
|
||||||
buildCmd := exec.Command(goPath, flags...)
|
buildCmd := exec.Command(goPath, flags...)
|
||||||
buildCmd.Env = append(os.Environ(),
|
if !c.Vendored {
|
||||||
"GOPATH="+gopath,
|
// This is Go main path
|
||||||
)
|
gopath := c.GoPath
|
||||||
utils.CmdInit(buildCmd, c.AppPath)
|
for _, o := range paths.ModulePathMap {
|
||||||
utils.Logger.Info("Exec:", "args", buildCmd.Args,"working dir", buildCmd.Dir)
|
gopath += string(filepath.ListSeparator) + o.Path
|
||||||
|
}
|
||||||
|
|
||||||
|
buildCmd.Env = append(os.Environ(),
|
||||||
|
"GOPATH=" + gopath,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
utils.CmdInit(buildCmd, !c.Vendored, c.AppPath)
|
||||||
|
|
||||||
|
utils.Logger.Info("Exec:", "args", buildCmd.Args, "working dir", buildCmd.Dir)
|
||||||
output, err := buildCmd.CombinedOutput()
|
output, err := buildCmd.CombinedOutput()
|
||||||
|
|
||||||
// If the build succeeded, we're done.
|
// If the build succeeded, we're done.
|
||||||
if err == nil {
|
if err == nil {
|
||||||
utils.Logger.Info("Build successful continuing")
|
utils.Logger.Info("Build successful continuing")
|
||||||
return NewApp(binName, paths,sourceInfo.PackageMap), nil
|
return NewApp(binName, paths, sourceInfo.PackageMap), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Since there was an error, capture the output in case we need to report it
|
// Since there was an error, capture the output in case we need to report it
|
||||||
stOutput := string(output)
|
stOutput := string(output)
|
||||||
|
utils.Logger.Infof("Got error on build of app %s", stOutput)
|
||||||
|
|
||||||
// See if it was an import error that we can go get.
|
// See if it was an import error that we can go get.
|
||||||
matches := importErrorPattern.FindAllStringSubmatch(stOutput, -1)
|
matches := importErrorPattern.FindAllStringSubmatch(stOutput, -1)
|
||||||
@@ -253,7 +258,7 @@ func getAppVersion(paths *model.RevelContainer) string {
|
|||||||
if (err != nil && os.IsNotExist(err)) || !info.IsDir() {
|
if (err != nil && os.IsNotExist(err)) || !info.IsDir() {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
gitCmd := exec.Command(gitPath, "--git-dir="+gitDir, "--work-tree="+paths.BasePath, "describe", "--always", "--dirty")
|
gitCmd := exec.Command(gitPath, "--git-dir=" + gitDir, "--work-tree=" + paths.BasePath, "describe", "--always", "--dirty")
|
||||||
utils.Logger.Info("Exec:", "args", gitCmd.Args)
|
utils.Logger.Info("Exec:", "args", gitCmd.Args)
|
||||||
output, err := gitCmd.Output()
|
output, err := gitCmd.Output()
|
||||||
|
|
||||||
@@ -418,12 +423,13 @@ 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"
|
||||||
absFilename = findInPaths(relFilename)
|
absFilename = findInPaths(relFilename)
|
||||||
line, _ = strconv.Atoi(string(errorMatch[2]))
|
line, _ = strconv.Atoi(string(errorMatch[2]))
|
||||||
description = string(errorMatch[4])
|
description = string(errorMatch[4])
|
||||||
compileError = &utils.SourceError{
|
compileError = &utils.SourceError{
|
||||||
SourceType: "Go code",
|
SourceType: "Go code",
|
||||||
Title: "Go Compilation Error",
|
Title: "Go Compilation Error",
|
||||||
@@ -442,7 +448,7 @@ func newCompileError(paths *model.RevelContainer, output []byte) *utils.SourceEr
|
|||||||
fileStr, err := utils.ReadLines(absFilename)
|
fileStr, err := utils.ReadLines(absFilename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
compileError.MetaError = absFilename + ": " + err.Error()
|
compileError.MetaError = absFilename + ": " + err.Error()
|
||||||
utils.Logger.Info("Unable to readlines "+compileError.MetaError, "error", err)
|
utils.Logger.Info("Unable to readlines " + compileError.MetaError, "error", err)
|
||||||
return compileError
|
return compileError
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -99,7 +99,7 @@ func (c callHandler) Log(log *log15.Record) error {
|
|||||||
ctx := log.Ctx
|
ctx := log.Ctx
|
||||||
var ctxMap ContextMap
|
var ctxMap ContextMap
|
||||||
if len(ctx) > 0 {
|
if len(ctx) > 0 {
|
||||||
ctxMap = make(ContextMap, len(ctx)/2)
|
ctxMap = make(ContextMap, len(ctx) / 2)
|
||||||
|
|
||||||
for i := 0; i < len(ctx); i += 2 {
|
for i := 0; i < len(ctx); i += 2 {
|
||||||
v := ctx[i]
|
v := ctx[i]
|
||||||
@@ -108,8 +108,8 @@ func (c callHandler) Log(log *log15.Record) error {
|
|||||||
key = fmt.Sprintf("LOGGER_INVALID_KEY %v", v)
|
key = fmt.Sprintf("LOGGER_INVALID_KEY %v", v)
|
||||||
}
|
}
|
||||||
var value interface{}
|
var value interface{}
|
||||||
if len(ctx) > i+1 {
|
if len(ctx) > i + 1 {
|
||||||
value = ctx[i+1]
|
value = ctx[i + 1]
|
||||||
} else {
|
} else {
|
||||||
value = "LOGGER_VALUE_MISSING"
|
value = "LOGGER_VALUE_MISSING"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
package command
|
package command
|
||||||
|
|
||||||
|
|
||||||
type (
|
type (
|
||||||
New struct {
|
New struct {
|
||||||
ImportCommand
|
ImportCommand
|
||||||
@@ -6,6 +8,7 @@ type (
|
|||||||
Package string `short:"p" long:"package" description:"The package name, this becomes the repfix to the app name, if defined vendored is set to true" required:"false"`
|
Package string `short:"p" long:"package" description:"The package name, this becomes the repfix to the app name, if defined vendored is set to true" required:"false"`
|
||||||
NotVendored bool `short:"V" long:"vendor" description:"True if project should not be configured with a go.mod"`
|
NotVendored bool `short:"V" long:"vendor" description:"True if project should not be configured with a go.mod"`
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
)
|
)
|
||||||
@@ -177,7 +177,7 @@ func (c *CommandConfig) initAppFolder() (err error) {
|
|||||||
appFolder = filepath.Join(wd,appFolder)
|
appFolder = filepath.Join(wd,appFolder)
|
||||||
}
|
}
|
||||||
|
|
||||||
utils.Logger.Info("Determined app folder to be", "folder",appFolder, "working",wd)
|
utils.Logger.Info("Determined app folder to be", "appfolder",appFolder, "working",wd,"importPath",c.ImportPath)
|
||||||
|
|
||||||
// Use app folder to read the go.mod if it exists and extract the package information
|
// Use app folder to read the go.mod if it exists and extract the package information
|
||||||
goModFile := filepath.Join(appFolder,"go.mod")
|
goModFile := filepath.Join(appFolder,"go.mod")
|
||||||
@@ -214,24 +214,29 @@ func (c *CommandConfig) initAppFolder() (err error) {
|
|||||||
workingDir, _ := os.Getwd()
|
workingDir, _ := os.Getwd()
|
||||||
goPathList := filepath.SplitList(c.GoPath)
|
goPathList := filepath.SplitList(c.GoPath)
|
||||||
bestpath := ""
|
bestpath := ""
|
||||||
for _, path := range goPathList {
|
if !c.Vendored {
|
||||||
if c.Index == NEW {
|
for _, path := range goPathList {
|
||||||
// If the GOPATH is part of the working dir this is the most likely target
|
if c.Index == NEW {
|
||||||
if strings.HasPrefix(workingDir, path) {
|
// If the GOPATH is part of the working dir this is the most likely target
|
||||||
bestpath = path
|
if strings.HasPrefix(workingDir, path) {
|
||||||
}
|
bestpath = path
|
||||||
} else {
|
}
|
||||||
if utils.Exists(filepath.Join(path, "src", c.ImportPath)) {
|
} else {
|
||||||
c.SrcRoot = path
|
if utils.Exists(filepath.Join(path, "src", c.ImportPath)) {
|
||||||
break
|
c.SrcRoot = path
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if len(c.SrcRoot) == 0 && len(bestpath) > 0 {
|
||||||
|
c.SrcRoot = bestpath
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
c.SrcRoot = appFolder
|
||||||
}
|
}
|
||||||
|
|
||||||
utils.Logger.Info("Source root", "path", c.SrcRoot, "cwd", workingDir, "gopath", c.GoPath, "bestpath",bestpath)
|
utils.Logger.Info("Source root", "path", c.SrcRoot, "cwd", workingDir, "gopath", c.GoPath, "bestpath",bestpath)
|
||||||
if len(c.SrcRoot) == 0 && len(bestpath) > 0 {
|
|
||||||
c.SrcRoot = bestpath
|
|
||||||
}
|
|
||||||
|
|
||||||
// If source root is empty and this isn't a version then skip it
|
// If source root is empty and this isn't a version then skip it
|
||||||
if len(c.SrcRoot) == 0 {
|
if len(c.SrcRoot) == 0 {
|
||||||
@@ -270,32 +275,11 @@ func (c *CommandConfig) InitPackageResolver() {
|
|||||||
utils.Logger.Info("Request for package ", "package", pkgName, "use vendor", c.Vendored)
|
utils.Logger.Info("Request for package ", "package", pkgName, "use vendor", c.Vendored)
|
||||||
if c.Vendored {
|
if c.Vendored {
|
||||||
goModCmd := exec.Command("go", "mod", "tidy")
|
goModCmd := exec.Command("go", "mod", "tidy")
|
||||||
utils.CmdInit(goModCmd, c.AppPath)
|
utils.CmdInit(goModCmd,!c.Vendored, c.AppPath)
|
||||||
|
goModCmd.Run()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
//utils.Logger.Info("Using dependency manager to import package", "package", pkgName)
|
|
||||||
//
|
|
||||||
//// Check to see if the package exists locally
|
|
||||||
//_, err := build.Import(pkgName, c.AppPath, build.FindOnly)
|
|
||||||
//if err != nil {
|
|
||||||
// getCmd = exec.Command(depPath, "ensure", "-add", pkgName)
|
|
||||||
//} else {
|
|
||||||
// getCmd = exec.Command(depPath, "ensure", "-update", pkgName)
|
|
||||||
//}
|
|
||||||
//
|
|
||||||
//
|
|
||||||
//} else {
|
|
||||||
// utils.Logger.Info("No vendor folder detected, not using dependency manager to import package", "package", pkgName)
|
|
||||||
// getCmd = exec.Command(c.GoCmd, "get", "-u", pkgName)
|
|
||||||
//}
|
|
||||||
//
|
|
||||||
//utils.CmdInit(getCmd, c.AppPath)
|
|
||||||
//utils.Logger.Info("Go get command ", "exec", getCmd.Path, "dir", getCmd.Dir, "args", getCmd.Args, "env", getCmd.Env, "package", pkgName)
|
|
||||||
//output, err := getCmd.CombinedOutput()
|
|
||||||
//if err != nil {
|
|
||||||
// fmt.Printf("Error stack %v\n", logger.NewCallStack())
|
|
||||||
// utils.Logger.Error("Failed to import package", "error", err, "gopath", build.Default.GOPATH, "GO-ROOT", build.Default.GOROOT, "output", string(output))
|
|
||||||
//}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,14 +12,14 @@ import (
|
|||||||
type SourceInfo struct {
|
type SourceInfo struct {
|
||||||
// StructSpecs lists type info for all structs found under the code paths.
|
// StructSpecs lists type info for all structs found under the code paths.
|
||||||
// They may be queried to determine which ones (transitively) embed certain types.
|
// They may be queried to determine which ones (transitively) embed certain types.
|
||||||
StructSpecs []*TypeInfo
|
StructSpecs []*TypeInfo
|
||||||
// ValidationKeys provides a two-level lookup. The keys are:
|
// ValidationKeys provides a two-level lookup. The keys are:
|
||||||
// 1. The fully-qualified function name,
|
// 1. The fully-qualified function name,
|
||||||
// e.g. "github.com/revel/examples/chat/app/controllers.(*Application).Action"
|
// e.g. "github.com/revel/examples/chat/app/controllers.(*Application).Action"
|
||||||
// 2. Within that func's file, the line number of the (overall) expression statement.
|
// 2. Within that func's file, the line number of the (overall) expression statement.
|
||||||
// e.g. the line returned from runtime.Caller()
|
// e.g. the line returned from runtime.Caller()
|
||||||
// The result of the lookup the name of variable being validated.
|
// The result of the lookup the name of variable being validated.
|
||||||
ValidationKeys map[string]map[int]string
|
ValidationKeys map[string]map[int]string
|
||||||
// A list of import paths.
|
// A list of import paths.
|
||||||
// Revel notices files with an init() function and imports that package.
|
// Revel notices files with an init() function and imports that package.
|
||||||
InitImportPaths []string
|
InitImportPaths []string
|
||||||
@@ -28,9 +28,9 @@ type SourceInfo struct {
|
|||||||
// app/controllers/... that embed (directly or indirectly) revel.Controller
|
// app/controllers/... that embed (directly or indirectly) revel.Controller
|
||||||
controllerSpecs []*TypeInfo
|
controllerSpecs []*TypeInfo
|
||||||
// testSuites list the types that constitute the set of application tests.
|
// testSuites list the types that constitute the set of application tests.
|
||||||
testSuites []*TypeInfo
|
testSuites []*TypeInfo
|
||||||
// packageMap a map of import to system directory (if available)
|
// packageMap a map of import to system directory (if available)
|
||||||
PackageMap map[string]string
|
PackageMap map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
// TypesThatEmbed returns all types that (directly or indirectly) embed the
|
// TypesThatEmbed returns all types that (directly or indirectly) embed the
|
||||||
@@ -76,7 +76,7 @@ func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered
|
|||||||
utils.Logger.Info("Debug: Skipping adding spec for unexported type",
|
utils.Logger.Info("Debug: Skipping adding spec for unexported type",
|
||||||
"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:]...)
|
||||||
exit = false
|
exit = false
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -99,8 +99,8 @@ func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered
|
|||||||
|
|
||||||
// Report non controller structures in controller folder.
|
// Report non controller structures in controller folder.
|
||||||
if !found && !strings.HasPrefix(spec.StructName, "Test") {
|
if !found && !strings.HasPrefix(spec.StructName, "Test") {
|
||||||
utils.Logger.Warn("Type found in package: "+packageFilter+
|
utils.Logger.Warn("Type found in package: " + packageFilter +
|
||||||
", but did not embed from: "+filepath.Base(targetType),
|
", but did not embed from: " + filepath.Base(targetType),
|
||||||
"name", spec.StructName, "importpath", spec.ImportPath, "foundstructures", unfoundNames)
|
"name", spec.StructName, "importpath", spec.ImportPath, "foundstructures", unfoundNames)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -112,7 +112,7 @@ func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered
|
|||||||
// `revel.Controller`
|
// `revel.Controller`
|
||||||
func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
|
func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
|
||||||
if s.controllerSpecs == nil {
|
if s.controllerSpecs == nil {
|
||||||
s.controllerSpecs = s.TypesThatEmbed(RevelImportPath+".Controller", "controllers")
|
s.controllerSpecs = s.TypesThatEmbed(RevelImportPath + ".Controller", "controllers")
|
||||||
}
|
}
|
||||||
return s.controllerSpecs
|
return s.controllerSpecs
|
||||||
}
|
}
|
||||||
@@ -121,7 +121,7 @@ func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
|
|||||||
// `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")
|
||||||
}
|
}
|
||||||
return s.testSuites
|
return s.testSuites
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,20 +8,20 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Version struct {
|
type Version struct {
|
||||||
Prefix string
|
Prefix string
|
||||||
Major int
|
Major int
|
||||||
Minor int
|
Minor int
|
||||||
Maintenance int
|
Maintenance int
|
||||||
Suffix string
|
Suffix string
|
||||||
BuildDate string
|
BuildDate string
|
||||||
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.1.0"}, // Compatible with Framework V 1.0 - 1.1
|
{"1.0.0", "1.1.0"}, // Compatible with Framework V 1.0 - 1.1
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parses a version like v1.2.3a or 1.2
|
// Parses a version like v1.2.3a or 1.2
|
||||||
|
|||||||
@@ -15,23 +15,23 @@ type (
|
|||||||
sourceProcessor *SourceProcessor
|
sourceProcessor *SourceProcessor
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewSourceInfoProcessor(sourceProcessor *SourceProcessor) *SourceInfoProcessor {
|
func NewSourceInfoProcessor(sourceProcessor *SourceProcessor) *SourceInfoProcessor {
|
||||||
return &SourceInfoProcessor{sourceProcessor:sourceProcessor}
|
return &SourceInfoProcessor{sourceProcessor:sourceProcessor}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func (s *SourceInfoProcessor) processPackage(p *packages.Package) (sourceInfo *model.SourceInfo) {
|
func (s *SourceInfoProcessor) processPackage(p *packages.Package) (sourceInfo *model.SourceInfo) {
|
||||||
sourceInfo = &model.SourceInfo{
|
sourceInfo = &model.SourceInfo{
|
||||||
ValidationKeys: map[string]map[int]string{},
|
ValidationKeys: map[string]map[int]string{},
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
isController = strings.HasSuffix(p.PkgPath, "/controllers") ||
|
isController = strings.HasSuffix(p.PkgPath, "/controllers") ||
|
||||||
strings.Contains(p.PkgPath, "/controllers/")
|
strings.Contains(p.PkgPath, "/controllers/")
|
||||||
isTest = strings.HasSuffix(p.PkgPath, "/tests") ||
|
isTest = strings.HasSuffix(p.PkgPath, "/tests") ||
|
||||||
strings.Contains(p.PkgPath, "/tests/")
|
strings.Contains(p.PkgPath, "/tests/")
|
||||||
methodMap = map[string][]*model.MethodSpec{}
|
methodMap = map[string][]*model.MethodSpec{}
|
||||||
)
|
)
|
||||||
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)
|
||||||
//println("*** checking", p.Fset.Position(decl.Pos()).Filename)
|
//println("*** checking", p.Fset.Position(decl.Pos()).Filename)
|
||||||
@@ -50,20 +50,21 @@ func (s *SourceInfoProcessor) processPackage(p *packages.Package) (sourceInfo *m
|
|||||||
}
|
}
|
||||||
// This could be a controller action endpoint, check and add if needed
|
// This could be a controller action endpoint, check and add if needed
|
||||||
if isController &&
|
if isController &&
|
||||||
funcDecl.Recv!=nil && // Must have a receiver
|
funcDecl.Recv != nil && // Must have a receiver
|
||||||
funcDecl.Name.IsExported() && // be public
|
funcDecl.Name.IsExported() && // be public
|
||||||
funcDecl.Type.Results != nil && len(funcDecl.Type.Results.List) == 1 { // return one result
|
funcDecl.Type.Results != nil && len(funcDecl.Type.Results.List) == 1 {
|
||||||
if m, receiver:=s.getControllerFunc(funcDecl,p);m!=nil {
|
// return one result
|
||||||
methodMap[receiver]=append(methodMap[receiver],m)
|
if m, receiver := s.getControllerFunc(funcDecl, p); m != nil {
|
||||||
s.sourceProcessor.log.Info("Added method map to ","receiver",receiver,"method",m.Name)
|
methodMap[receiver] = append(methodMap[receiver], m)
|
||||||
|
s.sourceProcessor.log.Info("Added method map to ", "receiver", receiver, "method", m.Name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Check for validation
|
// Check for validation
|
||||||
if lineKeyMap := s.getValidation(funcDecl,p);len(lineKeyMap)>1 {
|
if lineKeyMap := s.getValidation(funcDecl, p); len(lineKeyMap) > 1 {
|
||||||
sourceInfo.ValidationKeys[p.PkgPath+"."+s.getFuncName(funcDecl)] = lineKeyMap
|
sourceInfo.ValidationKeys[p.PkgPath + "." + s.getFuncName(funcDecl)] = lineKeyMap
|
||||||
}
|
}
|
||||||
if funcDecl.Name.Name == "init" {
|
if funcDecl.Name.Name == "init" {
|
||||||
sourceInfo.InitImportPaths = append(sourceInfo.InitImportPaths,p.PkgPath)
|
sourceInfo.InitImportPaths = append(sourceInfo.InitImportPaths, p.PkgPath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,7 +91,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)
|
||||||
|
|
||||||
@@ -182,7 +183,7 @@ func (s *SourceInfoProcessor) getValidationParameter(funcDecl *ast.FuncDecl) *a
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
func (s *SourceInfoProcessor) getControllerFunc(funcDecl *ast.FuncDecl,p *packages.Package) (method *model.MethodSpec, recvTypeName string) {
|
func (s *SourceInfoProcessor) getControllerFunc(funcDecl *ast.FuncDecl, p *packages.Package) (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 {
|
||||||
return
|
return
|
||||||
@@ -270,7 +271,7 @@ func (s *SourceInfoProcessor) getControllerFunc(funcDecl *ast.FuncDecl,p *packag
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
func (s *SourceInfoProcessor) getControllerSpec(spec *ast.TypeSpec,p *packages.Package) (controllerSpec *model.TypeInfo) {
|
func (s *SourceInfoProcessor) getControllerSpec(spec *ast.TypeSpec, p *packages.Package) (controllerSpec *model.TypeInfo) {
|
||||||
structType := spec.Type.(*ast.StructType)
|
structType := spec.Type.(*ast.StructType)
|
||||||
|
|
||||||
// At this point we know it's a type declaration for a struct.
|
// At this point we know it's a type declaration for a struct.
|
||||||
@@ -329,7 +330,7 @@ func (s *SourceInfoProcessor) getControllerSpec(spec *ast.TypeSpec,p *packages.P
|
|||||||
} else {
|
} else {
|
||||||
var ok bool
|
var ok bool
|
||||||
if importPath, ok = s.sourceProcessor.importMap[pkgName]; !ok {
|
if importPath, ok = s.sourceProcessor.importMap[pkgName]; !ok {
|
||||||
s.sourceProcessor.log.Error("Error: Failed to find import path for ", "package", pkgName, "type", typeName, "map",s.sourceProcessor.importMap)
|
s.sourceProcessor.log.Error("Error: Failed to find import path for ", "package", pkgName, "type", typeName, "map", s.sourceProcessor.importMap)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -339,7 +340,7 @@ func (s *SourceInfoProcessor) getControllerSpec(spec *ast.TypeSpec,p *packages.P
|
|||||||
StructName: typeName,
|
StructName: typeName,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
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) {
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ type (
|
|||||||
log logger.MultiLogger
|
log logger.MultiLogger
|
||||||
packageList []*packages.Package
|
packageList []*packages.Package
|
||||||
importMap map[string]string
|
importMap map[string]string
|
||||||
packageMap map[string]string
|
packageMap map[string]string
|
||||||
sourceInfoProcessor *SourceInfoProcessor
|
sourceInfoProcessor *SourceInfoProcessor
|
||||||
sourceInfo *model.SourceInfo
|
sourceInfo *model.SourceInfo
|
||||||
}
|
}
|
||||||
@@ -29,8 +29,8 @@ func ProcessSource(revelContainer *model.RevelContainer) (sourceInfo *model.Sour
|
|||||||
processor := NewSourceProcessor(revelContainer)
|
processor := NewSourceProcessor(revelContainer)
|
||||||
compileError = processor.parse()
|
compileError = processor.parse()
|
||||||
sourceInfo = processor.sourceInfo
|
sourceInfo = processor.sourceInfo
|
||||||
if compileError==nil {
|
if compileError == nil {
|
||||||
processor.log.Infof("From parsers : Structures:%d InitImports:%d ValidationKeys:%d %v", len(sourceInfo.StructSpecs), len(sourceInfo.InitImportPaths), len(sourceInfo.ValidationKeys),sourceInfo.PackageMap)
|
processor.log.Infof("From parsers : Structures:%d InitImports:%d ValidationKeys:%d %v", len(sourceInfo.StructSpecs), len(sourceInfo.InitImportPaths), len(sourceInfo.ValidationKeys), sourceInfo.PackageMap)
|
||||||
}
|
}
|
||||||
|
|
||||||
if false {
|
if false {
|
||||||
@@ -58,7 +58,7 @@ func (s *SourceProcessor) parse() (compileError error) {
|
|||||||
s.sourceInfo.PackageMap = map[string]string{}
|
s.sourceInfo.PackageMap = map[string]string{}
|
||||||
getImportFromMap := func(packagePath string) string {
|
getImportFromMap := func(packagePath string) string {
|
||||||
for path := range s.packageMap {
|
for path := range s.packageMap {
|
||||||
if strings.Index(path,packagePath)==0 {
|
if strings.Index(path, packagePath) == 0 {
|
||||||
fullPath := s.packageMap[path]
|
fullPath := s.packageMap[path]
|
||||||
return fullPath[:(len(fullPath) - len(path) + len(packagePath))]
|
return fullPath[:(len(fullPath) - len(path) + len(packagePath))]
|
||||||
}
|
}
|
||||||
@@ -74,7 +74,7 @@ func (s *SourceProcessor) parse() (compileError error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
func (s *SourceProcessor) addPackages() (err error) {
|
func (s *SourceProcessor) addPackages() (err error) {
|
||||||
allPackages := []string{s.revelContainer.ImportPath + "/...",model.RevelImportPath}
|
allPackages := []string{s.revelContainer.ImportPath + "/...", model.RevelImportPath}
|
||||||
for _, module := range s.revelContainer.ModulePathMap {
|
for _, module := range s.revelContainer.ModulePathMap {
|
||||||
allPackages = append(allPackages, module.ImportPath + "/...") // +"/app/controllers/...")
|
allPackages = append(allPackages, module.ImportPath + "/...") // +"/app/controllers/...")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,10 +37,10 @@ func init() {
|
|||||||
// 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 == "" {
|
||||||
c.Build.TargetPath="target"
|
c.Build.TargetPath = "target"
|
||||||
}
|
}
|
||||||
if len(args)==0 && c.Build.ImportPath!="" {
|
if len(args) == 0 && c.Build.ImportPath != "" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
// If arguments were passed in then there must be two
|
// If arguments were passed in then there must be two
|
||||||
@@ -176,13 +176,13 @@ func buildCopyModules(c *model.CommandConfig, revel_paths *model.RevelContainer,
|
|||||||
if moduleImportPath == "" {
|
if moduleImportPath == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
moduleImportList =append(moduleImportList,moduleImportPath)
|
moduleImportList = append(moduleImportList, moduleImportPath)
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy the the paths for each of the modules
|
// Copy the the paths for each of the modules
|
||||||
for _,importPath := range moduleImportList {
|
for _, importPath := range moduleImportList {
|
||||||
fsPath := app.PackagePathMap[importPath]
|
fsPath := app.PackagePathMap[importPath]
|
||||||
utils.Logger.Info("Copy files ", "to", filepath.Join(destPath, importPath), "from", fsPath)
|
utils.Logger.Info("Copy files ", "to", filepath.Join(destPath, importPath), "from", fsPath)
|
||||||
if c.Build.CopySource {
|
if c.Build.CopySource {
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ func init() {
|
|||||||
// 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 != "" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
|
|||||||
48
revel/new.go
48
revel/new.go
@@ -46,13 +46,13 @@ func init() {
|
|||||||
// 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 {
|
||||||
c.New.NotVendored = false
|
c.New.NotVendored = false
|
||||||
}
|
}
|
||||||
c.Vendored = !c.New.NotVendored
|
c.Vendored = !c.New.NotVendored
|
||||||
|
|
||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
if len(c.New.ImportPath)==0 {
|
if len(c.New.ImportPath) == 0 {
|
||||||
fmt.Fprintf(os.Stderr, cmdNew.Long)
|
fmt.Fprintf(os.Stderr, cmdNew.Long)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -76,7 +76,7 @@ func newApp(c *model.CommandConfig) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// checking and setting skeleton
|
// checking and setting skeleton
|
||||||
if err=setSkeletonPath(c);err!=nil {
|
if err = setSkeletonPath(c); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,18 +90,20 @@ func newApp(c *model.CommandConfig) (err error) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// At this point the versions can be set
|
// This kicked off the download of the revel app, not needed for vendor
|
||||||
c.SetVersions()
|
if !c.Vendored {
|
||||||
|
// At this point the versions can be set
|
||||||
|
c.SetVersions()
|
||||||
|
}
|
||||||
|
|
||||||
// copy files to new app directory
|
// copy files to new app directory
|
||||||
if err = copyNewAppFiles(c);err != nil {
|
if err = copyNewAppFiles(c); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run the vendor tool if needed
|
// Run the vendor tool if needed
|
||||||
println("********** here",c.Vendored)
|
|
||||||
if c.Vendored {
|
if c.Vendored {
|
||||||
if err=createModVendor(c); err!=nil {
|
if err = createModVendor(c); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -120,13 +122,15 @@ 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))
|
||||||
|
|
||||||
|
utils.CmdInit(goModCmd, !c.Vendored, c.AppPath)
|
||||||
|
|
||||||
utils.CmdInit(goModCmd, c.AppPath)
|
utils.Logger.Info("Exec:", "args", goModCmd.Args, "env", goModCmd.Env, "workingdir", goModCmd.Dir)
|
||||||
|
|
||||||
utils.Logger.Info("Exec:", "args", goModCmd.Args, "env", goModCmd.Env, "workingdir",goModCmd.Dir)
|
|
||||||
getOutput, err := goModCmd.CombinedOutput()
|
getOutput, err := goModCmd.CombinedOutput()
|
||||||
|
if c.New.Callback != nil {
|
||||||
|
err = c.New.Callback()
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.NewBuildIfError(err, string(getOutput))
|
return utils.NewBuildIfError(err, string(getOutput))
|
||||||
}
|
}
|
||||||
@@ -141,7 +145,7 @@ func createDepVendor(c *model.CommandConfig) (err error) {
|
|||||||
if !utils.DirExists(vendorPath) {
|
if !utils.DirExists(vendorPath) {
|
||||||
|
|
||||||
if err := os.MkdirAll(vendorPath, os.ModePerm); err != nil {
|
if err := os.MkdirAll(vendorPath, os.ModePerm); err != nil {
|
||||||
return utils.NewBuildError("Failed to create "+vendorPath, "error", err)
|
return utils.NewBuildError("Failed to create " + vendorPath, "error", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,11 +154,11 @@ func createDepVendor(c *model.CommandConfig) (err error) {
|
|||||||
utils.Logger.Info("Checking for temp folder for source code", "path", tempPath)
|
utils.Logger.Info("Checking for temp folder for source code", "path", tempPath)
|
||||||
if !utils.DirExists(tempPath) {
|
if !utils.DirExists(tempPath) {
|
||||||
if err := os.MkdirAll(tempPath, os.ModePerm); err != nil {
|
if err := os.MkdirAll(tempPath, os.ModePerm); err != nil {
|
||||||
return utils.NewBuildIfError(err, "Failed to create "+vendorPath)
|
return utils.NewBuildIfError(err, "Failed to create " + vendorPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = utils.GenerateTemplate(filepath.Join(tempPath, "main.go"), NEW_MAIN_FILE, nil); err != nil {
|
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)
|
return utils.NewBuildIfError(err, "Failed to create main file " + vendorPath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,9 +175,9 @@ func createDepVendor(c *model.CommandConfig) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getCmd := exec.Command("dep", "ensure", "-v")
|
getCmd := exec.Command("dep", "ensure", "-v")
|
||||||
utils.CmdInit(getCmd, c.AppPath)
|
utils.CmdInit(getCmd, !c.Vendored, c.AppPath)
|
||||||
|
|
||||||
utils.Logger.Info("Exec:", "args", getCmd.Args, "env", getCmd.Env, "workingdir",getCmd.Dir)
|
utils.Logger.Info("Exec:", "args", getCmd.Args, "env", getCmd.Env, "workingdir", getCmd.Dir)
|
||||||
getOutput, err := getCmd.CombinedOutput()
|
getOutput, err := getCmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.NewBuildIfError(err, string(getOutput))
|
return utils.NewBuildIfError(err, string(getOutput))
|
||||||
@@ -211,7 +215,7 @@ func setApplicationPath(c *model.CommandConfig) (err error) {
|
|||||||
//// 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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -235,13 +239,13 @@ func setSkeletonPath(c *model.CommandConfig) (err error) {
|
|||||||
switch strings.ToLower(sp.Scheme) {
|
switch strings.ToLower(sp.Scheme) {
|
||||||
// TODO Add support for ftp, sftp, scp ??
|
// TODO Add support for ftp, sftp, scp ??
|
||||||
case "" :
|
case "" :
|
||||||
sp.Scheme="file"
|
sp.Scheme = "file"
|
||||||
fallthrough
|
fallthrough
|
||||||
case "file" :
|
case "file" :
|
||||||
fullpath := sp.String()[7:]
|
fullpath := sp.String()[7:]
|
||||||
if !filepath.IsAbs(fullpath) {
|
if !filepath.IsAbs(fullpath) {
|
||||||
fullpath, err = filepath.Abs(fullpath)
|
fullpath, err = filepath.Abs(fullpath)
|
||||||
if err!=nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -276,11 +280,11 @@ func newLoadFromGit(c *model.CommandConfig, sp *url.URL) (err error) {
|
|||||||
targetPath := filepath.Join(os.TempDir(), "revel", "skeleton")
|
targetPath := filepath.Join(os.TempDir(), "revel", "skeleton")
|
||||||
os.RemoveAll(targetPath)
|
os.RemoveAll(targetPath)
|
||||||
pathpart := strings.Split(sp.Path, ":")
|
pathpart := strings.Split(sp.Path, ":")
|
||||||
getCmd := exec.Command("git", "clone", sp.Scheme+"://"+sp.Host+pathpart[0], targetPath)
|
getCmd := exec.Command("git", "clone", sp.Scheme + "://" + sp.Host + pathpart[0], targetPath)
|
||||||
utils.Logger.Info("Exec:", "args", getCmd.Args)
|
utils.Logger.Info("Exec:", "args", getCmd.Args)
|
||||||
getOutput, err := getCmd.CombinedOutput()
|
getOutput, err := getCmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.Logger.Fatal("Abort: could not clone the Skeleton source code: ","output", string(getOutput), "path", c.New.SkeletonPath)
|
utils.Logger.Fatal("Abort: could not clone the Skeleton source code: ", "output", string(getOutput), "path", c.New.SkeletonPath)
|
||||||
}
|
}
|
||||||
outputPath := targetPath
|
outputPath := targetPath
|
||||||
if len(pathpart) > 1 {
|
if len(pathpart) > 1 {
|
||||||
|
|||||||
@@ -3,95 +3,42 @@ package main_test
|
|||||||
import (
|
import (
|
||||||
"github.com/revel/cmd/model"
|
"github.com/revel/cmd/model"
|
||||||
"github.com/revel/cmd/revel"
|
"github.com/revel/cmd/revel"
|
||||||
"github.com/revel/cmd/utils"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 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)
|
||||||
|
|
||||||
t.Run("New", func(t *testing.T) {
|
|
||||||
a := assert.New(t)
|
|
||||||
c := newApp("new-test", model.NEW, nil, a)
|
|
||||||
a.Nil(main.Commands[model.NEW].RunWith(c), "New failed")
|
|
||||||
})
|
|
||||||
t.Run("Path", func(t *testing.T) {
|
|
||||||
a := assert.New(t)
|
|
||||||
c := newApp("new/test/a", model.NEW, nil, a)
|
|
||||||
a.Nil(main.Commands[model.NEW].RunWith(c), "New path failed")
|
|
||||||
})
|
|
||||||
t.Run("Path-Duplicate", func(t *testing.T) {
|
|
||||||
a := assert.New(t)
|
|
||||||
c := newApp("new/test/b", model.NEW, nil, a)
|
|
||||||
a.Nil(main.Commands[model.NEW].RunWith(c), "New path failed")
|
|
||||||
c = newApp("new/test/b", model.NEW, nil, a)
|
|
||||||
a.NotNil(main.Commands[model.NEW].RunWith(c), "Duplicate path Did Not failed")
|
|
||||||
})
|
|
||||||
t.Run("Skeleton-Git", func(t *testing.T) {
|
|
||||||
a := assert.New(t)
|
|
||||||
c := newApp("new/test/c/1", model.NEW, nil, a)
|
|
||||||
c.New.SkeletonPath = "git://github.com/revel/skeletons:basicnsadnsak"
|
|
||||||
a.NotNil(main.Commands[model.NEW].RunWith(c), "Expected Failed to run with new")
|
|
||||||
// We need to pick a different path
|
|
||||||
c = newApp("new/test/c/2", model.NEW, nil, a)
|
|
||||||
c.New.SkeletonPath = "git://github.com/revel/skeletons:basic/bootstrap4"
|
|
||||||
a.Nil(main.Commands[model.NEW].RunWith(c), "Failed to run with new skeleton git")
|
|
||||||
})
|
|
||||||
if !t.Failed() {
|
|
||||||
if err := os.RemoveAll(gopath); err != nil {
|
|
||||||
a.Fail("Failed to remove test path")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// test the commands
|
|
||||||
func TestNewVendor(t *testing.T) {
|
|
||||||
a := assert.New(t)
|
|
||||||
gopath := setup("revel-test-new-vendor", a)
|
|
||||||
precall := func(c *model.CommandConfig) {
|
|
||||||
c.New.DepVendored = true
|
|
||||||
}
|
|
||||||
t.Run("New", func(t *testing.T) {
|
t.Run("New", func(t *testing.T) {
|
||||||
a := assert.New(t)
|
a := assert.New(t)
|
||||||
c := newApp("onlyone/v/a", model.NEW, precall, a)
|
c := newApp("new-test", model.NEW, nil, a)
|
||||||
c.New.DepVendored = true
|
|
||||||
a.Nil(main.Commands[model.NEW].RunWith(c), "New failed")
|
a.Nil(main.Commands[model.NEW].RunWith(c), "New failed")
|
||||||
})
|
})
|
||||||
t.Run("Test", func(t *testing.T) {
|
t.Run("Path", func(t *testing.T) {
|
||||||
a := assert.New(t)
|
a := assert.New(t)
|
||||||
c := newApp("onlyone/v/a", model.TEST, nil, a)
|
c := newApp("new/test/a", model.NEW, nil, a)
|
||||||
a.Nil(main.Commands[model.TEST].RunWith(c), "Test failed")
|
a.Nil(main.Commands[model.NEW].RunWith(c), "New path failed")
|
||||||
})
|
})
|
||||||
t.Run("Build", func(t *testing.T) {
|
t.Run("Path-Duplicate", func(t *testing.T) {
|
||||||
a := assert.New(t)
|
a := assert.New(t)
|
||||||
c := newApp("onlyone/v/a", model.BUILD, nil, a)
|
c := newApp("new/test/b", model.NEW, nil, a)
|
||||||
c.Index = model.BUILD
|
a.Nil(main.Commands[model.NEW].RunWith(c), "New path failed")
|
||||||
c.Build.TargetPath = filepath.Join(gopath, "src/onlyone/v/a", "target")
|
c = newApp("new/test/b", model.NEW, nil, a)
|
||||||
a.Nil(main.Commands[model.BUILD].RunWith(c), " Build failed")
|
a.NotNil(main.Commands[model.NEW].RunWith(c), "Duplicate path Did Not failed")
|
||||||
a.True(utils.DirExists(c.Build.TargetPath), "Target folder not made", c.Build.TargetPath)
|
|
||||||
})
|
})
|
||||||
t.Run("Package", func(t *testing.T) {
|
t.Run("Skeleton-Git", func(t *testing.T) {
|
||||||
a := assert.New(t)
|
a := assert.New(t)
|
||||||
c := newApp("onlyone/v/a", model.PACKAGE, nil, a)
|
c := newApp("new/test/c/1", model.NEW, nil, a)
|
||||||
c.Package.TargetPath = filepath.Join(gopath, "src/onlyone/v/a", "target.tar.gz")
|
c.New.SkeletonPath = "git://github.com/revel/skeletons:basicnsadnsak"
|
||||||
a.Nil(main.Commands[model.PACKAGE].RunWith(c), "Package Failed")
|
a.NotNil(main.Commands[model.NEW].RunWith(c), "Expected Failed to run with new")
|
||||||
a.True(utils.Exists(c.Package.TargetPath), "Target package not made", c.Package.TargetPath)
|
// We need to pick a different path
|
||||||
})
|
c = newApp("new/test/c/2", model.NEW, nil, a)
|
||||||
t.Run("TestVendorDir", func(t *testing.T) {
|
c.New.SkeletonPath = "git://github.com/revel/skeletons:basic/bootstrap4"
|
||||||
// Check to see that no additional packages were downloaded outside the vendor folder
|
a.Nil(main.Commands[model.NEW].RunWith(c), "Failed to run with new skeleton git")
|
||||||
files, err := ioutil.ReadDir(gopath)
|
|
||||||
a.Nil(err, "Failed to read gopath folder")
|
|
||||||
// bin/ onlyone/ pkg/ src/
|
|
||||||
a.Equal(3, len(files), "Expected single file in "+gopath)
|
|
||||||
files, err = ioutil.ReadDir(filepath.Join(gopath, "src"))
|
|
||||||
a.Nil(err, "Failed to read src folder")
|
|
||||||
a.Equal(1, len(files), "Expected single file in source folder", filepath.Join(gopath, "src"))
|
|
||||||
})
|
})
|
||||||
if !t.Failed() {
|
if !t.Failed() {
|
||||||
if err := os.RemoveAll(gopath); err != nil {
|
if err := os.RemoveAll(gopath); err != nil {
|
||||||
@@ -99,3 +46,4 @@ func TestNewVendor(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -71,27 +71,27 @@ func main() {
|
|||||||
wd, _ := os.Getwd()
|
wd, _ := os.Getwd()
|
||||||
|
|
||||||
utils.InitLogger(wd, logger.LvlError)
|
utils.InitLogger(wd, logger.LvlError)
|
||||||
parser := flags.NewParser(c, flags.HelpFlag|flags.PassDoubleDash)
|
parser := flags.NewParser(c, flags.HelpFlag | flags.PassDoubleDash)
|
||||||
if len(os.Args)<2 {
|
if len(os.Args) < 2 {
|
||||||
parser.WriteHelp(os.Stdout)
|
parser.WriteHelp(os.Stdout)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := ParseArgs(c, parser, os.Args[1:]); err != nil {
|
if err := ParseArgs(c, parser, os.Args[1:]); err != nil {
|
||||||
fmt.Fprint(os.Stderr, err.Error() +"\n")
|
fmt.Fprint(os.Stderr, err.Error() + "\n")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Switch based on the verbose flag
|
// Switch based on the verbose flag
|
||||||
if len(c.Verbose)>1 {
|
if len(c.Verbose) > 1 {
|
||||||
utils.InitLogger(wd, logger.LvlDebug)
|
utils.InitLogger(wd, logger.LvlDebug)
|
||||||
} else if len(c.Verbose)>0 {
|
} else if len(c.Verbose) > 0 {
|
||||||
utils.InitLogger(wd, logger.LvlInfo)
|
utils.InitLogger(wd, logger.LvlInfo)
|
||||||
} else {
|
} else {
|
||||||
utils.InitLogger(wd, logger.LvlWarn)
|
utils.InitLogger(wd, logger.LvlWarn)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := c.UpdateImportPath();err!=nil {
|
if err := c.UpdateImportPath(); err != nil {
|
||||||
utils.Logger.Error(err.Error())
|
utils.Logger.Error(err.Error())
|
||||||
parser.WriteHelp(os.Stdout)
|
parser.WriteHelp(os.Stdout)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -107,7 +107,7 @@ func main() {
|
|||||||
c.InitPackageResolver()
|
c.InitPackageResolver()
|
||||||
|
|
||||||
if err := command.RunWith(c); err != nil {
|
if err := command.RunWith(c); err != nil {
|
||||||
utils.Logger.Error("Unable to execute","error",err)
|
utils.Logger.Error("Unable to execute", "error", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ func updateRunConfig(c *model.CommandConfig, args []string) bool {
|
|||||||
}
|
}
|
||||||
case 0:
|
case 0:
|
||||||
// Attempt to set the import path to the current working director.
|
// Attempt to set the import path to the current working director.
|
||||||
if c.Run.ImportPath=="" {
|
if c.Run.ImportPath == "" {
|
||||||
c.Run.ImportPath, _ = os.Getwd()
|
c.Run.ImportPath, _ = os.Getwd()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,7 +116,7 @@ func updateRunConfig(c *model.CommandConfig, args []string) bool {
|
|||||||
|
|
||||||
// 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 {
|
||||||
if _, err := build.Import(pathToCheck, "", build.FindOnly);err==nil {
|
if _, err := build.Import(pathToCheck, "", build.FindOnly); err == nil {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return filepath.IsAbs(pathToCheck)
|
return filepath.IsAbs(pathToCheck)
|
||||||
@@ -160,7 +160,7 @@ func runApp(c *model.CommandConfig) (err error) {
|
|||||||
}
|
}
|
||||||
app.Port = revel_path.HTTPPort
|
app.Port = revel_path.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))
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ func init() {
|
|||||||
// 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 != "" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +99,7 @@ func testApp(c *model.CommandConfig) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Direct all the output into a file in the test-results directory.
|
// Direct all the output into a file in the test-results directory.
|
||||||
file, err := os.OpenFile(filepath.Join(resultPath, "app.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
file, err := os.OpenFile(filepath.Join(resultPath, "app.log"), os.O_CREATE | os.O_WRONLY | os.O_APPEND, 0666)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.NewBuildError("Failed to create test result log file: ", "error", err)
|
return utils.NewBuildError("Failed to create test result log file: ", "error", err)
|
||||||
}
|
}
|
||||||
@@ -109,7 +109,7 @@ func testApp(c *model.CommandConfig) (err error) {
|
|||||||
return utils.NewBuildIfError(reverr, "Error building: ")
|
return utils.NewBuildIfError(reverr, "Error building: ")
|
||||||
}
|
}
|
||||||
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))
|
||||||
@@ -117,7 +117,7 @@ func testApp(c *model.CommandConfig) (err error) {
|
|||||||
runMode = app.Paths.RunMode
|
runMode = app.Paths.RunMode
|
||||||
}
|
}
|
||||||
cmd := app.Cmd(runMode)
|
cmd := app.Cmd(runMode)
|
||||||
cmd.Dir=c.AppPath
|
cmd.Dir = c.AppPath
|
||||||
|
|
||||||
cmd.Stderr = io.MultiWriter(cmd.Stderr, file)
|
cmd.Stderr = io.MultiWriter(cmd.Stderr, file)
|
||||||
cmd.Stdout = io.MultiWriter(cmd.Stderr, file)
|
cmd.Stdout = io.MultiWriter(cmd.Stderr, file)
|
||||||
@@ -234,7 +234,7 @@ func filterTestSuites(suites *[]tests.TestSuiteDesc, suiteArgument string) *[]te
|
|||||||
// in case it hasn't finished starting up yet.
|
// in case it hasn't finished starting up yet.
|
||||||
func getTestsList(baseURL string) (*[]tests.TestSuiteDesc, error) {
|
func getTestsList(baseURL string) (*[]tests.TestSuiteDesc, error) {
|
||||||
var (
|
var (
|
||||||
err error
|
err error
|
||||||
resp *http.Response
|
resp *http.Response
|
||||||
testSuites []tests.TestSuiteDesc
|
testSuites []tests.TestSuiteDesc
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -29,10 +29,10 @@ import (
|
|||||||
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
|
||||||
modulesVersion *model.Version // The Revel modules version
|
modulesVersion *model.Version // The Revel modules version
|
||||||
cmdVersion *model.Version // The tool version
|
cmdVersion *model.Version // The tool version
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -74,10 +74,10 @@ func (v *VersionCommand) RunWith(c *model.CommandConfig) (err error) {
|
|||||||
versionInfo := ""
|
versionInfo := ""
|
||||||
for x := 0; x < 2 && needsUpdates; x++ {
|
for x := 0; x < 2 && needsUpdates; x++ {
|
||||||
needsUpdates = false
|
needsUpdates = false
|
||||||
versionInfo, needsUpdates = v.doRepoCheck(x==0)
|
versionInfo, needsUpdates = v.doRepoCheck(x == 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("%s\n\nGo Location:%s\n\n",versionInfo,c.GoCmd)
|
fmt.Printf("%s\n\nGo Location:%s\n\n", versionInfo, c.GoCmd)
|
||||||
cmd := exec.Command(c.GoCmd, "version")
|
cmd := exec.Command(c.GoCmd, "version")
|
||||||
cmd.Stdout = os.Stdout
|
cmd.Stdout = os.Stdout
|
||||||
if e := cmd.Start(); e != nil {
|
if e := cmd.Start(); e != nil {
|
||||||
@@ -112,7 +112,7 @@ 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
|
||||||
shouldUpdate := updateLibs && v.Command.Version.Update
|
shouldUpdate := updateLibs && v.Command.Version.Update
|
||||||
if v.Command.Version.Update {
|
if v.Command.Version.Update {
|
||||||
if localVersion == nil || (versonFromRepo != nil && versonFromRepo.Newer(localVersion)) {
|
if localVersion == nil || (versonFromRepo != nil && versonFromRepo.Newer(localVersion)) {
|
||||||
needsUpdate = true
|
needsUpdate = true
|
||||||
if shouldUpdate {
|
if shouldUpdate {
|
||||||
v.doUpdate(title, repo, localVersion, versonFromRepo)
|
v.doUpdate(title, repo, localVersion, versonFromRepo)
|
||||||
@@ -127,7 +127,7 @@ func (v *VersionCommand) doRepoCheck(updateLibs bool) (versionInfo string, needs
|
|||||||
|
|
||||||
// Checks for updates if needed
|
// Checks for updates if needed
|
||||||
func (v *VersionCommand) doUpdate(title, repo string, local, remote *model.Version) {
|
func (v *VersionCommand) doUpdate(title, repo string, local, remote *model.Version) {
|
||||||
utils.Logger.Info("Updating package", "package", title, "repo",repo)
|
utils.Logger.Info("Updating package", "package", title, "repo", repo)
|
||||||
fmt.Println("Attempting to update package", title)
|
fmt.Println("Attempting to update package", title)
|
||||||
if err := v.Command.PackageResolver(repo); err != nil {
|
if err := v.Command.PackageResolver(repo); err != nil {
|
||||||
utils.Logger.Error("Unable to update repo", "repo", repo, "error", err)
|
utils.Logger.Error("Unable to update repo", "repo", repo, "error", err)
|
||||||
@@ -228,15 +228,15 @@ func (v *VersionCommand) versionFromBytes(sourceStream []byte) (version *model.V
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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)
|
||||||
v.cmdVersion.BuildDate = cmd.BuildDate
|
v.cmdVersion.BuildDate = cmd.BuildDate
|
||||||
v.cmdVersion.MinGoVersion = cmd.MinimumGoVersion
|
v.cmdVersion.MinGoVersion = cmd.MinimumGoVersion
|
||||||
|
|
||||||
pathMap, err := utils.FindSrcPaths(v.Command.AppPath,[]string{model.RevelImportPath,model.RevelModulesImportPath}, v.Command.PackageResolver)
|
pathMap, err := utils.FindSrcPaths(v.Command.AppPath, []string{model.RevelImportPath, model.RevelModulesImportPath}, v.Command.PackageResolver)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.Logger.Warn("Unable to extract version information from Revel library", "path",pathMap[model.RevelImportPath], "error",err)
|
utils.Logger.Warn("Unable to extract version information from Revel library", "path", pathMap[model.RevelImportPath], "error", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
utils.Logger.Info("Fullpath to revel modules", "dir", pathMap[model.RevelImportPath])
|
utils.Logger.Info("Fullpath to revel modules", "dir", pathMap[model.RevelImportPath])
|
||||||
|
|||||||
@@ -73,10 +73,10 @@ func NewCompileError(importPath, errorLink string, error error) *SourceError {
|
|||||||
|
|
||||||
// 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"
|
||||||
absFilename = relFilename
|
absFilename = relFilename
|
||||||
line, _ = strconv.Atoi(string(errorMatch[2]))
|
line, _ = strconv.Atoi(string(errorMatch[2]))
|
||||||
description = string(errorMatch[4])
|
description = string(errorMatch[4])
|
||||||
compileError = &SourceError{
|
compileError = &SourceError{
|
||||||
SourceType: "Go code",
|
SourceType: "Go code",
|
||||||
Title: "Go Compilation Error",
|
Title: "Go Compilation Error",
|
||||||
@@ -95,7 +95,7 @@ func NewCompileError(importPath, errorLink string, error error) *SourceError {
|
|||||||
fileStr, err := ReadLines(absFilename)
|
fileStr, err := ReadLines(absFilename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
compileError.MetaError = absFilename + ": " + err.Error()
|
compileError.MetaError = absFilename + ": " + err.Error()
|
||||||
Logger.Info("Unable to readlines "+compileError.MetaError, "error", err)
|
Logger.Info("Unable to readlines " + compileError.MetaError, "error", err)
|
||||||
return compileError
|
return compileError
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,25 +10,27 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Initialize the command based on the GO environment
|
// Initialize the command based on the GO environment
|
||||||
func CmdInit(c *exec.Cmd, 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
|
||||||
realPath := &bytes.Buffer{}
|
realPath := &bytes.Buffer{}
|
||||||
for _, p := range filepath.SplitList(build.Default.GOPATH) {
|
if addGoPath {
|
||||||
rp,_ := filepath.EvalSymlinks(p)
|
for _, p := range filepath.SplitList(build.Default.GOPATH) {
|
||||||
if realPath.Len() > 0 {
|
rp, _ := filepath.EvalSymlinks(p)
|
||||||
realPath.WriteString(string(filepath.ListSeparator))
|
if realPath.Len() > 0 {
|
||||||
|
realPath.WriteString(string(filepath.ListSeparator))
|
||||||
|
}
|
||||||
|
realPath.WriteString(rp)
|
||||||
}
|
}
|
||||||
realPath.WriteString(rp)
|
// Go 1.8 fails if we do not include the GOROOT
|
||||||
|
c.Env = []string{"GOPATH=" + realPath.String(), "GOROOT=" + os.Getenv("GOROOT")}
|
||||||
}
|
}
|
||||||
// Go 1.8 fails if we do not include the GOROOT
|
|
||||||
c.Env = []string{"GOPATH=" + realPath.String(), "GOROOT="+ os.Getenv("GOROOT")}
|
|
||||||
// Fetch the rest of the env variables
|
// Fetch the rest of the env variables
|
||||||
for _, e := range os.Environ() {
|
for _, e := range os.Environ() {
|
||||||
pair := strings.Split(e, "=")
|
pair := strings.Split(e, "=")
|
||||||
if pair[0]=="GOPATH" || pair[0]=="GOROOT" {
|
if pair[0] == "GOPATH" || pair[0] == "GOROOT" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
c.Env = append(c.Env,e)
|
c.Env = append(c.Env, e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ type (
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
// 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,
|
||||||
Title:title,
|
Title:title,
|
||||||
@@ -82,7 +82,7 @@ func (e *SourceError) ContextSource() []SourceLine {
|
|||||||
end = len(e.SourceLines)
|
end = len(e.SourceLines)
|
||||||
}
|
}
|
||||||
|
|
||||||
lines := make([]SourceLine, end-start)
|
lines := make([]SourceLine, end - start)
|
||||||
for i, src := range e.SourceLines[start:end] {
|
for i, src := range e.SourceLines[start:end] {
|
||||||
fileLine := start + i + 1
|
fileLine := start + i + 1
|
||||||
lines[i] = SourceLine{src, fileLine, fileLine == e.Line}
|
lines[i] = SourceLine{src, fileLine, fileLine == e.Line}
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ func GenerateTemplate(filename, templateSource string, args map[string]interface
|
|||||||
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 {
|
||||||
return NewBuildIfError(err, "Failed to parse template "+srcPath)
|
return NewBuildIfError(err, "Failed to parse template " + srcPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
f, err := os.Create(destPath)
|
f, err := os.Create(destPath)
|
||||||
@@ -119,12 +119,12 @@ func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
|
|||||||
|
|
||||||
err = tmpl.Execute(f, data)
|
err = tmpl.Execute(f, data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return NewBuildIfError(err, "Failed to Render template "+srcPath)
|
return NewBuildIfError(err, "Failed to Render template " + srcPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = f.Close()
|
err = f.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return NewBuildIfError(err, "Failed to close file stream "+destPath)
|
return NewBuildIfError(err, "Failed to close file stream " + destPath)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -133,12 +133,12 @@ func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
|
|||||||
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 {
|
||||||
return NewBuildIfError(err, "Failed to parse template "+srcPath[0])
|
return NewBuildIfError(err, "Failed to parse template " + srcPath[0])
|
||||||
}
|
}
|
||||||
|
|
||||||
err = tmpl.Execute(output, data)
|
err = tmpl.Execute(output, data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return NewBuildIfError(err, "Failed to render template "+srcPath[0])
|
return NewBuildIfError(err, "Failed to render template " + srcPath[0])
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -181,7 +181,7 @@ func CopyDir(destDir, srcDir string, data map[string]interface{}) error {
|
|||||||
if info.IsDir() {
|
if info.IsDir() {
|
||||||
err := os.MkdirAll(filepath.Join(destDir, relSrcPath), 0777)
|
err := os.MkdirAll(filepath.Join(destDir, relSrcPath), 0777)
|
||||||
if !os.IsExist(err) {
|
if !os.IsExist(err) {
|
||||||
return NewBuildIfError(err, "Failed to create directory", "path", destDir+"/"+relSrcPath)
|
return NewBuildIfError(err, "Failed to create directory", "path", destDir + "/" + relSrcPath)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -189,7 +189,7 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Else, just copy it over.
|
// Else, just copy it over.
|
||||||
@@ -218,7 +218,7 @@ func fsWalk(fname string, linkName string, walkFn filepath.WalkFunc) error {
|
|||||||
|
|
||||||
path = filepath.Join(linkName, name)
|
path = filepath.Join(linkName, name)
|
||||||
|
|
||||||
if err == nil && info.Mode()&os.ModeSymlink == os.ModeSymlink {
|
if err == nil && info.Mode() & os.ModeSymlink == os.ModeSymlink {
|
||||||
var symlinkPath string
|
var symlinkPath string
|
||||||
symlinkPath, err = filepath.EvalSymlinks(path)
|
symlinkPath, err = filepath.EvalSymlinks(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -321,16 +321,16 @@ func Empty(dirname string) bool {
|
|||||||
|
|
||||||
// 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 {
|
if err != nil && packageResolver != nil {
|
||||||
for _, item := range missingList {
|
for _, item := range missingList {
|
||||||
if err = packageResolver(item); err != nil {
|
if err = packageResolver(item); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sourcePathsmap,missingList,err = findSrcPaths(appPath,packageList)
|
sourcePathsmap, missingList, err = findSrcPaths(appPath, packageList)
|
||||||
}
|
}
|
||||||
if err!=nil && len(missingList)>0 {
|
if err != nil && len(missingList) > 0 {
|
||||||
for _, missing := range missingList {
|
for _, missing := range missingList {
|
||||||
Logger.Error("Unable to import this package", "package", missing)
|
Logger.Error("Unable to import this package", "package", missing)
|
||||||
}
|
}
|
||||||
@@ -338,6 +338,7 @@ func FindSrcPaths(appPath string, packageList []string, packageResolver func(pkg
|
|||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var NO_APP_FOUND = errors.New("No app found")
|
var NO_APP_FOUND = errors.New("No app found")
|
||||||
var NO_REVEL_FOUND = errors.New("No revel found")
|
var NO_REVEL_FOUND = errors.New("No revel found")
|
||||||
|
|
||||||
@@ -351,20 +352,19 @@ func findSrcPaths(appPath string, packagesList []string) (sourcePathsmap map[str
|
|||||||
}
|
}
|
||||||
sourcePathsmap = map[string]string{}
|
sourcePathsmap = map[string]string{}
|
||||||
|
|
||||||
pkgs, err := packages.Load(config, packagesList...)
|
pkgs, err := packages.Load(config, packagesList...)
|
||||||
Logger.Info("Loaded packages ", "len results", len(pkgs), "error",err,"basedir",appPath)
|
Logger.Info("Loaded packages ", "len results", len(pkgs), "error", err, "basedir", appPath)
|
||||||
for _, packageName := range packagesList {
|
for _, packageName := range packagesList {
|
||||||
found := false
|
found := false
|
||||||
log:= Logger.New("seeking",packageName)
|
log := Logger.New("seeking", packageName)
|
||||||
for _, pck := range pkgs {
|
for _, pck := range pkgs {
|
||||||
log.Info("Found package","package",pck.ID)
|
log.Info("Found package", "package", pck.ID)
|
||||||
if pck.ID == packageName {
|
if pck.ID == packageName {
|
||||||
if pck.Errors!=nil && len(pck.Errors)>0 {
|
if pck.Errors != nil && len(pck.Errors) > 0 {
|
||||||
log.Info("Error ", "count", len(pck.Errors), "App Import Path", pck.ID,"errors",pck.Errors)
|
log.Info("Error ", "count", len(pck.Errors), "App Import Path", pck.ID, "errors", pck.Errors)
|
||||||
|
|
||||||
}
|
}
|
||||||
//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)
|
||||||
sourcePathsmap[packageName] = filepath.Dir(pck.GoFiles[0])
|
sourcePathsmap[packageName] = filepath.Dir(pck.GoFiles[0])
|
||||||
found = true
|
found = true
|
||||||
}
|
}
|
||||||
@@ -375,7 +375,7 @@ func findSrcPaths(appPath string, packagesList []string) (sourcePathsmap map[str
|
|||||||
} else {
|
} else {
|
||||||
err = NO_APP_FOUND
|
err = NO_APP_FOUND
|
||||||
}
|
}
|
||||||
missingList = append(missingList,packageName)
|
missingList = append(missingList, packageName)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user