Updated formating

Ran through testing individually for vendored Revel applications
This commit is contained in:
notzippy@gmail.com
2020-04-26 22:24:00 -07:00
parent 07d67846c1
commit 86736d6e43
22 changed files with 239 additions and 291 deletions

View File

@@ -1,9 +1,9 @@
{
"GOLANG": {
"ABC":[25, 35, 50, 70],
"ABC":[33, 38, 50, 70],
"ARITY":[5,6,7,8],
"BLOCK_NESTING":[7, 9, 11, 13],
"CYCLO":[20, 30, 45, 60],
"BLOCK_NESTING":[9, 10, 12, 13],
"CYCLO":[30, 35, 45, 60],
"TOO_MANY_IVARS": [20, 25, 40, 45],
"TOO_MANY_FUNCTIONS": [20, 30, 40, 50],
"TOTAL_COMPLEXITY": [150, 250, 400, 500],

View File

@@ -65,7 +65,7 @@ func (cmd AppCmd) Start(c *model.CommandConfig) error {
listeningWriter := &startupListeningWriter{os.Stdout, make(chan bool), c, &bytes.Buffer{}}
cmd.Stdout = listeningWriter
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 {
utils.Logger.Fatal("Error running:", "error", err)
}
@@ -73,7 +73,7 @@ func (cmd AppCmd) Start(c *model.CommandConfig) error {
select {
case exitState := <-cmd.waitChan():
fmt.Println("Startup failure view previous messages, \n Proxy is listening :", c.Run.Port)
err := utils.NewError("","Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState,"")
err := utils.NewError("", "Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState, "")
// TODO pretiffy command line output
// err.MetaError = listeningWriter.getLastOutput()
return err
@@ -199,7 +199,7 @@ func (w *startupListeningWriter) Write(p []byte) (int, error) {
w.notifyReady = nil
}
}
if w.notifyReady!=nil {
if w.notifyReady != nil {
w.buffer.Write(p)
}
return w.dest.Write(p)

View File

@@ -29,9 +29,15 @@ var importErrorPattern = regexp.MustCompile("cannot find package \"([^\"]+)\"")
type ByString []*model.TypeInfo
func (c ByString) Len() int { return len(c) }
func (c ByString) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c ByString) Less(i, j int) bool { return c[i].String() < c[j].String() }
func (c ByString) Len() int {
return len(c)
}
func (c ByString) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
func (c ByString) Less(i, j int) bool {
return c[i].String() < c[j].String()
}
// Build the app:
// 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.
binName := filepath.Join(paths.BasePath, "target", paths.ImportPath, filepath.Base(paths.BasePath))
// Binary path is a combination of BasePath/target/app directory, app's import path and its name.
binName := filepath.Join(paths.BasePath, "target", "app", paths.ImportPath, filepath.Base(paths.BasePath))
// Change binary path for Windows build
goos := runtime.GOOS
@@ -139,14 +145,10 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
}
for {
appVersion := getAppVersion(paths)
if appVersion == "" {
appVersion = "noVersionProvided"
}
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)
// 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") {
flags = []string{"build"}
}
flags = append(flags, c.BuildFlags...)
if !contains(flags, "-ldflags") {
ldflags := "-ldflags= " + versionLinkerFlags
// Add in build flags
for i := range c.BuildFlags {
ldflags += "-X '" + c.BuildFlags[i] + "'"
}
flags = append(flags, ldflags)
flags = append(flags, "-ldflags", versionLinkerFlags)
}
if !contains(flags, "-tags") {
flags = append(flags, "-tags", buildTags)
@@ -177,31 +175,38 @@ func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err err
}
}
// Add in build flags
flags = append(flags, c.BuildFlags...)
// Note: It's not applicable for filepath.* usage
flags = append(flags, path.Join(paths.ImportPath, "app", "tmp"))
buildCmd := exec.Command(goPath, flags...)
if !c.Vendored {
// This is Go main path
gopath := c.GoPath
for _, o := range paths.ModulePathMap {
gopath += string(filepath.ListSeparator) + o.Path
}
// Note: It's not applicable for filepath.* usage
flags = append(flags, path.Join(paths.ImportPath, "app", "tmp"))
buildCmd := exec.Command(goPath, flags...)
buildCmd.Env = append(os.Environ(),
"GOPATH="+gopath,
"GOPATH=" + gopath,
)
utils.CmdInit(buildCmd, c.AppPath)
utils.Logger.Info("Exec:", "args", buildCmd.Args,"working dir", buildCmd.Dir)
}
utils.CmdInit(buildCmd, !c.Vendored, c.AppPath)
utils.Logger.Info("Exec:", "args", buildCmd.Args, "working dir", buildCmd.Dir)
output, err := buildCmd.CombinedOutput()
// If the build succeeded, we're done.
if err == nil {
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
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.
matches := importErrorPattern.FindAllStringSubmatch(stOutput, -1)
@@ -253,7 +258,7 @@ func getAppVersion(paths *model.RevelContainer) string {
if (err != nil && os.IsNotExist(err)) || !info.IsDir() {
return ""
}
gitCmd := exec.Command(gitPath, "--git-dir="+gitDir, "--work-tree="+paths.BasePath, "describe", "--always", "--dirty")
gitCmd := exec.Command(gitPath, "--git-dir=" + gitDir, "--work-tree=" + paths.BasePath, "describe", "--always", "--dirty")
utils.Logger.Info("Exec:", "args", gitCmd.Args)
output, err := gitCmd.Output()
@@ -418,6 +423,7 @@ func newCompileError(paths *model.RevelContainer, output []byte) *utils.SourceEr
return newPath
}
// Read the source for the offending file.
var (
relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go"
@@ -442,7 +448,7 @@ func newCompileError(paths *model.RevelContainer, output []byte) *utils.SourceEr
fileStr, err := utils.ReadLines(absFilename)
if err != nil {
compileError.MetaError = absFilename + ": " + err.Error()
utils.Logger.Info("Unable to readlines "+compileError.MetaError, "error", err)
utils.Logger.Info("Unable to readlines " + compileError.MetaError, "error", err)
return compileError
}

View File

@@ -99,7 +99,7 @@ func (c callHandler) Log(log *log15.Record) error {
ctx := log.Ctx
var ctxMap ContextMap
if len(ctx) > 0 {
ctxMap = make(ContextMap, len(ctx)/2)
ctxMap = make(ContextMap, len(ctx) / 2)
for i := 0; i < len(ctx); i += 2 {
v := ctx[i]
@@ -108,8 +108,8 @@ func (c callHandler) Log(log *log15.Record) error {
key = fmt.Sprintf("LOGGER_INVALID_KEY %v", v)
}
var value interface{}
if len(ctx) > i+1 {
value = ctx[i+1]
if len(ctx) > i + 1 {
value = ctx[i + 1]
} else {
value = "LOGGER_VALUE_MISSING"
}

View File

@@ -1,4 +1,6 @@
package command
type (
New struct {
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"`
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"`
Callback func() error
}
)

View File

@@ -177,7 +177,7 @@ func (c *CommandConfig) initAppFolder() (err error) {
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
goModFile := filepath.Join(appFolder,"go.mod")
@@ -214,6 +214,7 @@ func (c *CommandConfig) initAppFolder() (err error) {
workingDir, _ := os.Getwd()
goPathList := filepath.SplitList(c.GoPath)
bestpath := ""
if !c.Vendored {
for _, path := range goPathList {
if c.Index == NEW {
// If the GOPATH is part of the working dir this is the most likely target
@@ -227,12 +228,16 @@ func (c *CommandConfig) initAppFolder() (err error) {
}
}
}
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
}
} else {
c.SrcRoot = appFolder
}
utils.Logger.Info("Source root", "path", c.SrcRoot, "cwd", workingDir, "gopath", c.GoPath, "bestpath",bestpath)
// If source root is empty and this isn't a version then skip it
if len(c.SrcRoot) == 0 {
if c.Index == NEW {
@@ -270,32 +275,11 @@ func (c *CommandConfig) InitPackageResolver() {
utils.Logger.Info("Request for package ", "package", pkgName, "use vendor", c.Vendored)
if c.Vendored {
goModCmd := exec.Command("go", "mod", "tidy")
utils.CmdInit(goModCmd, c.AppPath)
utils.CmdInit(goModCmd,!c.Vendored, c.AppPath)
goModCmd.Run()
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
}
}

View File

@@ -76,7 +76,7 @@ func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered
utils.Logger.Info("Debug: Skipping adding spec for unexported type",
"type", filteredItem.StructName,
"package", filteredItem.ImportPath)
filtered = append(filtered[:i], filtered[i+1:]...)
filtered = append(filtered[:i], filtered[i + 1:]...)
exit = false
break
}
@@ -99,8 +99,8 @@ func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered
// Report non controller structures in controller folder.
if !found && !strings.HasPrefix(spec.StructName, "Test") {
utils.Logger.Warn("Type found in package: "+packageFilter+
", but did not embed from: "+filepath.Base(targetType),
utils.Logger.Warn("Type found in package: " + packageFilter +
", but did not embed from: " + filepath.Base(targetType),
"name", spec.StructName, "importpath", spec.ImportPath, "foundstructures", unfoundNames)
}
}
@@ -112,7 +112,7 @@ func (s *SourceInfo) TypesThatEmbed(targetType, packageFilter string) (filtered
// `revel.Controller`
func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
if s.controllerSpecs == nil {
s.controllerSpecs = s.TypesThatEmbed(RevelImportPath+".Controller", "controllers")
s.controllerSpecs = s.TypesThatEmbed(RevelImportPath + ".Controller", "controllers")
}
return s.controllerSpecs
}
@@ -121,7 +121,7 @@ func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
// `testing.TestSuite`
func (s *SourceInfo) TestSuites() []*TypeInfo {
if s.testSuites == nil {
s.testSuites = s.TypesThatEmbed(RevelImportPath+"/testing.TestSuite", "testsuite")
s.testSuites = s.TypesThatEmbed(RevelImportPath + "/testing.TestSuite", "testsuite")
}
return s.testSuites
}

View File

@@ -15,11 +15,11 @@ type (
sourceProcessor *SourceProcessor
}
)
func NewSourceInfoProcessor(sourceProcessor *SourceProcessor) *SourceInfoProcessor {
return &SourceInfoProcessor{sourceProcessor:sourceProcessor}
}
func (s *SourceInfoProcessor) processPackage(p *packages.Package) (sourceInfo *model.SourceInfo) {
sourceInfo = &model.SourceInfo{
ValidationKeys: map[string]map[int]string{},
@@ -31,7 +31,7 @@ func (s *SourceInfoProcessor) processPackage(p *packages.Package) (sourceInfo *m
strings.Contains(p.PkgPath, "/tests/")
methodMap = map[string][]*model.MethodSpec{}
)
for _,tree := range p.Syntax {
for _, tree := range p.Syntax {
for _, decl := range tree.Decls {
s.sourceProcessor.packageMap[p.PkgPath] = filepath.Dir(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
if isController &&
funcDecl.Recv!=nil && // Must have a receiver
funcDecl.Recv != nil && // Must have a receiver
funcDecl.Name.IsExported() && // be public
funcDecl.Type.Results != nil && len(funcDecl.Type.Results.List) == 1 { // return one result
if m, receiver:=s.getControllerFunc(funcDecl,p);m!=nil {
methodMap[receiver]=append(methodMap[receiver],m)
s.sourceProcessor.log.Info("Added method map to ","receiver",receiver,"method",m.Name)
funcDecl.Type.Results != nil && len(funcDecl.Type.Results.List) == 1 {
// return one result
if m, receiver := s.getControllerFunc(funcDecl, p); m != nil {
methodMap[receiver] = append(methodMap[receiver], m)
s.sourceProcessor.log.Info("Added method map to ", "receiver", receiver, "method", m.Name)
}
}
// Check for validation
if lineKeyMap := s.getValidation(funcDecl,p);len(lineKeyMap)>1 {
sourceInfo.ValidationKeys[p.PkgPath+"."+s.getFuncName(funcDecl)] = lineKeyMap
if lineKeyMap := s.getValidation(funcDecl, p); len(lineKeyMap) > 1 {
sourceInfo.ValidationKeys[p.PkgPath + "." + s.getFuncName(funcDecl)] = lineKeyMap
}
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
// 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 (
lineKeys = make(map[int]string)
@@ -182,7 +183,7 @@ func (s *SourceInfoProcessor) getValidationParameter(funcDecl *ast.FuncDecl) *a
}
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)
if !ok {
return
@@ -270,7 +271,7 @@ func (s *SourceInfoProcessor) getControllerFunc(funcDecl *ast.FuncDecl,p *packag
}
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)
// 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 {
var ok bool
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
}
}
@@ -339,7 +340,7 @@ func (s *SourceInfoProcessor) getControllerSpec(spec *ast.TypeSpec,p *packages.P
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
}
func (s *SourceInfoProcessor) getStructTypeDecl(decl ast.Decl, fset *token.FileSet) (spec *ast.TypeSpec, found bool) {

View File

@@ -29,8 +29,8 @@ func ProcessSource(revelContainer *model.RevelContainer) (sourceInfo *model.Sour
processor := NewSourceProcessor(revelContainer)
compileError = processor.parse()
sourceInfo = processor.sourceInfo
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)
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)
}
if false {
@@ -58,7 +58,7 @@ func (s *SourceProcessor) parse() (compileError error) {
s.sourceInfo.PackageMap = map[string]string{}
getImportFromMap := func(packagePath string) string {
for path := range s.packageMap {
if strings.Index(path,packagePath)==0 {
if strings.Index(path, packagePath) == 0 {
fullPath := s.packageMap[path]
return fullPath[:(len(fullPath) - len(path) + len(packagePath))]
}
@@ -74,7 +74,7 @@ func (s *SourceProcessor) parse() (compileError error) {
return
}
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 {
allPackages = append(allPackages, module.ImportPath + "/...") // +"/app/controllers/...")
}

View File

@@ -37,10 +37,10 @@ func init() {
// The update config updates the configuration command so that it can run
func updateBuildConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.BUILD
if c.Build.TargetPath=="" {
c.Build.TargetPath="target"
if c.Build.TargetPath == "" {
c.Build.TargetPath = "target"
}
if len(args)==0 && c.Build.ImportPath!="" {
if len(args) == 0 && c.Build.ImportPath != "" {
return true
}
// 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 == "" {
continue
}
moduleImportList =append(moduleImportList,moduleImportPath)
moduleImportList = append(moduleImportList, moduleImportPath)
}
}
// Copy the the paths for each of the modules
for _,importPath := range moduleImportList {
for _, importPath := range moduleImportList {
fsPath := app.PackagePathMap[importPath]
utils.Logger.Info("Copy files ", "to", filepath.Join(destPath, importPath), "from", fsPath)
if c.Build.CopySource {

View File

@@ -37,7 +37,7 @@ func init() {
// Update the clean command configuration, using old method
func updateCleanConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.CLEAN
if len(args)==0 && c.Clean.ImportPath!="" {
if len(args) == 0 && c.Clean.ImportPath != "" {
return true
}
if len(args) == 0 {

View File

@@ -46,13 +46,13 @@ func init() {
// Called when unable to parse the command line automatically and assumes an old launch
func updateNewConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.NEW
if len(c.New.Package)>0 {
if len(c.New.Package) > 0 {
c.New.NotVendored = false
}
c.Vendored = !c.New.NotVendored
if len(args) == 0 {
if len(c.New.ImportPath)==0 {
if len(c.New.ImportPath) == 0 {
fmt.Fprintf(os.Stderr, cmdNew.Long)
return false
}
@@ -76,7 +76,7 @@ func newApp(c *model.CommandConfig) (err error) {
}
// checking and setting skeleton
if err=setSkeletonPath(c);err!=nil {
if err = setSkeletonPath(c); err != nil {
return
}
@@ -90,18 +90,20 @@ func newApp(c *model.CommandConfig) (err error) {
return err
}
// This kicked off the download of the revel app, not needed for vendor
if !c.Vendored {
// At this point the versions can be set
c.SetVersions()
}
// copy files to new app directory
if err = copyNewAppFiles(c);err != nil {
if err = copyNewAppFiles(c); err != nil {
return
}
// Run the vendor tool if needed
println("********** here",c.Vendored)
if c.Vendored {
if err=createModVendor(c); err!=nil {
if err = createModVendor(c); err != nil {
return
}
}
@@ -120,13 +122,15 @@ func newApp(c *model.CommandConfig) (err error) {
func createModVendor(c *model.CommandConfig) (err error) {
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()
if c.New.Callback != nil {
err = c.New.Callback()
}
if err != nil {
return utils.NewBuildIfError(err, string(getOutput))
}
@@ -141,7 +145,7 @@ func createDepVendor(c *model.CommandConfig) (err error) {
if !utils.DirExists(vendorPath) {
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)
if !utils.DirExists(tempPath) {
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 {
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")
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()
if err != nil {
return utils.NewBuildIfError(err, string(getOutput))
@@ -211,7 +215,7 @@ func setApplicationPath(c *model.CommandConfig) (err error) {
//// Go get the revel project
err = c.PackageResolver(model.RevelImportPath)
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) {
// TODO Add support for ftp, sftp, scp ??
case "" :
sp.Scheme="file"
sp.Scheme = "file"
fallthrough
case "file" :
fullpath := sp.String()[7:]
if !filepath.IsAbs(fullpath) {
fullpath, err = filepath.Abs(fullpath)
if err!=nil {
if err != nil {
return
}
}
@@ -276,11 +280,11 @@ func newLoadFromGit(c *model.CommandConfig, sp *url.URL) (err error) {
targetPath := filepath.Join(os.TempDir(), "revel", "skeleton")
os.RemoveAll(targetPath)
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)
getOutput, err := getCmd.CombinedOutput()
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
if len(pathpart) > 1 {

View File

@@ -3,11 +3,8 @@ package main_test
import (
"github.com/revel/cmd/model"
"github.com/revel/cmd/revel"
"github.com/revel/cmd/utils"
"github.com/stretchr/testify/assert"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
@@ -50,52 +47,3 @@ func TestNew(t *testing.T) {
}
}
// 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) {
a := assert.New(t)
c := newApp("onlyone/v/a", model.NEW, precall, a)
c.New.DepVendored = true
a.Nil(main.Commands[model.NEW].RunWith(c), "New failed")
})
t.Run("Test", func(t *testing.T) {
a := assert.New(t)
c := newApp("onlyone/v/a", model.TEST, nil, a)
a.Nil(main.Commands[model.TEST].RunWith(c), "Test failed")
})
t.Run("Build", func(t *testing.T) {
a := assert.New(t)
c := newApp("onlyone/v/a", model.BUILD, nil, a)
c.Index = model.BUILD
c.Build.TargetPath = filepath.Join(gopath, "src/onlyone/v/a", "target")
a.Nil(main.Commands[model.BUILD].RunWith(c), " Build failed")
a.True(utils.DirExists(c.Build.TargetPath), "Target folder not made", c.Build.TargetPath)
})
t.Run("Package", func(t *testing.T) {
a := assert.New(t)
c := newApp("onlyone/v/a", model.PACKAGE, nil, a)
c.Package.TargetPath = filepath.Join(gopath, "src/onlyone/v/a", "target.tar.gz")
a.Nil(main.Commands[model.PACKAGE].RunWith(c), "Package Failed")
a.True(utils.Exists(c.Package.TargetPath), "Target package not made", c.Package.TargetPath)
})
t.Run("TestVendorDir", func(t *testing.T) {
// Check to see that no additional packages were downloaded outside the vendor folder
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 err := os.RemoveAll(gopath); err != nil {
a.Fail("Failed to remove test path")
}
}
}

View File

@@ -71,27 +71,27 @@ func main() {
wd, _ := os.Getwd()
utils.InitLogger(wd, logger.LvlError)
parser := flags.NewParser(c, flags.HelpFlag|flags.PassDoubleDash)
if len(os.Args)<2 {
parser := flags.NewParser(c, flags.HelpFlag | flags.PassDoubleDash)
if len(os.Args) < 2 {
parser.WriteHelp(os.Stdout)
os.Exit(1)
}
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)
}
// Switch based on the verbose flag
if len(c.Verbose)>1 {
if len(c.Verbose) > 1 {
utils.InitLogger(wd, logger.LvlDebug)
} else if len(c.Verbose)>0 {
} else if len(c.Verbose) > 0 {
utils.InitLogger(wd, logger.LvlInfo)
} else {
utils.InitLogger(wd, logger.LvlWarn)
}
if err := c.UpdateImportPath();err!=nil {
if err := c.UpdateImportPath(); err != nil {
utils.Logger.Error(err.Error())
parser.WriteHelp(os.Stdout)
os.Exit(1)
@@ -107,7 +107,7 @@ func main() {
c.InitPackageResolver()
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)
}
}

View File

@@ -106,7 +106,7 @@ func updateRunConfig(c *model.CommandConfig, args []string) bool {
}
case 0:
// Attempt to set the import path to the current working director.
if c.Run.ImportPath=="" {
if c.Run.ImportPath == "" {
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
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 filepath.IsAbs(pathToCheck)
@@ -160,7 +160,7 @@ func runApp(c *model.CommandConfig) (err error) {
}
app.Port = revel_path.HTTPPort
var paths []byte
if len(app.PackagePathMap)>0 {
if len(app.PackagePathMap) > 0 {
paths, _ = json.Marshal(app.PackagePathMap)
}
runMode := fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v,"packagePathMap":%s}`, app.Paths.RunMode, c.Verbose, string(paths))

View File

@@ -55,7 +55,7 @@ func init() {
// Called to update the config command with from the older stype
func updateTestConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.TEST
if len(args)==0 && c.Test.ImportPath!="" {
if len(args) == 0 && c.Test.ImportPath != "" {
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.
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 {
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: ")
}
var paths []byte
if len(app.PackagePathMap)>0 {
if len(app.PackagePathMap) > 0 {
paths, _ = json.Marshal(app.PackagePathMap)
}
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
}
cmd := app.Cmd(runMode)
cmd.Dir=c.AppPath
cmd.Dir = c.AppPath
cmd.Stderr = io.MultiWriter(cmd.Stderr, file)
cmd.Stdout = io.MultiWriter(cmd.Stderr, file)

View File

@@ -74,10 +74,10 @@ func (v *VersionCommand) RunWith(c *model.CommandConfig) (err error) {
versionInfo := ""
for x := 0; x < 2 && needsUpdates; x++ {
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.Stdout = os.Stdout
if e := cmd.Start(); e != nil {
@@ -127,7 +127,7 @@ func (v *VersionCommand) doRepoCheck(updateLibs bool) (versionInfo string, needs
// Checks for updates if needed
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)
if err := v.Command.PackageResolver(repo); err != nil {
utils.Logger.Error("Unable to update repo", "repo", repo, "error", err)
@@ -234,9 +234,9 @@ func (v *VersionCommand) updateLocalVersions() {
v.cmdVersion.BuildDate = cmd.BuildDate
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 {
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
}
utils.Logger.Info("Fullpath to revel modules", "dir", pathMap[model.RevelImportPath])

View File

@@ -95,7 +95,7 @@ func NewCompileError(importPath, errorLink string, error error) *SourceError {
fileStr, err := ReadLines(absFilename)
if err != nil {
compileError.MetaError = absFilename + ": " + err.Error()
Logger.Info("Unable to readlines "+compileError.MetaError, "error", err)
Logger.Info("Unable to readlines " + compileError.MetaError, "error", err)
return compileError
}

View File

@@ -10,25 +10,27 @@ import (
)
// 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
// Dep does not like paths that are not real, convert all paths in go to real paths
realPath := &bytes.Buffer{}
if addGoPath {
for _, p := range filepath.SplitList(build.Default.GOPATH) {
rp,_ := filepath.EvalSymlinks(p)
rp, _ := filepath.EvalSymlinks(p)
if realPath.Len() > 0 {
realPath.WriteString(string(filepath.ListSeparator))
}
realPath.WriteString(rp)
}
// Go 1.8 fails if we do not include the GOROOT
c.Env = []string{"GOPATH=" + realPath.String(), "GOROOT="+ os.Getenv("GOROOT")}
c.Env = []string{"GOPATH=" + realPath.String(), "GOROOT=" + os.Getenv("GOROOT")}
}
// Fetch the rest of the env variables
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
if pair[0]=="GOPATH" || pair[0]=="GOROOT" {
if pair[0] == "GOPATH" || pair[0] == "GOROOT" {
continue
}
c.Env = append(c.Env,e)
c.Env = append(c.Env, e)
}
}

View File

@@ -24,7 +24,7 @@ type (
}
)
// Return a new error object
func NewError(source, title,path,description string) *SourceError {
func NewError(source, title, path, description string) *SourceError {
return &SourceError{
SourceType:source,
Title:title,
@@ -82,7 +82,7 @@ func (e *SourceError) ContextSource() []SourceLine {
end = len(e.SourceLines)
}
lines := make([]SourceLine, end-start)
lines := make([]SourceLine, end - start)
for i, src := range e.SourceLines[start:end] {
fileLine := start + i + 1
lines[i] = SourceLine{src, fileLine, fileLine == e.Line}

View File

@@ -109,7 +109,7 @@ func GenerateTemplate(filename, templateSource string, args map[string]interface
func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
tmpl, err := template.ParseFiles(srcPath)
if err != nil {
return NewBuildIfError(err, "Failed to parse template "+srcPath)
return NewBuildIfError(err, "Failed to parse template " + srcPath)
}
f, err := os.Create(destPath)
@@ -119,12 +119,12 @@ func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
err = tmpl.Execute(f, data)
if err != nil {
return NewBuildIfError(err, "Failed to Render template "+srcPath)
return NewBuildIfError(err, "Failed to Render template " + srcPath)
}
err = f.Close()
if err != nil {
return NewBuildIfError(err, "Failed to close file stream "+destPath)
return NewBuildIfError(err, "Failed to close file stream " + destPath)
}
return
}
@@ -133,12 +133,12 @@ func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
func RenderTemplateToStream(output io.Writer, srcPath []string, data interface{}) (err error) {
tmpl, err := template.ParseFiles(srcPath...)
if err != nil {
return NewBuildIfError(err, "Failed to parse template "+srcPath[0])
return NewBuildIfError(err, "Failed to parse template " + srcPath[0])
}
err = tmpl.Execute(output, data)
if err != nil {
return NewBuildIfError(err, "Failed to render template "+srcPath[0])
return NewBuildIfError(err, "Failed to render template " + srcPath[0])
}
return
}
@@ -181,7 +181,7 @@ func CopyDir(destDir, srcDir string, data map[string]interface{}) error {
if info.IsDir() {
err := os.MkdirAll(filepath.Join(destDir, relSrcPath), 0777)
if !os.IsExist(err) {
return NewBuildIfError(err, "Failed to create directory", "path", destDir+"/"+relSrcPath)
return NewBuildIfError(err, "Failed to create directory", "path", destDir + "/" + relSrcPath)
}
return nil
}
@@ -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 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.
@@ -218,7 +218,7 @@ func fsWalk(fname string, linkName string, walkFn filepath.WalkFunc) error {
path = filepath.Join(linkName, name)
if err == nil && info.Mode()&os.ModeSymlink == os.ModeSymlink {
if err == nil && info.Mode() & os.ModeSymlink == os.ModeSymlink {
var symlinkPath string
symlinkPath, err = filepath.EvalSymlinks(path)
if err != nil {
@@ -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
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 {
for _, item := range missingList {
if err = packageResolver(item); err != nil {
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 {
Logger.Error("Unable to import this package", "package", missing)
}
@@ -338,6 +338,7 @@ func FindSrcPaths(appPath string, packageList []string, packageResolver func(pkg
return
}
var NO_APP_FOUND = errors.New("No app found")
var NO_REVEL_FOUND = errors.New("No revel found")
@@ -352,19 +353,18 @@ func findSrcPaths(appPath string, packagesList []string) (sourcePathsmap map[str
sourcePathsmap = map[string]string{}
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 {
found := false
log:= Logger.New("seeking",packageName)
log := Logger.New("seeking", packageName)
for _, pck := range pkgs {
log.Info("Found package","package",pck.ID)
log.Info("Found package", "package", pck.ID)
if pck.ID == packageName {
if pck.Errors!=nil && len(pck.Errors)>0 {
log.Info("Error ", "count", len(pck.Errors), "App Import Path", pck.ID,"errors",pck.Errors)
if pck.Errors != nil && len(pck.Errors) > 0 {
log.Info("Error ", "count", len(pck.Errors), "App Import Path", pck.ID, "errors", pck.Errors)
}
//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])
found = true
}
@@ -375,7 +375,7 @@ func findSrcPaths(appPath string, packagesList []string) (sourcePathsmap map[str
} else {
err = NO_APP_FOUND
}
missingList = append(missingList,packageName)
missingList = append(missingList, packageName)
}
}
return