From 86736d6e4389243875ecb03a33bb645d80633aa1 Mon Sep 17 00:00:00 2001 From: "notzippy@gmail.com" Date: Sun, 26 Apr 2020 22:24:00 -0700 Subject: [PATCH] Updated formating Ran through testing individually for vendored Revel applications --- .codebeatsettings | 8 +-- harness/app.go | 20 +++---- harness/build.go | 72 +++++++++++++------------ logger/revel_logger.go | 6 +-- model/command/new.go | 3 ++ model/command_config.go | 60 ++++++++------------- model/source_info.go | 18 +++---- model/version.go | 16 +++--- parser2/source_info_processor.go | 39 +++++++------- parser2/source_processor.go | 10 ++-- revel/build.go | 10 ++-- revel/clean.go | 2 +- revel/new.go | 48 +++++++++-------- revel/new_test.go | 90 +++++++------------------------- revel/revel.go | 14 ++--- revel/run.go | 6 +-- revel/test.go | 10 ++-- revel/version.go | 22 ++++---- utils/build_error.go | 10 ++-- utils/command.go | 22 ++++---- utils/error.go | 4 +- utils/file.go | 40 +++++++------- 22 files changed, 239 insertions(+), 291 deletions(-) diff --git a/.codebeatsettings b/.codebeatsettings index a99f39e..b8c65b2 100644 --- a/.codebeatsettings +++ b/.codebeatsettings @@ -1,13 +1,13 @@ { "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], "LOC": [100, 175, 250, 320], "TOTAL_LOC": [300, 400, 500, 600] } -} \ No newline at end of file +} diff --git a/harness/app.go b/harness/app.go index 3b5475a..8fa1105 100644 --- a/harness/app.go +++ b/harness/app.go @@ -21,11 +21,11 @@ import ( // App contains the configuration for running a Revel app. (Not for the app itself) // Its only purpose is constructing the command to execute. type App struct { - BinaryPath string // Path to the app executable - Port int // Port to pass as a command line argument. - cmd AppCmd // The last cmd returned. + BinaryPath string // Path to the app executable + Port int // Port to pass as a command line argument. + cmd AppCmd // The last cmd returned. PackagePathMap map[string]string // Package to directory path map - Paths *model.RevelContainer + Paths *model.RevelContainer } // 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{}} 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,9 +73,9 @@ func (cmd AppCmd) Start(c *model.CommandConfig) error { select { case exitState := <-cmd.waitChan(): fmt.Println("Startup failure view previous messages, \n Proxy is listening :", c.Run.Port) - err := utils.NewError("","Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState,"") - // TODO pretiffy command line output - // err.MetaError = listeningWriter.getLastOutput() + err := utils.NewError("", "Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState, "") + // TODO pretiffy command line output + // err.MetaError = listeningWriter.getLastOutput() return err case <-time.After(60 * time.Second): @@ -150,7 +150,7 @@ func (cmd AppCmd) Kill() { case <-ch: return case <-time.After(60 * time.Second): - // Kill the process + // Kill the process utils.Logger.Error( "Revel app failed to exit in 60 seconds - killing.", "processid", cmd.Process.Pid, @@ -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) diff --git a/harness/build.go b/harness/build.go index 729fd15..c92dde0 100644 --- a/harness/build.go +++ b/harness/build.go @@ -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 } } - // This is Go main path - gopath := c.GoPath - for _, o := range paths.ModulePathMap { - gopath += string(filepath.ListSeparator) + o.Path - } + // 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...) - buildCmd.Env = append(os.Environ(), - "GOPATH="+gopath, - ) - utils.CmdInit(buildCmd, c.AppPath) - utils.Logger.Info("Exec:", "args", buildCmd.Args,"working dir", buildCmd.Dir) + if !c.Vendored { + // This is Go main path + gopath := c.GoPath + for _, o := range paths.ModulePathMap { + 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() // 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,12 +423,13 @@ func newCompileError(paths *model.RevelContainer, output []byte) *utils.SourceEr return newPath } + // Read the source for the offending file. var ( - relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go" - absFilename = findInPaths(relFilename) - line, _ = strconv.Atoi(string(errorMatch[2])) - description = string(errorMatch[4]) + relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go" + absFilename = findInPaths(relFilename) + line, _ = strconv.Atoi(string(errorMatch[2])) + description = string(errorMatch[4]) compileError = &utils.SourceError{ SourceType: "Go code", Title: "Go Compilation Error", @@ -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 } diff --git a/logger/revel_logger.go b/logger/revel_logger.go index 3010d49..0097421 100644 --- a/logger/revel_logger.go +++ b/logger/revel_logger.go @@ -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" } diff --git a/model/command/new.go b/model/command/new.go index 25f3de2..66d88fb 100644 --- a/model/command/new.go +++ b/model/command/new.go @@ -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 } ) \ No newline at end of file diff --git a/model/command_config.go b/model/command_config.go index db248f3..db4ebc9 100644 --- a/model/command_config.go +++ b/model/command_config.go @@ -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,24 +214,29 @@ func (c *CommandConfig) initAppFolder() (err error) { workingDir, _ := os.Getwd() goPathList := filepath.SplitList(c.GoPath) bestpath := "" - for _, path := range goPathList { - if c.Index == NEW { - // If the GOPATH is part of the working dir this is the most likely target - if strings.HasPrefix(workingDir, path) { - bestpath = path - } - } else { - if utils.Exists(filepath.Join(path, "src", c.ImportPath)) { - c.SrcRoot = path - break + 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 + if strings.HasPrefix(workingDir, path) { + bestpath = path + } + } else { + if utils.Exists(filepath.Join(path, "src", c.ImportPath)) { + 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) - 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 len(c.SrcRoot) == 0 { @@ -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 } } diff --git a/model/source_info.go b/model/source_info.go index 88ed26f..836f004 100644 --- a/model/source_info.go +++ b/model/source_info.go @@ -12,14 +12,14 @@ import ( type SourceInfo struct { // StructSpecs lists type info for all structs found under the code paths. // 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: // 1. The fully-qualified function name, // 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. // e.g. the line returned from runtime.Caller() // 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. // Revel notices files with an init() function and imports that package. InitImportPaths []string @@ -28,9 +28,9 @@ type SourceInfo struct { // app/controllers/... that embed (directly or indirectly) revel.Controller controllerSpecs []*TypeInfo // 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 map[string]string + PackageMap map[string]string } // 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", "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 } diff --git a/model/version.go b/model/version.go index bc52654..6016285 100644 --- a/model/version.go +++ b/model/version.go @@ -8,20 +8,20 @@ import ( ) type Version struct { - Prefix string - Major int - Minor int - Maintenance int - Suffix string - BuildDate string + Prefix string + Major int + Minor int + Maintenance int + Suffix string + BuildDate string MinGoVersion string } // The compatibility list var frameworkCompatibleRangeList = [][]string{ {"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 - {"1.0.0", "1.1.0"}, // Compatible with Framework V 1.0 - 1.1 + {"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 } // Parses a version like v1.2.3a or 1.2 diff --git a/parser2/source_info_processor.go b/parser2/source_info_processor.go index 6d8a1c0..e0e4141 100644 --- a/parser2/source_info_processor.go +++ b/parser2/source_info_processor.go @@ -15,23 +15,23 @@ 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{}, } var ( - isController = strings.HasSuffix(p.PkgPath, "/controllers") || - strings.Contains(p.PkgPath, "/controllers/") - isTest = strings.HasSuffix(p.PkgPath, "/tests") || - strings.Contains(p.PkgPath, "/tests/") + isController = strings.HasSuffix(p.PkgPath, "/controllers") || + strings.Contains(p.PkgPath, "/controllers/") + isTest = strings.HasSuffix(p.PkgPath, "/tests") || + 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) { diff --git a/parser2/source_processor.go b/parser2/source_processor.go index 2811da1..d7499ee 100644 --- a/parser2/source_processor.go +++ b/parser2/source_processor.go @@ -18,7 +18,7 @@ type ( log logger.MultiLogger packageList []*packages.Package importMap map[string]string - packageMap map[string]string + packageMap map[string]string sourceInfoProcessor *SourceInfoProcessor sourceInfo *model.SourceInfo } @@ -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/...") } diff --git a/revel/build.go b/revel/build.go index 3bba537..9e43f69 100644 --- a/revel/build.go +++ b/revel/build.go @@ -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 { diff --git a/revel/clean.go b/revel/clean.go index 285ea93..ebbae09 100644 --- a/revel/clean.go +++ b/revel/clean.go @@ -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 { diff --git a/revel/new.go b/revel/new.go index ae8941f..147d08a 100644 --- a/revel/new.go +++ b/revel/new.go @@ -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 } - // At this point the versions can be set - c.SetVersions() + // 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 { diff --git a/revel/new_test.go b/revel/new_test.go index 31aa2b4..f0cb757 100644 --- a/revel/new_test.go +++ b/revel/new_test.go @@ -3,95 +3,42 @@ 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" ) // test the commands func TestNew(t *testing.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) { a := assert.New(t) - c := newApp("onlyone/v/a", model.NEW, precall, a) - c.New.DepVendored = true + c := newApp("new-test", model.NEW, nil, a) 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) - c := newApp("onlyone/v/a", model.TEST, nil, a) - a.Nil(main.Commands[model.TEST].RunWith(c), "Test failed") + c := newApp("new/test/a", model.NEW, nil, a) + 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) - 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) + 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("Package", func(t *testing.T) { + t.Run("Skeleton-Git", 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")) + 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 { @@ -99,3 +46,4 @@ func TestNewVendor(t *testing.T) { } } } + diff --git a/revel/revel.go b/revel/revel.go index c783e4e..2c32df5 100644 --- a/revel/revel.go +++ b/revel/revel.go @@ -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) } } diff --git a/revel/run.go b/revel/run.go index 85c9d3f..c996ae2 100644 --- a/revel/run.go +++ b/revel/run.go @@ -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)) diff --git a/revel/test.go b/revel/test.go index abeb35b..a82fb6b 100644 --- a/revel/test.go +++ b/revel/test.go @@ -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) @@ -234,7 +234,7 @@ func filterTestSuites(suites *[]tests.TestSuiteDesc, suiteArgument string) *[]te // in case it hasn't finished starting up yet. func getTestsList(baseURL string) (*[]tests.TestSuiteDesc, error) { var ( - err error + err error resp *http.Response testSuites []tests.TestSuiteDesc ) diff --git a/revel/version.go b/revel/version.go index 3de97fb..5dc6acf 100644 --- a/revel/version.go +++ b/revel/version.go @@ -29,10 +29,10 @@ import ( type ( // The version container VersionCommand struct { - Command *model.CommandConfig // The command - revelVersion *model.Version // The Revel framework version - modulesVersion *model.Version // The Revel modules version - cmdVersion *model.Version // The tool version + Command *model.CommandConfig // The command + revelVersion *model.Version // The Revel framework version + modulesVersion *model.Version // The Revel modules version + cmdVersion *model.Version // The tool version } ) @@ -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 { @@ -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 shouldUpdate := updateLibs && 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 if shouldUpdate { v.doUpdate(title, repo, localVersion, versonFromRepo) @@ -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) @@ -228,15 +228,15 @@ func (v *VersionCommand) versionFromBytes(sourceStream []byte) (version *model.V } // Fetch the local version of revel from the file system -func (v *VersionCommand) updateLocalVersions() { +func (v *VersionCommand) updateLocalVersions() { v.cmdVersion = &model.Version{} v.cmdVersion.ParseVersion(cmd.Version) 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]) diff --git a/utils/build_error.go b/utils/build_error.go index 8655a96..faa8614 100644 --- a/utils/build_error.go +++ b/utils/build_error.go @@ -73,10 +73,10 @@ func NewCompileError(importPath, errorLink string, error error) *SourceError { // Read the source for the offending file. var ( - relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go" - absFilename = relFilename - line, _ = strconv.Atoi(string(errorMatch[2])) - description = string(errorMatch[4]) + relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go" + absFilename = relFilename + line, _ = strconv.Atoi(string(errorMatch[2])) + description = string(errorMatch[4]) compileError = &SourceError{ SourceType: "Go code", Title: "Go Compilation Error", @@ -95,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 } diff --git a/utils/command.go b/utils/command.go index 4a36592..e00b4e1 100644 --- a/utils/command.go +++ b/utils/command.go @@ -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{} - for _, p := range filepath.SplitList(build.Default.GOPATH) { - rp,_ := filepath.EvalSymlinks(p) - if realPath.Len() > 0 { - realPath.WriteString(string(filepath.ListSeparator)) + if addGoPath { + for _, p := range filepath.SplitList(build.Default.GOPATH) { + rp, _ := filepath.EvalSymlinks(p) + 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 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) } } \ No newline at end of file diff --git a/utils/error.go b/utils/error.go index 1146d72..93143d8 100644 --- a/utils/error.go +++ b/utils/error.go @@ -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} diff --git a/utils/file.go b/utils/file.go index d661beb..da8a177 100644 --- a/utils/file.go +++ b/utils/file.go @@ -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") @@ -351,20 +352,19 @@ 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) + pkgs, err := packages.Load(config, packagesList...) + 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