File: generators_common.go

package info (click to toggle)
golang-github-onsi-ginkgo-v2 2.15.0-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 4,112 kB
  • sloc: javascript: 59; sh: 14; makefile: 7
file content (76 lines) | stat: -rw-r--r-- 1,764 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
package generators

import (
	"fmt"
	"go/build"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/onsi/ginkgo/v2/ginkgo/command"
)

type GeneratorsConfig struct {
	Agouti, NoDot, Internal bool
	CustomTemplate          string
	CustomTemplateData      string
	Tags                    string
}

func getPackageAndFormattedName() (string, string, string) {
	path, err := os.Getwd()
	command.AbortIfError("Could not get current working directory:", err)

	dirName := strings.ReplaceAll(filepath.Base(path), "-", "_")
	dirName = strings.ReplaceAll(dirName, " ", "_")

	pkg, err := build.ImportDir(path, 0)
	packageName := pkg.Name
	if err != nil {
		packageName = ensureLegalPackageName(dirName)
	}

	formattedName := prettifyName(filepath.Base(path))
	return packageName, dirName, formattedName
}

func ensureLegalPackageName(name string) string {
	if name == "_" {
		return "underscore"
	}
	if len(name) == 0 {
		return "empty"
	}
	n, isDigitErr := strconv.Atoi(string(name[0]))
	if isDigitErr == nil {
		return []string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}[n] + name[1:]
	}
	return name
}

func prettifyName(name string) string {
	name = strings.ReplaceAll(name, "-", " ")
	name = strings.ReplaceAll(name, "_", " ")
	name = strings.Title(name)
	name = strings.ReplaceAll(name, " ", "")
	return name
}

func determinePackageName(name string, internal bool) string {
	if internal {
		return name
	}

	return name + "_test"
}

// getBuildTags returns the resultant string to be added.
// If the input string is not empty, then returns a `//go:build {}` string,
// otherwise returns an empty string.
func getBuildTags(tags string) string {
	if tags != "" {
		return fmt.Sprintf("//go:build %s\n", tags)
	}
	return ""
}