bs.go 1.9 KB
Newer Older
P
Phodal Huang 已提交
1 2 3
package cmd

import (
P
Phodal Huang 已提交
4
	"encoding/json"
5 6
	"github.com/phodal/coca/core/adapter/bs"
	"github.com/phodal/coca/core/support"
P
Phodal Huang 已提交
7
	"github.com/spf13/cobra"
P
Phodal Huang 已提交
8
	"sort"
P
Phodal Huang 已提交
9 10 11
	"strings"
)

P
Phodal Huang 已提交
12 13 14 15 16 17 18 19
type BsCmdConfig struct {
	Path string
}

var (
	bsCmdConfig BsCmdConfig
)

P
Phodal Huang 已提交
20
var badsmellCmd = &cobra.Command{
P
Phodal Huang 已提交
21
	Use:   "bs",
P
Phodal Huang 已提交
22
	Short: "generate bad smell list and suggestions",
P
Phodal Huang 已提交
23 24
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
P
Phodal Huang 已提交
25
		importPath := *&bsCmdConfig.Path
P
Phodal Huang 已提交
26 27 28 29 30
		ignoreStr := cmd.Flag("ignore").Value.String()
		sortType := cmd.Flag("sort").Value.String()

		ignoreRules := strings.Split(ignoreStr, ",")

P
Phodal Huang 已提交
31
		bsApp := *bs.NewBadSmellApp()
P
Phodal Huang 已提交
32
		bsList := bsApp.AnalysisPath(importPath, ignoreRules)
P
Phodal Huang 已提交
33

P
Phodal Huang 已提交
34
		bsModel, _ := json.MarshalIndent(bsList, "", "\t")
P
Phodal Huang 已提交
35

P
Phodal Huang 已提交
36 37 38
		if sortType == "type" {
			sortSmells := sortSmellByType(bsList)
			bsModel, _ = json.MarshalIndent(sortSmells, "", "\t")
P
Phodal Huang 已提交
39
		}
P
Phodal Huang 已提交
40

P
Phodal Huang 已提交
41
		support.WriteToCocaFile("bs.json", string(bsModel))
P
Phodal Huang 已提交
42 43 44 45 46 47 48 49 50
	},
}

func sortSmellByType(models []bs.BadSmellModel) map[string][]bs.BadSmellModel {
	sortSmells := make(map[string][]bs.BadSmellModel)
	for _, model := range models {
		sortSmells[model.Bs] = append(sortSmells[model.Bs], model)
	}

P
Phodal Huang 已提交
51 52 53 54 55 56 57 58 59 60
	for key, smells := range sortSmells {
		if isSmellHaveSize(key) {
			sort.Slice(smells, func(i, j int) bool {
				return smells[i].Size > (smells[j].Size)
			})

			sortSmells[key] = smells
		}
	}

P
Phodal Huang 已提交
61 62 63
	return sortSmells
}

P
Phodal Huang 已提交
64 65 66 67 68 69 70 71
func isSmellHaveSize(key string) bool {
	var smellList = []string{
		"largeClass",
		"repeatedSwitches",
		"longParameterList",
		"longMethod",
		"dataClass",
	}
P
Phodal Huang 已提交
72
	return support.Contains(smellList, key)
P
Phodal Huang 已提交
73 74
}

P
Phodal Huang 已提交
75 76 77
func init() {
	rootCmd.AddCommand(badsmellCmd)

P
Phodal Huang 已提交
78
	badsmellCmd.PersistentFlags().StringVarP(&bsCmdConfig.Path, "path", "p", ".", "example -p core/main")
P
Phodal Huang 已提交
79 80 81
	badsmellCmd.PersistentFlags().StringP("ignore", "x", "", "-x=dataClass,lazyElement,longMethod,refusedBequest")
	badsmellCmd.PersistentFlags().StringP("sort", "s", "", "sort bad smell -s=type")
}