Extend roles code generator

It now also generates a function for comparing two roles for equality.
If an attribute is nil, that attribute is ignored (or rather counted as
equal)
This commit is contained in:
Melody Becker 2024-10-31 16:52:35 +01:00
parent 0ed50aca60
commit b9c95a0297

View file

@ -15,7 +15,11 @@ var findRoleStructRegex = regexp.MustCompile(`type Role struct \{([\s\S]+)\}\n\n
var (
flagInputFile = flag.String("input", "", "Specify the input file. If empty, read from stdin")
flagOutputFile = flag.String("output", "", "Specify the output file. If empty, writes to stdout")
flagOutputFile = flag.String(
"output",
"",
"Specify the output file. If empty, writes to stdout",
)
)
func main() {
@ -82,7 +86,9 @@ func main() {
// If you need to refresh the content, run go generate again
`)
outBuilder.WriteString(pkgString + "\n\n")
outBuilder.WriteString("import \"slices\"\n\n")
outBuilder.WriteString(
"import (\n \"slices\"\n \"gitlab.com/mstarongitlab/goutils/sliceutils\"\n)\n\n",
)
// Build role collapse function
outBuilder.WriteString(
@ -113,7 +119,7 @@ func main() {
`)
// Then build the deep copy function
outBuilder.WriteString("\n\nfunc RoleDeepCopy(o *Role) Role {\n")
outBuilder.WriteString("\nfunc RoleDeepCopy(o *Role) Role {\n")
outBuilder.WriteString(` n := Role{}
n.Model = o.Model
n.Name = o.Name
@ -132,7 +138,33 @@ func main() {
`, valName, valName, valName, valName))
}
}
outBuilder.WriteString(" return n\n}\n")
outBuilder.WriteString(" return n\n}\n\n")
// Build compare function
outBuilder.WriteString("func CompareRoles(a, b *Role) bool {\n")
outBuilder.WriteString(" return ")
lastName, lastType := "", ""
for valName, valType := range nameTypeMap {
lastName = valName
lastType = valType
outBuilder.WriteString(fmt.Sprintf("(a.%s == nil || b.%s == nil || ", valName, valName))
if strings.HasPrefix(valType, "[]") {
outBuilder.WriteString(
fmt.Sprintf("sliceutils.CompareUnordered(a.%s,b.%s)) && ", valName, valName),
)
} else {
outBuilder.WriteString(fmt.Sprintf("a.%s == b.%s) && ", valName, valName))
}
}
outBuilder.WriteString("(a == nil || b == nil || ")
if strings.HasPrefix(lastType, "[]") {
outBuilder.WriteString(
fmt.Sprintf("sliceutils.CompareUnordered(a.%s,b.%s))", lastName, lastName),
)
} else {
outBuilder.WriteString(fmt.Sprintf("a.%s == b.%s)", lastName, lastName))
}
outBuilder.WriteString("\n}")
// And write the entire thing to the output
fmt.Fprint(output, outBuilder.String())