chore: update code format. (#628)

This commit is contained in:
Bo-Yi Wu
2021-04-15 19:49:17 +08:00
committed by GitHub
parent 7e087de6e6
commit afd9ff889e
68 changed files with 390 additions and 414 deletions

View File

@@ -29,7 +29,7 @@ Future {{pathToFuncName .Path}}( {{if ne .Method "get"}}{{with .RequestType}}{{.
{{end}}`
func genApi(dir string, api *spec.ApiSpec) error {
err := os.MkdirAll(dir, 0755)
err := os.MkdirAll(dir, 0o755)
if err != nil {
return err
}
@@ -39,7 +39,7 @@ func genApi(dir string, api *spec.ApiSpec) error {
return err
}
file, err := os.OpenFile(dir+api.Service.Name+".dart", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
file, err := os.OpenFile(dir+api.Service.Name+".dart", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}
@@ -60,7 +60,7 @@ func genApiFile(dir string) error {
if fileExists(path) {
return nil
}
apiFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
apiFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}

View File

@@ -32,7 +32,7 @@ class {{.Name}}{
`
func genData(dir string, api *spec.ApiSpec) error {
err := os.MkdirAll(dir, 0755)
err := os.MkdirAll(dir, 0o755)
if err != nil {
return err
}
@@ -42,7 +42,7 @@ func genData(dir string, api *spec.ApiSpec) error {
return err
}
file, err := os.OpenFile(dir+api.Service.Name+".dart", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
file, err := os.OpenFile(dir+api.Service.Name+".dart", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}
@@ -64,7 +64,7 @@ func genTokens(dir string) error {
return nil
}
tokensFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
tokensFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}

View File

@@ -41,20 +41,20 @@ Future<Tokens> getTokens() async {
`
func genVars(dir string) error {
err := os.MkdirAll(dir, 0755)
err := os.MkdirAll(dir, 0o755)
if err != nil {
return err
}
if !fileExists(dir + "vars.dart") {
err = ioutil.WriteFile(dir+"vars.dart", []byte(`const serverHost='demo-crm.xiaoheiban.cn';`), 0644)
err = ioutil.WriteFile(dir+"vars.dart", []byte(`const serverHost='demo-crm.xiaoheiban.cn';`), 0o644)
if err != nil {
return err
}
}
if !fileExists(dir + "kv.dart") {
err = ioutil.WriteFile(dir+"kv.dart", []byte(varTemplate), 0644)
err = ioutil.WriteFile(dir+"kv.dart", []byte(varTemplate), 0o644)
if err != nil {
return err
}

View File

@@ -84,7 +84,7 @@ func buildDoc(route spec.Type) (string, error) {
return "", nil
}
var tps = make([]spec.Type, 0)
tps := make([]spec.Type, 0)
tps = append(tps, route)
if definedType, ok := route.(spec.DefineStruct); ok {
associatedTypes(definedType, &tps)
@@ -98,7 +98,7 @@ func buildDoc(route spec.Type) (string, error) {
}
func associatedTypes(tp spec.DefineStruct, tps *[]spec.Type) {
var hasAdded = false
hasAdded := false
for _, item := range *tps {
if item.Name() == tp.Name() {
hasAdded = true

View File

@@ -107,8 +107,8 @@ func apiFormat(data string) (string, error) {
var builder strings.Builder
s := bufio.NewScanner(strings.NewReader(data))
var tapCount = 0
var newLineCount = 0
tapCount := 0
newLineCount := 0
var preLine string
for s.Scan() {
line := strings.TrimSpace(s.Text())

View File

@@ -35,12 +35,12 @@ func genConfig(dir string, cfg *config.Config, api *spec.ApiSpec) error {
return err
}
var authNames = getAuths(api)
authNames := getAuths(api)
var auths []string
for _, item := range authNames {
auths = append(auths, fmt.Sprintf("%s %s", item, jwtTemplate))
}
var authImportStr = fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL)
authImportStr := fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL)
return genFile(fileGenConfig{
dir: dir,

View File

@@ -31,7 +31,7 @@ func (m *{{.name}})Handle(next http.HandlerFunc) http.HandlerFunc {
`
func genMiddleware(dir string, cfg *config.Config, api *spec.ApiSpec) error {
var middlewares = getMiddleware(api)
middlewares := getMiddleware(api)
for _, item := range middlewares {
middlewareFilename := strings.TrimSuffix(strings.ToLower(item), "middleware") + "_middleware"
filename, err := format.FileNamingFormat(cfg.NamingFormat, middlewareFilename)

View File

@@ -95,11 +95,11 @@ func genRoutes(dir string, cfg *config.Config, api *spec.ApiSpec) error {
var routes string
if len(g.middlewares) > 0 {
gbuilder.WriteString("\n}...,")
var params = g.middlewares
params := g.middlewares
for i := range params {
params[i] = "serverCtx." + params[i]
}
var middlewareStr = strings.Join(params, ", ")
middlewareStr := strings.Join(params, ", ")
routes = fmt.Sprintf("rest.WithMiddlewares(\n[]rest.Middleware{ %s }, \n %s \n),",
middlewareStr, strings.TrimSpace(gbuilder.String()))
} else {
@@ -146,7 +146,7 @@ func genRoutes(dir string, cfg *config.Config, api *spec.ApiSpec) error {
}
func genRouteImports(parentPkg string, api *spec.ApiSpec) string {
var importSet = collection.NewSet()
importSet := collection.NewSet()
importSet.AddStr(fmt.Sprintf("\"%s\"", util.JoinPackages(parentPkg, contextDir)))
for _, group := range api.Service.Groups {
for _, route := range group.Routes {

View File

@@ -39,7 +39,7 @@ func genServiceContext(dir string, cfg *config.Config, api *spec.ApiSpec) error
return err
}
var authNames = getAuths(api)
authNames := getAuths(api)
var auths []string
for _, item := range authNames {
auths = append(auths, fmt.Sprintf("%s config.AuthConfig", item))
@@ -52,7 +52,7 @@ func genServiceContext(dir string, cfg *config.Config, api *spec.ApiSpec) error
var middlewareStr string
var middlewareAssignment string
var middlewares = getMiddleware(api)
middlewares := getMiddleware(api)
for _, item := range middlewares {
middlewareStr += fmt.Sprintf("%s rest.Middleware\n", item)
@@ -61,7 +61,7 @@ func genServiceContext(dir string, cfg *config.Config, api *spec.ApiSpec) error
fmt.Sprintf("middleware.New%s().%s", strings.Title(name), "Handle"))
}
var configImport = "\"" + ctlutil.JoinPackages(parentPkg, configDir) + "\""
configImport := "\"" + ctlutil.JoinPackages(parentPkg, configDir) + "\""
if len(middlewareStr) > 0 {
configImport += "\n\t\"" + ctlutil.JoinPackages(parentPkg, middlewareDir) + "\""
configImport += fmt.Sprintf("\n\t\"%s/rest\"", vars.ProjectOpenSourceURL)

View File

@@ -277,15 +277,15 @@ func (c *componentsContext) buildConstructor() (string, string, error) {
}
func (c *componentsContext) genGetSet(writer io.Writer, indent int) error {
var members = c.members
members := c.members
for _, member := range members {
javaType, err := specTypeToJava(member.Type)
if err != nil {
return nil
}
var property = util.Title(member.Name)
var templateStr = getSetTemplate
property := util.Title(member.Name)
templateStr := getSetTemplate
if javaType == "boolean" {
templateStr = boolTemplate
property = strings.TrimPrefix(property, "Is")

View File

@@ -67,7 +67,7 @@ func createWith(dir string, api *spec.ApiSpec, route spec.Route, packetName stri
}
defer fp.Close()
var hasRequestBody = false
hasRequestBody := false
if route.RequestType != nil {
if defineStruct, ok := route.RequestType.(spec.DefineStruct); ok {
hasRequestBody = len(defineStruct.GetBodyMembers()) > 0 || len(defineStruct.GetFormMembers()) > 0

View File

@@ -61,7 +61,7 @@ func writeIndent(writer io.Writer, indent int) {
}
func indentString(indent int) string {
var result = ""
result := ""
for i := 0; i < indent; i++ {
result += "\t"
}

View File

@@ -98,7 +98,7 @@ object {{with .Info}}{{.Title}}{{end}}{
)
func genBase(dir, pkg string, api *spec.ApiSpec) error {
e := os.MkdirAll(dir, 0755)
e := os.MkdirAll(dir, 0o755)
if e != nil {
return e
}
@@ -108,7 +108,7 @@ func genBase(dir, pkg string, api *spec.ApiSpec) error {
return nil
}
file, e := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
file, e := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
if e != nil {
return e
}
@@ -146,12 +146,12 @@ func genApi(dir, pkg string, api *spec.ApiSpec) error {
api.Info.Title = name
api.Info.Desc = desc
e := os.MkdirAll(dir, 0755)
e := os.MkdirAll(dir, 0o755)
if e != nil {
return e
}
file, e := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
file, e := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644)
if e != nil {
return e
}

View File

@@ -175,7 +175,7 @@ func (p *Parser) valid(mainApi *Api, nestedApi *Api) error {
for _, g := range list {
handler := g.GetHandler()
if handler.IsNotNil() {
var handlerName = handler.Text()
handlerName := handler.Text()
handlerMap[handlerName] = Holder
path := fmt.Sprintf("%s://%s", g.Route.Method.Text(), g.Route.Path.Text())
routeMap[path] = Holder

View File

@@ -289,7 +289,7 @@ func (v *ApiVisitor) getHiddenTokensToLeft(t TokenStream, channel int, containsC
if index > 0 {
allTokens := ct.GetAllTokens()
var flag = false
flag := false
for i := index; i >= 0; i-- {
tk := allTokens[i]
if tk.GetChannel() == antlr.LexerDefaultTokenChannel {

View File

@@ -128,7 +128,6 @@ func (v *ApiVisitor) VisitTypeBlock(ctx *api.TypeBlockContext) interface{} {
var types []TypeExpr
for _, each := range list {
types = append(types, each.Accept(v).(TypeExpr))
}
return types
}
@@ -155,7 +154,6 @@ func (v *ApiVisitor) VisitTypeStruct(ctx *api.TypeStructContext) interface{} {
st.Name = v.newExprWithToken(ctx.GetStructName())
if util.UnExport(ctx.GetStructName().GetText()) {
}
if ctx.GetStructToken() != nil {
structExpr := v.newExprWithToken(ctx.GetStructToken())

View File

@@ -10,8 +10,10 @@ import (
)
// Suppress unused import error
var _ = fmt.Printf
var _ = unicode.IsLetter
var (
_ = fmt.Printf
_ = unicode.IsLetter
)
var serializedLexerAtn = []uint16{
3, 24715, 42794, 33075, 47597, 16764, 15335, 30598, 22884, 2, 25, 266,

File diff suppressed because it is too large Load Diff

View File

@@ -16,28 +16,30 @@ const (
tagRegex = `(?m)\x60[a-z]+:".+"\x60`
)
var holder = struct{}{}
var kind = map[string]struct{}{
"bool": holder,
"int": holder,
"int8": holder,
"int16": holder,
"int32": holder,
"int64": holder,
"uint": holder,
"uint8": holder,
"uint16": holder,
"uint32": holder,
"uint64": holder,
"uintptr": holder,
"float32": holder,
"float64": holder,
"complex64": holder,
"complex128": holder,
"string": holder,
"byte": holder,
"rune": holder,
}
var (
holder = struct{}{}
kind = map[string]struct{}{
"bool": holder,
"int": holder,
"int8": holder,
"int16": holder,
"int32": holder,
"int64": holder,
"uint": holder,
"uint8": holder,
"uint16": holder,
"uint32": holder,
"uint64": holder,
"uintptr": holder,
"float32": holder,
"float64": holder,
"complex64": holder,
"complex128": holder,
"string": holder,
"byte": holder,
"rune": holder,
}
)
func match(p *ApiParserParser, text string) {
v := getCurrentTokenText(p)

View File

@@ -145,7 +145,6 @@ line"`),
},
},
}))
})
t.Run("mismatched", func(t *testing.T) {

View File

@@ -120,7 +120,8 @@ func TestRoute(t *testing.T) {
PointerExpr: ast.NewTextExpr("*Bar"),
Star: ast.NewTextExpr("*"),
Name: ast.NewTextExpr("Bar"),
}},
},
},
},
}))
@@ -224,7 +225,6 @@ func TestAtHandler(t *testing.T) {
_, err = parser.Accept(fn, `@handler "foo"`)
assert.Error(t, err)
})
}
func TestAtDoc(t *testing.T) {

View File

@@ -64,7 +64,7 @@ func (p parser) convert2Spec() error {
}
func (p parser) fillInfo() {
var properties = make(map[string]string, 0)
properties := make(map[string]string, 0)
if p.ast.Info != nil {
p.spec.Info = spec.Info{}
for _, kv := range p.ast.Info.Kvs {
@@ -147,8 +147,8 @@ func (p parser) findDefinedType(name string) (*spec.Type, error) {
}
func (p parser) fieldToMember(field *ast.TypeField) spec.Member {
var name = ""
var tag = ""
name := ""
tag := ""
if !field.IsAnonymous {
name = field.Name.Text()
if field.Tag == nil {
@@ -239,7 +239,7 @@ func (p parser) fillService() error {
route.ResponseType = p.astTypeToSpec(astRoute.Route.Reply.Name)
}
if astRoute.AtDoc != nil {
var properties = make(map[string]string, 0)
properties := make(map[string]string, 0)
for _, kv := range astRoute.AtDoc.Kv {
properties[kv.Key.Text()] = kv.Value.Text()
}
@@ -271,7 +271,7 @@ func (p parser) fillService() error {
func (p parser) fillRouteAtServer(astRoute *ast.ServiceRoute, route *spec.Route) error {
if astRoute.AtServer != nil {
var properties = make(map[string]string, 0)
properties := make(map[string]string, 0)
for _, kv := range astRoute.AtServer.Kv {
properties[kv.Key.Text()] = kv.Value.Text()
}
@@ -295,7 +295,7 @@ func (p parser) fillRouteAtServer(astRoute *ast.ServiceRoute, route *spec.Route)
func (p parser) fillAtServer(item *ast.Service, group *spec.Group) {
if item.AtServer != nil {
var properties = make(map[string]string, 0)
properties := make(map[string]string, 0)
for _, kv := range item.AtServer.Kv {
properties[kv.Key.Text()] = kv.Value.Text()
}

View File

@@ -76,7 +76,7 @@ func WriteIndent(writer io.Writer, indent int) {
// RemoveComment filters comment content
func RemoveComment(line string) string {
var commentIdx = strings.Index(line, "//")
commentIdx := strings.Index(line, "//")
if commentIdx >= 0 {
return strings.TrimSpace(line[:commentIdx])
}

View File

@@ -20,7 +20,7 @@ func TestDo(t *testing.T) {
tempDir := t.TempDir()
typesfile := filepath.Join(tempDir, "types.go")
err = ioutil.WriteFile(typesfile, []byte(testTypes), 0666)
err = ioutil.WriteFile(typesfile, []byte(testTypes), 0o666)
assert.Nil(t, err)
err = Do(&Context{

View File

@@ -68,7 +68,7 @@ func TestBuilderSql(t *testing.T) {
}
func TestBuildSqlDefaultValue(t *testing.T) {
var eq = builder.Eq{}
eq := builder.Eq{}
eq["age"] = 0
eq["user_name"] = ""

View File

@@ -230,7 +230,7 @@ func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, er
return "", err
}
var findCode = make([]string, 0)
findCode := make([]string, 0)
findOneCode, findOneCodeMethod, err := genFindOne(table, withCache)
if err != nil {
return "", err

View File

@@ -15,9 +15,7 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/model/sql/builderx"
)
var (
source = "CREATE TABLE `test_user` (\n `id` bigint NOT NULL AUTO_INCREMENT,\n `mobile` varchar(255) COLLATE utf8mb4_bin NOT NULL,\n `class` bigint NOT NULL,\n `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `mobile_unique` (`mobile`),\n UNIQUE KEY `class_name_unique` (`class`,`name`),\n KEY `create_index` (`create_time`),\n KEY `name_index` (`name`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;"
)
var source = "CREATE TABLE `test_user` (\n `id` bigint NOT NULL AUTO_INCREMENT,\n `mobile` varchar(255) COLLATE utf8mb4_bin NOT NULL,\n `class` bigint NOT NULL,\n `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `mobile_unique` (`mobile`),\n UNIQUE KEY `class_name_unique` (`class`,`name`),\n KEY `create_index` (`create_time`),\n KEY `name_index` (`name`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;"
func TestCacheModel(t *testing.T) {
logx.Disable()

View File

@@ -134,7 +134,6 @@ func TestGenCacheKeys(t *testing.T) {
return true
}())
})
}
func cacheKeyEqual(k1 Key, k2 Key) bool {
@@ -161,5 +160,4 @@ func cacheKeyEqual(k1 Key, k2 Key) bool {
k1.DataKeyRight == k2.DataKeyRight &&
k1.DataKeyExpression == k2.DataKeyExpression &&
k1.KeyExpression == k2.KeyExpression
}

View File

@@ -165,7 +165,7 @@ func convertColumns(columns []*sqlparser.ColumnDefinition, primaryColumn string)
comment = string(column.Type.Comment.Val)
}
var isDefaultNull = true
isDefaultNull := true
if column.Type.NotNull {
isDefaultNull = false
} else {

View File

@@ -37,7 +37,7 @@ func PluginCommand(c *cli.Context) error {
panic(err)
}
var plugin = c.String("plugin")
plugin := c.String("plugin")
if len(plugin) == 0 {
return errors.New("missing plugin")
}
@@ -113,7 +113,7 @@ func getCommand(arg string) (string, bool, error) {
return abs, false, nil
}
var defaultErr = errors.New("invalid plugin value " + arg)
defaultErr := errors.New("invalid plugin value " + arg)
if strings.HasPrefix(arg, "http") {
items := strings.Split(arg, "/")
if len(items) == 0 {

View File

@@ -89,7 +89,7 @@ func (g *DefaultGenerator) GenCall(ctx DirContext, proto parser.Proto, cfg *conf
return err
}
var alias = collection.NewSet()
alias := collection.NewSet()
for _, item := range proto.Message {
alias.AddStr(fmt.Sprintf("%s = %s", parser.CamelCase(item.Name), fmt.Sprintf("%s.%s", proto.PbPackage, parser.CamelCase(item.Name))))
}

View File

@@ -83,7 +83,7 @@ func (g *DefaultGenerator) GenLogic(ctx DirContext, proto parser.Proto, cfg *con
}
func (g *DefaultGenerator) genLogicFunction(goPackage string, rpc *parser.RPC) (string, error) {
var functions = make([]string, 0)
functions := make([]string, 0)
text, err := util.LoadTemplate(category, logicFuncTemplateFileFile, logicFunctionTemplate)
if err != nil {
return "", err

View File

@@ -164,6 +164,7 @@ func CamelCase(s string) string {
}
return string(t)
}
func isASCIILower(c byte) bool {
return 'a' <= c && c <= 'z'
}

View File

@@ -21,11 +21,9 @@ type (
MarkDone()
Must(err error)
}
colorConsole struct {
}
colorConsole struct{}
// for idea log
ideaConsole struct {
}
ideaConsole struct{}
)
// NewConsole returns an instance of Console

View File

@@ -61,8 +61,8 @@ func FindGoModPath(dir string) (string, bool) {
absDir = strings.ReplaceAll(absDir, `\`, `/`)
var rootPath string
var tempPath = absDir
var hasGoMod = false
tempPath := absDir
hasGoMod := false
for {
if FileExists(filepath.Join(tempPath, goModeIdentifier)) {
rootPath = strings.TrimPrefix(absDir[len(tempPath):], "/")

View File

@@ -42,7 +42,7 @@ func (s String) ReplaceAll(old, new string) string {
return strings.ReplaceAll(s.source, old, new)
}
//Source returns the source string value
// Source returns the source string value
func (s String) Source() string {
return s.source
}

View File

@@ -7,7 +7,7 @@ import (
"text/template"
)
const regularPerm = 0666
const regularPerm = 0o666
// DefaultTemplate is a tool to provides the text/template operations
type DefaultTemplate struct {