summaryrefslogtreecommitdiff
path: root/internal/enumtest/enumtest.go
blob: cccb09cbde79e1a0281af2e3b6e25b39c1efa477 (plain) (blame)
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
// SPDX-License-Identifier: GPL-3.0-or-later

// Package enumtest reads the constants of an enum type from Go source, so
// a test can check that every value is handled - and fails when a value is
// added without the code that needs it. Only tests import it.
package enumtest

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
)

// Names returns, in declaration order, the constants declared with type typ
// in the Go file at path, including those an iota block types implicitly.
// A type with no constants there is an error, so a renamed file or type
// cannot make a test pass by finding nothing.
func Names(path, typ string) ([]string, error) {
	f, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)
	if err != nil {
		return nil, err
	}
	var names []string
	for _, decl := range f.Decls {
		g, ok := decl.(*ast.GenDecl)
		if !ok || g.Tok != token.CONST {
			continue
		}
		inType := false
		for _, spec := range g.Specs {
			vs, ok := spec.(*ast.ValueSpec)
			if !ok {
				continue
			}
			switch {
			case vs.Type != nil:
				id, ok := vs.Type.(*ast.Ident)
				inType = ok && id.Name == typ
			case len(vs.Values) > 0:
				inType = false
			}
			if inType {
				for _, n := range vs.Names {
					names = append(names, n.Name)
				}
			}
		}
	}
	if len(names) == 0 {
		return nil, fmt.Errorf("%s: no constants of type %s", path, typ)
	}
	return names, nil
}