|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | + "io/ioutil" |
| 7 | + "encoding/json" |
| 8 | + |
| 9 | + "github.com/pkg/errors" |
| 10 | + "github.com/spf13/cobra" |
| 11 | +) |
| 12 | + |
| 13 | +func getLineCount(result map[string]interface{}, key string) int { |
| 14 | + line_counts := result["line_counts"].(map[string]interface{}) |
| 15 | + return int(line_counts[key].(float64)) |
| 16 | +} |
| 17 | + |
| 18 | +func printHeader(result map[string]interface{}) { |
| 19 | + header := "Coverage: %.2f%% (%d/%d lines covered, %d missing)" |
| 20 | + fmt.Println(fmt.Sprintf(header, result["covered_percent"], getLineCount(result, "covered"), getLineCount(result, "total"), getLineCount(result, "missed"))) |
| 21 | +} |
| 22 | + |
| 23 | +func printUncoveredLines(result map[string]interface{}) { |
| 24 | + if getLineCount(result, "missed") > 0 { |
| 25 | + |
| 26 | + fmt.Println("Uncovered lines by file:") |
| 27 | + files := result["source_files"].([]interface{}) |
| 28 | + |
| 29 | + for _, file_obj := range files { |
| 30 | + file := file_obj.(map[string]interface{}) |
| 31 | + if file["covered_percent"].(float64) < 100 { |
| 32 | + printUncoveredLinesFromFile(file) |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +func printUncoveredLinesFromFile(file map[string]interface{}) { |
| 39 | + var uncovered_lines []int |
| 40 | + var values []interface{} |
| 41 | + json.Unmarshal([]byte(file["coverage"].(string)), &values) |
| 42 | + for i, value := range values { |
| 43 | + if value != nil && int(value.(float64)) == 0 { |
| 44 | + uncovered_lines = append(uncovered_lines, i + 1) |
| 45 | + } |
| 46 | + } |
| 47 | + uncovered_lines_str := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(uncovered_lines)), ", "), "[]") |
| 48 | + fmt.Println(fmt.Sprintf("%s: %s", file["name"], uncovered_lines_str)) |
| 49 | +} |
| 50 | + |
| 51 | +var showCoverageCmd = &cobra.Command{ |
| 52 | + Use: "show-coverage", |
| 53 | + Short: "Show coverage results in standard output", |
| 54 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 55 | + if len(args) == 0 { |
| 56 | + return errors.New("you must pass in one file with the coverage results") |
| 57 | + } |
| 58 | + |
| 59 | + dat, err := ioutil.ReadFile(args[0]) |
| 60 | + if err != nil { |
| 61 | + return errors.New("could not open input file") |
| 62 | + } |
| 63 | + |
| 64 | + // Parse JSON from coverage file |
| 65 | + var result map[string]interface{} |
| 66 | + json.Unmarshal([]byte(string(dat)), &result) |
| 67 | + |
| 68 | + printHeader(result) |
| 69 | + |
| 70 | + // If there are missed lines, print which are them, by file |
| 71 | + printUncoveredLines(result) |
| 72 | + |
| 73 | + return nil |
| 74 | + }, |
| 75 | +} |
| 76 | + |
| 77 | +func init() { |
| 78 | + RootCmd.AddCommand(showCoverageCmd) |
| 79 | +} |
0 commit comments