File: labels_command.go

package info (click to toggle)
golang-github-onsi-ginkgo-v2 2.22.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,060 kB
  • sloc: javascript: 59; makefile: 23; sh: 14
file content (123 lines) | stat: -rw-r--r-- 2,934 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package labels

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"sort"
	"strconv"
	"strings"

	"github.com/onsi/ginkgo/v2/ginkgo/command"
	"github.com/onsi/ginkgo/v2/ginkgo/internal"
	"github.com/onsi/ginkgo/v2/types"
	"golang.org/x/tools/go/ast/inspector"
)

func BuildLabelsCommand() command.Command {
	var cliConfig = types.NewDefaultCLIConfig()

	flags, err := types.BuildLabelsCommandFlagSet(&cliConfig)
	if err != nil {
		panic(err)
	}

	return command.Command{
		Name:     "labels",
		Usage:    "ginkgo labels <FLAGS> <PACKAGES>",
		Flags:    flags,
		ShortDoc: "List labels detected in the passed-in packages (or the package in the current directory if left blank).",
		DocLink:  "spec-labels",
		Command: func(args []string, _ []string) {
			ListLabels(args, cliConfig)
		},
	}
}

func ListLabels(args []string, cliConfig types.CLIConfig) {
	suites := internal.FindSuites(args, cliConfig, false).WithoutState(internal.TestSuiteStateSkippedByFilter)
	if len(suites) == 0 {
		command.AbortWith("Found no test suites")
	}
	for _, suite := range suites {
		labels := fetchLabelsFromPackage(suite.Path)
		if len(labels) == 0 {
			fmt.Printf("%s: No labels found\n", suite.PackageName)
		} else {
			fmt.Printf("%s: [%s]\n", suite.PackageName, strings.Join(labels, ", "))
		}
	}
}

func fetchLabelsFromPackage(packagePath string) []string {
	fset := token.NewFileSet()
	parsedPackages, err := parser.ParseDir(fset, packagePath, nil, 0)
	command.AbortIfError("Failed to parse package source:", err)

	files := []*ast.File{}
	hasTestPackage := false
	for key, pkg := range parsedPackages {
		if strings.HasSuffix(key, "_test") {
			hasTestPackage = true
			for _, file := range pkg.Files {
				files = append(files, file)
			}
		}
	}
	if !hasTestPackage {
		for _, pkg := range parsedPackages {
			for _, file := range pkg.Files {
				files = append(files, file)
			}
		}
	}

	seen := map[string]bool{}
	labels := []string{}
	ispr := inspector.New(files)
	ispr.Preorder([]ast.Node{&ast.CallExpr{}}, func(n ast.Node) {
		potentialLabels := fetchLabels(n.(*ast.CallExpr))
		for _, label := range potentialLabels {
			if !seen[label] {
				seen[label] = true
				labels = append(labels, strconv.Quote(label))
			}
		}
	})

	sort.Strings(labels)
	return labels
}

func fetchLabels(callExpr *ast.CallExpr) []string {
	out := []string{}
	switch expr := callExpr.Fun.(type) {
	case *ast.Ident:
		if expr.Name != "Label" {
			return out
		}
	case *ast.SelectorExpr:
		if expr.Sel.Name != "Label" {
			return out
		}
	default:
		return out
	}
	for _, arg := range callExpr.Args {
		switch expr := arg.(type) {
		case *ast.BasicLit:
			if expr.Kind == token.STRING {
				unquoted, err := strconv.Unquote(expr.Value)
				if err != nil {
					unquoted = expr.Value
				}
				validated, err := types.ValidateAndCleanupLabel(unquoted, types.CodeLocation{})
				if err == nil {
					out = append(out, validated)
				}
			}
		}
	}
	return out
}