This repository has been archived on 2026-11-27. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
w10k/internal/gentypes/render.go
T
unkin-agent dfb5fa021f
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline failed
ci/woodpecker/pr/test Pipeline failed
ci/woodpecker/pr/lint Pipeline was successful
Generate Puppet resource types natively before the env swap
- add gentypes: a static Go port of `puppet generate types` for classic and Resource API types
- run it in prepare when w10k.generate_types is set; a failure fails the env and keeps the old link
- confine reads to the worktree and module cache, refuse a committed .resource_types symlink
- test against real puppet output for a vendored Apache-2.0 type set
2026-11-08 17:59:12 +11:00

332 lines
7.7 KiB
Go

package gentypes
import (
"fmt"
"slices"
"strings"
"time"
)
const rubySpace = " \t\r\n\f\v\x00"
func strip(s string) string { return strings.Trim(s, rubySpace) }
// scrub ports Puppet::Util::Docs.scrub: drop the least common indent (ignoring the first line) and trailing space.
func scrub(text string) string {
if !strings.Contains(strip(text), "\n") {
return strip(text)
}
_, rest, _ := strings.Cut(text, "\n")
indent, found := "", false
for _, line := range strings.Split(rest, "\n") {
n := len(line) - len(strings.TrimLeft(line, " \t"))
if n == len(line) || strings.ContainsRune(rubySpace, rune(line[n])) {
continue
}
if !found || line[:n] < indent {
indent, found = line[:n], true
}
}
lines := strings.Split(text, "\n")
for i, line := range lines {
if indent != "" {
line = strings.TrimPrefix(line, indent)
}
lines[i] = strings.TrimRight(line, rubySpace)
}
return strings.TrimRight(strings.Join(lines, "\n"), rubySpace)
}
// quote ports Puppet's StringConverter#puppet_quote.
func quote(s string) string {
for _, r := range s {
if r < 0x20 {
return doubleQuote(s)
}
}
var b strings.Builder
b.WriteByte('\'')
escaped := false
for _, r := range s {
switch {
case escaped:
b.WriteByte('\\')
b.WriteRune(r)
escaped = false
case r == '\'':
b.WriteString(`\'`)
case r == '\\':
escaped = true
default:
b.WriteRune(r)
}
}
if escaped {
b.WriteByte('\\')
}
b.WriteByte('\'')
return b.String()
}
func doubleQuote(s string) string {
var b strings.Builder
b.WriteByte('"')
for _, r := range s {
switch r {
case '\t':
b.WriteString(`\t`)
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '"':
b.WriteString(`\"`)
case '$':
b.WriteString(`\$`)
case '\\':
b.WriteString(`\\`)
default:
if r < 0x20 {
fmt.Fprintf(&b, `\u{%X}`, r)
} else {
b.WriteRune(r)
}
}
}
b.WriteByte('"')
return b.String()
}
func escapeSlash(src string) string {
var b strings.Builder
for i := 0; i < len(src); i++ {
switch src[i] {
case '\\':
b.WriteByte('\\')
if i+1 < len(src) {
i++
b.WriteByte(src[i])
}
case '/':
b.WriteString(`\/`)
default:
b.WriteByte(src[i])
}
}
return b.String()
}
func (r regex) opts() (on, off string) {
for _, f := range "mix" {
if strings.ContainsRune(r.flags, f) {
on += string(f)
} else {
off += string(f)
}
}
return on, off
}
// inspect renders Ruby's Regexp#inspect.
func (r regex) inspect() string {
on, _ := r.opts()
return "/" + escapeSlash(r.src) + "/" + on
}
// puppet renders the %p form: inspect without options, else /(?on-off:src)/.
func (r regex) puppet() (string, error) {
if strings.ContainsAny(r.flags, "nesu") {
return "", fmt.Errorf("regex /%s/%s: encoding flags are not supported", r.src, r.flags)
}
on, off := r.opts()
if on == "" {
return r.inspect(), nil
}
if strings.HasPrefix(r.src, "(?") {
return "", fmt.Errorf("regex /%s/%s: leading inline group with flags is not supported", r.src, r.flags)
}
if off != "" {
off = "-" + off
}
return "/(?" + on + off + ":" + escapeSlash(r.src) + ")/", nil
}
func (a *attr) puppetType() (string, error) {
var strs, res []string
for _, v := range a.values {
if v.re != nil {
s, err := v.re.puppet()
if err != nil {
return "", err
}
res = append(res, s)
continue
}
strs = append(strs, quote(v.display()))
for _, al := range v.aliases {
strs = append(strs, quote(al))
}
}
var parts []string
if slices.Contains(strs, "'true'") || slices.Contains(strs, "'false'") {
parts = append(parts, "Boolean")
}
if len(strs) > 0 {
parts = append(parts, "Enum["+strings.Join(strs, ", ")+"]")
}
if len(res) > 0 {
parts = append(parts, "Pattern["+strings.Join(res, ", ")+"]")
}
switch len(parts) {
case 0:
return "Any", nil
case 1:
return parts[0], nil
}
return "Variant[" + strings.Join(parts, ", ") + "]", nil
}
func (v *value) display() string { return strings.TrimPrefix(v.name, "\x00") }
func (a *attr) fullDoc() string {
doc := a.doc
if doc == "" && a.defaults {
doc = "The basic property that the resource should be in."
}
var vals strings.Builder
if len(a.strs) > 0 {
names := make([]string, len(a.strs))
for i, v := range a.strs {
names[i] = "`" + v.display() + "`"
if len(v.aliases) > 0 {
names[i] += " (also called `" + strings.Join(v.aliases, ", ") + "`)"
}
}
vals.WriteString("Valid values are " + strings.Join(names, ", ") + ". ")
}
if len(a.res) > 0 {
res := make([]string, len(a.res))
for i, v := range a.res {
res[i] = v.re.inspect()
}
vals.WriteString("Values can match `" + strings.Join(res, "`, `") + "`.")
}
doc = scrub(doc) + "\n\n" + vals.String()
if len(a.features) > 0 {
doc += "\n\nRequires features " + strings.Join(a.features, " ") + "."
}
return strip(doc)
}
func providerParam(typ string, providers []string) *attr {
doc := "The specific backend to use for this `" + typ + "`\nresource. You will seldom need to specify this --- OpenVox will usually\ndiscover the appropriate provider for your platform.Available providers are:\n\n"
for _, p := range providers {
doc += p + "\n: \n\n"
}
return &attr{name: "provider", doc: doc}
}
func writeDoc(b *strings.Builder, doc, prefix string) {
if doc == "" {
return
}
for _, line := range strings.Split(doc, "\n") {
b.WriteString(prefix + line + "\n")
}
}
func writeAttrs(b *strings.Builder, attrs []*attr) error {
b.WriteString(" [\n")
for i, a := range attrs {
typ, err := a.puppetType()
if err != nil {
return fmt.Errorf("attribute %s: %w", a.name, err)
}
writeDoc(b, a.fullDoc(), " # ")
b.WriteString(" Puppet::Resource::Param(" + typ + ", " + quote(a.name))
if a.namevar {
b.WriteString(", true")
}
b.WriteString(")")
if i+1 < len(attrs) {
b.WriteString(",\n\n")
}
}
b.WriteString("\n ],\n")
return nil
}
func (t *rtype) titlePatterns() ([]pattern, error) {
if t.custom {
return t.patterns, nil
}
var keys []string
for _, a := range t.params {
if a.namevar || a.name == "name" {
keys = append(keys, a.name)
}
}
switch len(keys) {
case 0:
return nil, nil
case 1:
return []pattern{{re: regex{"(.*)", "m"}, names: keys}}, nil
}
return nil, fmt.Errorf("you must specify title patterns when there are two or more key attributes")
}
func render(t *rtype, providers []string, now time.Time) (string, error) {
params := t.params
if len(providers) > 0 && !t.rsapi && !t.hasParam("provider") {
params = append(params[:len(params):len(params)], providerParam(t.name, providers))
}
pats, err := t.titlePatterns()
if err != nil {
return "", err
}
var b strings.Builder
b.WriteString("# This file was automatically generated on " + now.Format("2006-01-02 15:04:05 -0700") + ".\n")
b.WriteString("# Use the 'puppet generate types' command to regenerate this file.\n\n")
writeDoc(&b, strip(scrub(t.doc)), "# ")
b.WriteString("Puppet::Resource::ResourceType3.new(\n " + quote(t.name) + ",\n")
if err := writeAttrs(&b, t.props); err != nil {
return "", err
}
if err := writeAttrs(&b, params); err != nil {
return "", err
}
b.WriteString(" {\n")
var keys, lines []string
for _, p := range pats {
re, err := p.re.puppet()
if err != nil {
return "", err
}
names := make([]string, len(p.names))
for i, n := range p.names {
names[i] = quote(n)
}
line := " " + re + " => [" + strings.Join(names, ", ") + "]"
if i := slices.Index(keys, re); i >= 0 {
lines[i] = line
continue
}
keys, lines = append(keys, re), append(lines, line)
}
b.WriteString(strings.Join(lines, ",\n"))
if len(lines) > 0 {
b.WriteString("\n")
}
b.WriteString(" },\n true,\n false)\n")
return b.String(), nil
}
func (t *rtype) hasParam(name string) bool {
for _, a := range t.params {
if a.name == name {
return true
}
}
return false
}