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

import (
P
Phodal Huang 已提交
4 5
	"encoding/json"
	"github.com/olekukonko/tablewriter"
P
Phodal Huang 已提交
6
	"github.com/phodal/coca/cmd/cmd_util"
P
Phodal Huang 已提交
7
	"github.com/phodal/coca/cmd/config"
P
Phodal Huang 已提交
8 9
	"github.com/phodal/coca/core/context/count"
	"github.com/phodal/coca/core/domain"
P
Phodal Huang 已提交
10
	"github.com/phodal/coca/core/infrastructure/string_helper"
P
Phodal Huang 已提交
11
	"github.com/spf13/cobra"
P
Phodal Huang 已提交
12
	"log"
P
Phodal Huang 已提交
13 14
	"os"
	"strconv"
P
Phodal Huang 已提交
15 16 17
)

type CountCmdConfig struct {
P
Phodal Huang 已提交
18
	DependencePath string
P
Phodal Huang 已提交
19
	Top            int
P
Phodal Huang 已提交
20 21 22 23 24 25
}

var (
	countCmdConfig CountCmdConfig
)

P
Phodal Huang 已提交
26
var cparsedDeps []domain.JClassNode
P
Phodal Huang 已提交
27

P
Phodal Huang 已提交
28
var countCmd = &cobra.Command{
P
Phodal Huang 已提交
29
	Use:   "count",
P
Phodal Huang 已提交
30
	Short: "count most refs function",
P
Phodal Huang 已提交
31 32
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
P
Phodal Huang 已提交
33 34 35 36 37
		dependence := countCmdConfig.DependencePath
		if dependence == "" {
			return
		}

P
Phodal Huang 已提交
38
		file := cmd_util.ReadFile(dependence)
P
Phodal Huang 已提交
39 40 41 42 43 44
		if file == nil {
			log.Fatal("lost file:" + dependence)
		}

		_ = json.Unmarshal(file, &cparsedDeps)

P
Phodal Huang 已提交
45
		callMap := count.BuildCallMap(cparsedDeps)
P
Phodal Huang 已提交
46

P
Phodal Huang 已提交
47
		callMapSort := string_helper.RankByWordCount(callMap)
P
Phodal Huang 已提交
48

P
Phodal Huang 已提交
49 50
		if countCmdConfig.Top > 0 {
			callMapSort = callMapSort[:countCmdConfig.Top]
P
Phodal Huang 已提交
51 52
		}

P
Phodal Huang 已提交
53 54 55
		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{"Refs Count", "method"})

P
Phodal Huang 已提交
56
		for _, count := range callMapSort {
P
Phodal Huang 已提交
57
			table.Append([]string{strconv.Itoa(count.Value), count.Key})
P
Phodal Huang 已提交
58
		}
P
Phodal Huang 已提交
59 60

		table.Render()
P
Phodal Huang 已提交
61 62 63 64 65 66
	},
}

func init() {
	rootCmd.AddCommand(countCmd)

P
Phodal Huang 已提交
67
	countCmd.PersistentFlags().StringVarP(&countCmdConfig.DependencePath, "dependence", "d", config.CocaConfig.ReporterPath+"/deps.json", "get dependence file")
P
Phodal Huang 已提交
68
	countCmd.PersistentFlags().IntVarP(&countCmdConfig.Top, "top", "t", 0, "top x")
P
Phodal Huang 已提交
69
}