Lint fixes

This commit is contained in:
Paul Tötterman
2020-10-19 13:40:52 +03:00
parent 3cec19ee62
commit 3d924a016b
65 changed files with 884 additions and 1083 deletions

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,23 +1,24 @@
package main_test
import (
"github.com/revel/cmd/logger"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"github.com/stretchr/testify/assert"
"fmt"
"go/build"
"os"
"os/exec"
"path/filepath"
"fmt"
"github.com/revel/cmd/logger"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"github.com/stretchr/testify/assert"
)
// Test that the event handler can be attached and it dispatches the event received
func setup(suffix string, a *assert.Assertions) (string) {
// Test that the event handler can be attached and it dispatches the event received.
func setup(suffix string, a *assert.Assertions) string {
temp := os.TempDir()
wd, _ := os.Getwd()
utils.InitLogger(wd, logger.LvlInfo)
gopath := filepath.Join(temp, "revel-test",suffix)
gopath := filepath.Join(temp, "revel-test", suffix)
if utils.Exists(gopath) {
utils.Logger.Info("Removing test path", "path", gopath)
if err := os.RemoveAll(gopath); err != nil {
@@ -38,30 +39,29 @@ func setup(suffix string, a *assert.Assertions) (string) {
defaultBuild := build.Default
defaultBuild.GOPATH = gopath
build.Default = defaultBuild
utils.Logger.Info("Setup stats", "original wd", wd, "new wd", newwd, "gopath",gopath, "gopath exists", utils.DirExists(gopath), "wd exists", utils.DirExists(newwd))
utils.Logger.Info("Setup stats", "original wd", wd, "new wd", newwd, "gopath", gopath, "gopath exists", utils.DirExists(gopath), "wd exists", utils.DirExists(newwd))
return gopath
}
// Create a new app for the name
// Create a new app for the name.
func newApp(name string, command model.COMMAND, precall func(c *model.CommandConfig), a *assert.Assertions) *model.CommandConfig {
c := &model.CommandConfig{Vendored:true}
c := &model.CommandConfig{Vendored: true}
switch command {
case model.NEW:
c.New.ImportPath = name
c.New.Callback=func() error {
c.New.Callback = func() error {
// On callback we will invoke a specific branch of revel so that it works
goModCmd := exec.Command("go", "mod", "tidy")
utils.CmdInit(goModCmd, !c.Vendored, c.AppPath)
getOutput, _ := goModCmd.CombinedOutput()
fmt.Printf("Calling go mod tidy %s",string(getOutput))
fmt.Printf("Calling go mod tidy %s", string(getOutput))
goModCmd = exec.Command("go", "mod", "edit", "-replace=github.com/revel/revel=github.com/revel/revel@develop")
utils.CmdInit(goModCmd, !c.Vendored, c.AppPath)
getOutput, _ = goModCmd.CombinedOutput()
fmt.Printf("Calling go mod edit %v",string(getOutput))
fmt.Printf("Calling go mod edit %v", string(getOutput))
return nil
}
@@ -83,7 +83,7 @@ func newApp(name string, command model.COMMAND, precall func(c *model.CommandCon
if precall != nil {
precall(c)
}
if c.UpdateImportPath()!=nil {
if c.UpdateImportPath() != nil {
a.Fail("Unable to update import path")
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,6 +6,7 @@
package main
import (
"bytes"
"flag"
"fmt"
"math/rand"
@@ -14,23 +15,18 @@ import (
"strings"
"time"
"github.com/jessevdk/go-flags"
"github.com/agtorre/gocolorize"
"github.com/jessevdk/go-flags"
"github.com/revel/cmd/logger"
"github.com/revel/cmd/model"
"github.com/revel/cmd/utils"
"bytes"
)
const (
// RevelCmdImportPath Revel framework cmd tool import path
RevelCmdImportPath = "github.com/revel/cmd"
// RevelCmdImportPath Revel framework cmd tool import path
// RevelCmdImportPath Revel framework cmd tool import path.
RevelSkeletonsImportPath = "github.com/revel/skeletons"
// DefaultRunMode for revel's application
// DefaultRunMode for revel's application.
DefaultRunMode = "dev"
)
@@ -41,7 +37,7 @@ type Command struct {
UsageLine, Short, Long string
}
// Name returns command name from usage line
// Name returns command name from usage line.
func (cmd *Command) Name() string {
name := cmd.UsageLine
i := strings.Index(name, " ")
@@ -51,7 +47,7 @@ func (cmd *Command) Name() string {
return name
}
// The commands
// Commands defines the available commands.
var Commands = []*Command{
nil, // Safety net, prevent missing index from running
cmdNew,
@@ -71,14 +67,14 @@ func main() {
wd, _ := os.Getwd()
utils.InitLogger(wd, logger.LvlError)
parser := flags.NewParser(c, flags.HelpFlag | flags.PassDoubleDash)
parser := flags.NewParser(c, flags.HelpFlag|flags.PassDoubleDash)
if len(os.Args) < 2 {
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)
}
@@ -109,7 +105,7 @@ func main() {
}
}
// Parse the arguments passed into the model.CommandConfig
// Parse the arguments passed into the model.CommandConfig.
func ParseArgs(c *model.CommandConfig, parser *flags.Parser, args []string) (err error) {
var extraArgs []string
if ini := flag.String("ini", "none", ""); *ini != "none" {
@@ -119,30 +115,30 @@ func ParseArgs(c *model.CommandConfig, parser *flags.Parser, args []string) (err
} else {
if extraArgs, err = parser.ParseArgs(args); err != nil {
return
} else {
switch parser.Active.Name {
case "new":
c.Index = model.NEW
case "run":
c.Index = model.RUN
case "build":
c.Index = model.BUILD
case "package":
c.Index = model.PACKAGE
case "clean":
c.Index = model.CLEAN
case "test":
c.Index = model.TEST
case "version":
c.Index = model.VERSION
}
}
switch parser.Active.Name {
case "new":
c.Index = model.NEW
case "run":
c.Index = model.RUN
case "build":
c.Index = model.BUILD
case "package":
c.Index = model.PACKAGE
case "clean":
c.Index = model.CLEAN
case "test":
c.Index = model.TEST
case "version":
c.Index = model.VERSION
}
}
if !Commands[c.Index].UpdateConfig(c, extraArgs) {
buffer := &bytes.Buffer{}
parser.WriteHelp(buffer)
err = fmt.Errorf("Invalid command line arguements %v\n%s", extraArgs, buffer.String())
err = fmt.Errorf("invalid command line arguments %v\n%s", extraArgs, buffer.String())
}
return

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,18 +1,19 @@
package main_test
import (
"github.com/revel/cmd/model"
"github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
"os"
"path/filepath"
"testing"
"github.com/revel/cmd/model"
main "github.com/revel/cmd/revel"
"github.com/stretchr/testify/assert"
)
// test the commands
// test the commands.
func TestVersion(t *testing.T) {
a := assert.New(t)
gopath := setup("revel-test-version", a)
gopath := setup("revel-test-version", a)
t.Run("Version", func(t *testing.T) {
a := assert.New(t)
@@ -34,8 +35,8 @@ func TestVersion(t *testing.T) {
a.Nil(main.Commands[model.VERSION].RunWith(c), "Failed to run version-test")
})
if !t.Failed() {
if err := os.RemoveAll(gopath); err != nil && err!=os.ErrNotExist {
a.Fail("Failed to remove test path",err.Error())
if err := os.RemoveAll(gopath); err != nil && err != os.ErrNotExist {
a.Fail("Failed to remove test path", err.Error())
}
}
}