1
0
mirror of https://github.com/beego/bee.git synced 2024-12-23 16:40:50 +00:00
bee/cmd/commands/beefix/fix.go

233 lines
8.7 KiB
Go
Raw Normal View History

package beefix
2016-01-06 03:55:56 +00:00
2016-01-07 17:20:12 +00:00
import (
"fmt"
2016-01-13 08:39:56 +00:00
"go/parser"
"go/token"
2016-01-07 17:20:12 +00:00
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/beego/bee/cmd/commands"
"github.com/beego/bee/cmd/commands/version"
beeLogger "github.com/beego/bee/logger"
"github.com/beego/bee/logger/colors"
2016-01-07 17:20:12 +00:00
)
var CmdFix = &commands.Command{
2016-01-06 03:55:56 +00:00
UsageLine: "fix",
Short: "Fixes your application by making it compatible with newer versions of Beego",
Long: `As of {{"Beego 1.6"|bold}}, there are some backward compatibility issues.
2016-01-06 03:55:56 +00:00
The command 'fix' will try to solve those issues by upgrading your code base
to be compatible with Beego version 1.6+.
2016-01-06 03:55:56 +00:00
`,
}
func init() {
CmdFix.Run = runFix
CmdFix.PreRun = func(cmd *commands.Command, args []string) { version.ShowShortVersionBanner() }
commands.AvailableCommands = append(commands.AvailableCommands, CmdFix)
2016-01-06 03:55:56 +00:00
}
func runFix(cmd *commands.Command, args []string) int {
output := cmd.Out()
beeLogger.Log.Info("Upgrading the application...")
2016-01-07 17:20:12 +00:00
dir, err := os.Getwd()
if err != nil {
beeLogger.Log.Fatalf("Error while getting the current working directory: %s", err)
2016-01-07 17:20:12 +00:00
}
2016-01-07 17:20:12 +00:00
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
2016-01-08 03:04:05 +00:00
if strings.HasPrefix(info.Name(), ".") {
return filepath.SkipDir
}
2016-01-07 17:20:12 +00:00
return nil
}
2016-01-08 03:04:05 +00:00
if err != nil {
return err
}
2016-01-18 03:33:52 +00:00
if strings.HasSuffix(info.Name(), ".exe") {
return nil
}
2016-01-07 17:20:12 +00:00
err = fixFile(path)
fmt.Fprintf(output, colors.GreenBold("\tfix\t")+"%s\n", path)
2016-01-07 17:20:12 +00:00
if err != nil {
beeLogger.Log.Errorf("Could not fix file: %s", err)
2016-01-07 17:20:12 +00:00
}
return err
})
beeLogger.Log.Success("Upgrade Done!")
2016-01-06 03:55:56 +00:00
return 0
}
2016-01-07 17:20:12 +00:00
var rules = []string{
"beego.AppName", "beego.BConfig.AppName",
"beego.RunMode", "beego.BConfig.RunMode",
"beego.RecoverPanic", "beego.BConfig.RecoverPanic",
"beego.RouterCaseSensitive", "beego.BConfig.RouterCaseSensitive",
"beego.BeegoServerName", "beego.BConfig.ServerName",
"beego.EnableGzip", "beego.BConfig.EnableGzip",
"beego.ErrorsShow", "beego.BConfig.EnableErrorsShow",
"beego.CopyRequestBody", "beego.BConfig.CopyRequestBody",
"beego.MaxMemory", "beego.BConfig.MaxMemory",
"beego.Graceful", "beego.BConfig.Listen.Graceful",
"beego.HttpAddr", "beego.BConfig.Listen.HTTPAddr",
"beego.HttpPort", "beego.BConfig.Listen.HTTPPort",
"beego.ListenTCP4", "beego.BConfig.Listen.ListenTCP4",
2016-02-05 00:32:45 +00:00
"beego.EnableHttpListen", "beego.BConfig.Listen.EnableHTTP",
"beego.EnableHttpTLS", "beego.BConfig.Listen.EnableHTTPS",
2016-01-07 17:20:12 +00:00
"beego.HttpsAddr", "beego.BConfig.Listen.HTTPSAddr",
"beego.HttpsPort", "beego.BConfig.Listen.HTTPSPort",
"beego.HttpCertFile", "beego.BConfig.Listen.HTTPSCertFile",
"beego.HttpKeyFile", "beego.BConfig.Listen.HTTPSKeyFile",
"beego.EnableAdmin", "beego.BConfig.Listen.EnableAdmin",
2016-01-07 17:20:12 +00:00
"beego.AdminHttpAddr", "beego.BConfig.Listen.AdminAddr",
"beego.AdminHttpPort", "beego.BConfig.Listen.AdminPort",
"beego.UseFcgi", "beego.BConfig.Listen.EnableFcgi",
"beego.HttpServerTimeOut", "beego.BConfig.Listen.ServerTimeOut",
"beego.AutoRender", "beego.BConfig.WebConfig.AutoRender",
"beego.ViewsPath", "beego.BConfig.WebConfig.ViewsPath",
"beego.StaticDir", "beego.BConfig.WebConfig.StaticDir",
"beego.StaticExtensionsToGzip", "beego.BConfig.WebConfig.StaticExtensionsToGzip",
2016-01-07 17:20:12 +00:00
"beego.DirectoryIndex", "beego.BConfig.WebConfig.DirectoryIndex",
"beego.FlashName", "beego.BConfig.WebConfig.FlashName",
"beego.FlashSeperator", "beego.BConfig.WebConfig.FlashSeparator",
2016-01-07 17:20:12 +00:00
"beego.EnableDocs", "beego.BConfig.WebConfig.EnableDocs",
2016-01-15 06:45:56 +00:00
"beego.XSRFKEY", "beego.BConfig.WebConfig.XSRFKey",
2016-01-07 17:20:12 +00:00
"beego.EnableXSRF", "beego.BConfig.WebConfig.EnableXSRF",
"beego.XSRFExpire", "beego.BConfig.WebConfig.XSRFExpire",
"beego.TemplateLeft", "beego.BConfig.WebConfig.TemplateLeft",
"beego.TemplateRight", "beego.BConfig.WebConfig.TemplateRight",
"beego.SessionOn", "beego.BConfig.WebConfig.Session.SessionOn",
"beego.SessionProvider", "beego.BConfig.WebConfig.Session.SessionProvider",
"beego.SessionName", "beego.BConfig.WebConfig.Session.SessionName",
"beego.SessionGCMaxLifetime", "beego.BConfig.WebConfig.Session.SessionGCMaxLifetime",
"beego.SessionSavePath", "beego.BConfig.WebConfig.Session.SessionProviderConfig",
"beego.SessionCookieLifeTime", "beego.BConfig.WebConfig.Session.SessionCookieLifeTime",
"beego.SessionAutoSetCookie", "beego.BConfig.WebConfig.Session.SessionAutoSetCookie",
"beego.SessionDomain", "beego.BConfig.WebConfig.Session.SessionDomain",
2016-01-08 02:50:52 +00:00
"Ctx.Input.CopyBody(", "Ctx.Input.CopyBody(beego.BConfig.MaxMemory",
2016-01-07 17:20:12 +00:00
".UrlFor(", ".URLFor(",
".ServeJson(", ".ServeJSON(",
".ServeXml(", ".ServeXML(",
2016-01-25 13:05:08 +00:00
".ServeJsonp(", ".ServeJSONP(",
2016-01-07 17:20:12 +00:00
".XsrfToken(", ".XSRFToken(",
".CheckXsrfCookie(", ".CheckXSRFCookie(",
".XsrfFormHtml(", ".XSRFFormHTML(",
"beego.UrlFor(", "beego.URLFor(",
"beego.GlobalDocApi", "beego.GlobalDocAPI",
"beego.Errorhandler", "beego.ErrorHandler",
2016-01-11 06:30:42 +00:00
"Output.Jsonp(", "Output.JSONP(",
"Output.Json(", "Output.JSON(",
"Output.Xml(", "Output.XML(",
2016-01-07 17:20:12 +00:00
"Input.Uri()", "Input.URI()",
"Input.Url()", "Input.URL()",
"Input.AcceptsHtml()", "Input.AcceptsHTML()",
"Input.AcceptsXml()", "Input.AcceptsXML()",
"Input.AcceptsJson()", "Input.AcceptsJSON()",
"Ctx.XsrfToken()", "Ctx.XSRFToken()",
"Ctx.CheckXsrfCookie()", "Ctx.CheckXSRFCookie()",
"session.SessionStore", "session.Store",
".TplNames", ".TplName",
2016-01-08 02:50:52 +00:00
"swagger.ApiRef", "swagger.APIRef",
"swagger.ApiDeclaration", "swagger.APIDeclaration",
"swagger.Api", "swagger.API",
"swagger.ApiRef", "swagger.APIRef",
2016-01-15 06:45:56 +00:00
"swagger.Infomation", "swagger.Information",
2016-01-08 02:50:52 +00:00
"toolbox.UrlMap", "toolbox.URLMap",
2016-01-08 03:47:16 +00:00
"logs.LoggerInterface", "logs.Logger",
2016-01-08 15:16:17 +00:00
"Input.Request", "Input.Context.Request",
"Input.Params)", "Input.Params())",
2016-01-11 06:30:42 +00:00
"httplib.BeegoHttpSettings", "httplib.BeegoHTTPSettings",
"httplib.BeegoHttpRequest", "httplib.BeegoHTTPRequest",
".TlsClientConfig", ".TLSClientConfig",
".JsonBody", ".JSONBody",
".ToJson", ".ToJSON",
".ToXml", ".ToXML",
"beego.Html2str", "beego.HTML2str",
"beego.AssetsCss", "beego.AssetsCSS",
"orm.DR_Sqlite", "orm.DRSqlite",
"orm.DR_Postgres", "orm.DRPostgres",
"orm.DR_MySQL", "orm.DRMySQL",
"orm.DR_Oracle", "orm.DROracle",
"orm.Col_Add", "orm.ColAdd",
"orm.Col_Minus", "orm.ColMinus",
"orm.Col_Multiply", "orm.ColMultiply",
"orm.Col_Except", "orm.ColExcept",
"GenerateOperatorSql", "GenerateOperatorSQL",
"OperatorSql", "OperatorSQL",
"orm.Debug_Queries", "orm.DebugQueries",
"orm.COMMA_SPACE", "orm.CommaSpace",
2016-01-18 03:33:52 +00:00
".SendOut()", ".DoRequest()",
2016-01-25 13:05:08 +00:00
"validation.ValidationError", "validation.Error",
2016-01-07 17:20:12 +00:00
}
func fixFile(file string) error {
rp := strings.NewReplacer(rules...)
content, err := ioutil.ReadFile(file)
if err != nil {
return err
}
fixed := rp.Replace(string(content))
2016-01-08 15:16:17 +00:00
// Forword the RequestBody from the replace
2016-01-08 15:16:17 +00:00
// "Input.Request", "Input.Context.Request",
fixed = strings.Replace(fixed, "Input.Context.RequestBody", "Input.RequestBody", -1)
// Regexp replace
2016-01-08 03:10:18 +00:00
pareg := regexp.MustCompile(`(Input.Params\[")(.*)("])`)
fixed = pareg.ReplaceAllString(fixed, "Input.Param(\"$2\")")
2016-01-08 15:16:17 +00:00
pareg = regexp.MustCompile(`(Input.Data\[\")(.*)(\"\])(\s)(=)(\s)(.*)`)
fixed = pareg.ReplaceAllString(fixed, "Input.SetData(\"$2\", $7)")
2016-01-11 07:21:54 +00:00
pareg = regexp.MustCompile(`(Input.Data\[\")(.*)(\"\])`)
fixed = pareg.ReplaceAllString(fixed, "Input.Data(\"$2\")")
// Fix the cache object Put method
2016-01-13 08:39:56 +00:00
pareg = regexp.MustCompile(`(\.Put\(\")(.*)(\",)(\s)(.*)(,\s*)([^\*.]*)(\))`)
if pareg.MatchString(fixed) && strings.HasSuffix(file, ".go") {
fixed = pareg.ReplaceAllString(fixed, ".Put(\"$2\", $5, $7*time.Second)")
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, file, nil, parser.ImportsOnly)
if err != nil {
panic(err)
}
// Print the imports from the file's AST.
hasTimepkg := false
for _, s := range f.Imports {
if s.Path.Value == `"time"` {
hasTimepkg = true
break
}
}
if !hasTimepkg {
fixed = strings.Replace(fixed, "import (", "import (\n\t\"time\"", 1)
}
}
// Replace the v.Apis in docs.go
2016-01-08 03:40:49 +00:00
if strings.Contains(file, "docs.go") {
2016-01-08 03:44:38 +00:00
fixed = strings.Replace(fixed, "v.Apis", "v.APIs", -1)
2016-01-08 03:35:23 +00:00
}
// Replace the config file
2016-01-12 13:57:52 +00:00
if strings.HasSuffix(file, ".conf") {
fixed = strings.Replace(fixed, "HttpCertFile", "HTTPSCertFile", -1)
fixed = strings.Replace(fixed, "HttpKeyFile", "HTTPSKeyFile", -1)
fixed = strings.Replace(fixed, "EnableHttpListen", "HTTPEnable", -1)
fixed = strings.Replace(fixed, "EnableHttpTLS", "EnableHTTPS", -1)
fixed = strings.Replace(fixed, "EnableHttpTLS", "EnableHTTPS", -1)
fixed = strings.Replace(fixed, "BeegoServerName", "ServerName", -1)
fixed = strings.Replace(fixed, "AdminHttpAddr", "AdminAddr", -1)
fixed = strings.Replace(fixed, "AdminHttpPort", "AdminPort", -1)
fixed = strings.Replace(fixed, "HttpServerTimeOut", "ServerTimeOut", -1)
}
2016-01-07 17:20:12 +00:00
err = os.Truncate(file, 0)
if err != nil {
return err
}
return ioutil.WriteFile(file, []byte(fixed), 0666)
}