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 8435678797 Reject unparsed type-body statements and render literals as Ruby does
- error on stray closers, deep nesting and runaway parses
- allow only inert statements in type and attribute bodies, resolving included mixins
- add the implicit ensure puppet gives types defining exists?, create and destroy
- accept behavior: as the Resource API alias of behaviour:
- normalise Ruby integer, float, string escape and regex literals, failing on forms that cannot be reproduced
- unlink stale symlinks in .resource_types
- verify fixtures, with real providers, against real puppet output
2026-11-08 18:50:46 +11:00

394 lines
9.7 KiB
Go

package gentypes
import (
"fmt"
"slices"
"strconv"
"strings"
"time"
"unicode/utf8"
)
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()
}
// exprStr ports Ruby's rb_reg_expr_str: escape unescaped '/' and hex-escape non-printable ASCII.
func exprStr(src string) string {
var b strings.Builder
for i := 0; i < len(src); i++ {
switch c := src[i]; {
case c == '\\' && i+1 < len(src):
_, n := utf8.DecodeRuneInString(src[i+1:])
b.WriteString(src[i : i+1+n])
i += n
case c == '/':
b.WriteString(`\/`)
case c < 0x80 && (c < 0x20 || c == 0x7f) && !strings.ContainsRune("\t\n\v\f\r", rune(c)):
fmt.Fprintf(&b, `\x%02X`, c)
default:
b.WriteByte(c)
}
}
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
}
// fixedEncoding reports whether Ruby marks the regex FIXEDENCODING, rejecting escapes Ruby rewrites or refuses.
func (r regex) fixedEncoding() (bool, error) {
fixed := false
for i := 0; i < len(r.src); i++ {
if r.src[i] >= 0x80 {
fixed = true
continue
}
if r.src[i] != '\\' || i+1 >= len(r.src) {
continue
}
i++
rest := r.src[i:]
switch rest[0] {
case 'p', 'P':
fixed = true
case 'u':
var cps []string
if len(rest) > 1 && rest[1] == '{' {
end := strings.IndexByte(rest, '}')
if end < 0 {
return false, fmt.Errorf("regex /%s/: invalid \\u escape", r.src)
}
cps = strings.Fields(rest[2:end])
} else if len(rest) >= 5 {
cps = []string{rest[1:5]}
}
if len(cps) == 0 {
return false, fmt.Errorf("regex /%s/: invalid \\u escape", r.src)
}
for _, h := range cps {
v, err := strconv.ParseUint(h, 16, 32)
if err != nil {
return false, fmt.Errorf("regex /%s/: invalid \\u escape", r.src)
}
fixed = fixed || v >= 0x80
}
case 'x':
if v, n := hexVal(rest[1:], 2); n > 0 && v >= 0x80 {
return false, fmt.Errorf("regex /%s/: non-ASCII \\x escape is not supported", r.src)
}
case 'M', 'C', 'c':
return false, fmt.Errorf("regex /%s/: \\%c escapes are not supported", r.src, rest[0])
case '2', '3':
if len(rest) >= 3 && strings.IndexByte("01234567", rest[1]) >= 0 && strings.IndexByte("01234567", rest[2]) >= 0 {
return false, fmt.Errorf("regex /%s/: non-ASCII octal escape is not supported", r.src)
}
}
}
return fixed, nil
}
// inspect renders Ruby's Regexp#inspect.
func (r regex) inspect() string {
on, _ := r.opts()
return "/" + exprStr(r.src) + "/" + on
}
// puppet ports Puppet's regexp_to_s_with_delimiters: inspect when options are 0, else /#{Regexp#to_s}/.
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)
}
fixed, err := r.fixedEncoding()
if err != nil {
return "", err
}
on, off := r.opts()
if on == "" && !fixed {
return r.inspect(), nil
}
if strings.HasPrefix(r.src, "(?") {
return "", fmt.Errorf("regex /%s/%s: leading inline group with options is not supported", r.src, r.flags)
}
if off != "" {
off = "-" + off
}
return "/(?" + on + off + ":" + exprStr(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, "\xff") }
func (a *attr) fullDoc() string {
if a.raw {
return strip(a.doc)
}
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 slices.Sorted(slices.Values(providers)) {
doc += p + "\n: \n\n"
}
return &attr{name: "provider", doc: doc, raw: true}
}
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
}