From dfb5fa021fe3ff01a1addae06fe49f4b5ed59469 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 17:59:12 +1100 Subject: [PATCH 1/8] 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 --- .pre-commit-config.yaml | 1 + internal/deploy/config.go | 3 +- internal/deploy/config_test.go | 13 + internal/deploy/deploy.go | 7 + internal/deploy/deploy_test.go | 52 + internal/gentypes/generate.go | 278 +++ internal/gentypes/generate_test.go | 391 +++++ internal/gentypes/lexer.go | 637 +++++++ internal/gentypes/parse.go | 1144 ++++++++++++ internal/gentypes/render.go | 331 ++++ .../gentypes/testdata/env/environment.conf | 1 + .../env/external_modules/alternatives/LICENSE | 178 ++ .../provider/alternative_entry/chkconfig.rb | 0 .../puppet/provider/alternative_entry/dpkg.rb | 0 .../puppet/provider/alternatives/chkconfig.rb | 0 .../lib/puppet/provider/alternatives/dpkg.rb | 0 .../lib/puppet/type/alternative_entry.rb | 68 + .../lib/puppet/type/alternatives.rb | 45 + .../env/external_modules/archive/LICENSE | 203 +++ .../lib/puppet/provider/archive/curl.rb | 0 .../lib/puppet/provider/archive/ruby.rb | 0 .../lib/puppet/provider/archive/wget.rb | 0 .../archive/lib/puppet/type/archive.rb | 283 +++ .../env/external_modules/concat/LICENSE | 202 +++ .../env/external_modules/concat/NOTICE | 15 + .../concat/lib/puppet/type/concat_file.rb | 362 ++++ .../env/external_modules/firewall/LICENSE | 202 +++ .../env/external_modules/firewall/NOTICE | 23 + .../lib/puppet/provider/firewall/firewall.rb | 0 .../provider/firewallchain/firewallchain.rb | 0 .../firewall/lib/puppet/type/firewall.rb | 1548 +++++++++++++++++ .../firewall/lib/puppet/type/firewallchain.rb | 91 + .../env/external_modules/grafana/LICENSE | 201 +++ .../provider/grafana_plugin/grafana_cli.rb | 0 .../grafana/lib/puppet/type/grafana_plugin.rb | 59 + .../env/external_modules/inifile/LICENSE | 202 +++ .../env/external_modules/inifile/NOTICE | 19 + .../lib/puppet/provider/ini_setting/ruby.rb | 0 .../inifile/lib/puppet/type/ini_setting.rb | 153 ++ .../env/external_modules/minio/LICENSE | 13 + .../minio_client_alias/minio_client_alias.rb | 0 .../lib/puppet/type/minio_client_alias.rb | 66 + .../env/external_modules/mysql/LICENSE | 202 +++ .../env/external_modules/mysql/NOTICE | 15 + .../provider/mysql_login_path/inifile.rb | 0 .../mysql_login_path/mysql_login_path.rb | 0 .../provider/mysql_login_path/sensitive.rb | 0 .../mysql/lib/puppet/type/mysql_login_path.rb | 82 + .../env/external_modules/network/LICENSE | 178 ++ .../provider/network_config/interfaces.rb | 0 .../puppet/provider/network_config/redhat.rb | 0 .../puppet/provider/network_config/sles.rb | 0 .../network/lib/puppet/type/network_config.rb | 155 ++ .../env/external_modules/reboot/LICENSE | 202 +++ .../env/external_modules/reboot/NOTICE | 15 + .../lib/puppet/provider/reboot/linux.rb | 0 .../lib/puppet/provider/reboot/posix.rb | 0 .../lib/puppet/provider/reboot/windows.rb | 0 .../reboot/lib/puppet/type/reboot.rb | 214 +++ .../env/external_modules/stdlib/LICENSE | 202 +++ .../env/external_modules/stdlib/NOTICE | 23 + .../lib/puppet/provider/file_line/ruby.rb | 0 .../stdlib/lib/puppet/type/anchor.rb | 54 + .../stdlib/lib/puppet/type/file_line.rb | 194 +++ .../env/external_modules/yumrepo_core/LICENSE | 201 +++ .../lib/puppet/provider/yumrepo/inifile.rb | 0 .../yumrepo_core/lib/puppet/type/yumrepo.rb | 462 +++++ .../testdata/golden/alternative_entry.pp | 47 + .../gentypes/testdata/golden/alternatives.pp | 40 + internal/gentypes/testdata/golden/anchor.pp | 55 + internal/gentypes/testdata/golden/archive.pp | 143 ++ .../gentypes/testdata/golden/concat_file.pp | 114 ++ .../gentypes/testdata/golden/file_line.pp | 178 ++ internal/gentypes/testdata/golden/firewall.pp | 1408 +++++++++++++++ .../gentypes/testdata/golden/firewallchain.pp | 82 + .../testdata/golden/grafana_plugin.pp | 59 + .../gentypes/testdata/golden/ini_setting.pp | 71 + .../testdata/golden/minio_client_alias.pp | 62 + .../testdata/golden/mysql_login_path.pp | 75 + .../testdata/golden/network_config.pp | 99 ++ internal/gentypes/testdata/golden/reboot.pp | 140 ++ internal/gentypes/testdata/golden/yumrepo.pp | 348 ++++ 82 files changed, 11910 insertions(+), 1 deletion(-) create mode 100644 internal/gentypes/generate.go create mode 100644 internal/gentypes/generate_test.go create mode 100644 internal/gentypes/lexer.go create mode 100644 internal/gentypes/parse.go create mode 100644 internal/gentypes/render.go create mode 100644 internal/gentypes/testdata/env/environment.conf create mode 100644 internal/gentypes/testdata/env/external_modules/alternatives/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/chkconfig.rb create mode 100644 internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/dpkg.rb create mode 100644 internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/chkconfig.rb create mode 100644 internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/dpkg.rb create mode 100644 internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/type/alternative_entry.rb create mode 100644 internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/type/alternatives.rb create mode 100644 internal/gentypes/testdata/env/external_modules/archive/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/curl.rb create mode 100644 internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/ruby.rb create mode 100644 internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/wget.rb create mode 100644 internal/gentypes/testdata/env/external_modules/archive/lib/puppet/type/archive.rb create mode 100644 internal/gentypes/testdata/env/external_modules/concat/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/concat/NOTICE create mode 100644 internal/gentypes/testdata/env/external_modules/concat/lib/puppet/type/concat_file.rb create mode 100644 internal/gentypes/testdata/env/external_modules/firewall/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/firewall/NOTICE create mode 100644 internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewall/firewall.rb create mode 100644 internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewallchain/firewallchain.rb create mode 100644 internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/type/firewall.rb create mode 100644 internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/type/firewallchain.rb create mode 100644 internal/gentypes/testdata/env/external_modules/grafana/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/provider/grafana_plugin/grafana_cli.rb create mode 100644 internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/type/grafana_plugin.rb create mode 100644 internal/gentypes/testdata/env/external_modules/inifile/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/inifile/NOTICE create mode 100644 internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb create mode 100644 internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/type/ini_setting.rb create mode 100644 internal/gentypes/testdata/env/external_modules/minio/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/minio/lib/puppet/provider/minio_client_alias/minio_client_alias.rb create mode 100644 internal/gentypes/testdata/env/external_modules/minio/lib/puppet/type/minio_client_alias.rb create mode 100644 internal/gentypes/testdata/env/external_modules/mysql/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/mysql/NOTICE create mode 100644 internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/inifile.rb create mode 100644 internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/mysql_login_path.rb create mode 100644 internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/sensitive.rb create mode 100644 internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/type/mysql_login_path.rb create mode 100644 internal/gentypes/testdata/env/external_modules/network/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/interfaces.rb create mode 100644 internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/redhat.rb create mode 100644 internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/sles.rb create mode 100644 internal/gentypes/testdata/env/external_modules/network/lib/puppet/type/network_config.rb create mode 100644 internal/gentypes/testdata/env/external_modules/reboot/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/reboot/NOTICE create mode 100644 internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/linux.rb create mode 100644 internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/posix.rb create mode 100644 internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/windows.rb create mode 100644 internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/type/reboot.rb create mode 100644 internal/gentypes/testdata/env/external_modules/stdlib/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/stdlib/NOTICE create mode 100644 internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/provider/file_line/ruby.rb create mode 100644 internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/type/anchor.rb create mode 100644 internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/type/file_line.rb create mode 100644 internal/gentypes/testdata/env/external_modules/yumrepo_core/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb create mode 100644 internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/type/yumrepo.rb create mode 100644 internal/gentypes/testdata/golden/alternative_entry.pp create mode 100644 internal/gentypes/testdata/golden/alternatives.pp create mode 100644 internal/gentypes/testdata/golden/anchor.pp create mode 100644 internal/gentypes/testdata/golden/archive.pp create mode 100644 internal/gentypes/testdata/golden/concat_file.pp create mode 100644 internal/gentypes/testdata/golden/file_line.pp create mode 100644 internal/gentypes/testdata/golden/firewall.pp create mode 100644 internal/gentypes/testdata/golden/firewallchain.pp create mode 100644 internal/gentypes/testdata/golden/grafana_plugin.pp create mode 100644 internal/gentypes/testdata/golden/ini_setting.pp create mode 100644 internal/gentypes/testdata/golden/minio_client_alias.pp create mode 100644 internal/gentypes/testdata/golden/mysql_login_path.pp create mode 100644 internal/gentypes/testdata/golden/network_config.pp create mode 100644 internal/gentypes/testdata/golden/reboot.pp create mode 100644 internal/gentypes/testdata/golden/yumrepo.pp diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 24236dd..6e92a31 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,3 +1,4 @@ +exclude: ^internal/gentypes/testdata/ repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.6.0 diff --git a/internal/deploy/config.go b/internal/deploy/config.go index 20e9636..1673271 100644 --- a/internal/deploy/config.go +++ b/internal/deploy/config.go @@ -15,7 +15,8 @@ type Config struct { Cachedir string `yaml:"cachedir"` Sources map[string]*Source `yaml:"sources"` W10k struct { - GCGrace *time.Duration `yaml:"gc_grace"` + GCGrace *time.Duration `yaml:"gc_grace"` + GenerateTypes bool `yaml:"generate_types"` } `yaml:"w10k"` } diff --git a/internal/deploy/config_test.go b/internal/deploy/config_test.go index 20ebe34..2dfa9ad 100644 --- a/internal/deploy/config_test.go +++ b/internal/deploy/config_test.go @@ -98,3 +98,16 @@ func TestIgnored(t *testing.T) { } } } + +func TestParseConfigGenerateTypes(t *testing.T) { + base := "cachedir: /c\nsources:\n a:\n remote: r\n basedir: /a\n" + for cfg, want := range map[string]bool{base: false, base + "w10k:\n generate_types: true\n": true, base + ":w10k:\n :generate_types: true\n": true} { + c, err := ParseConfig([]byte(cfg)) + if err != nil { + t.Fatal(err) + } + if c.W10k.GenerateTypes != want { + t.Errorf("%q: generate_types = %v", cfg, c.W10k.GenerateTypes) + } + } +} diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 18abe54..8aa3829 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -16,6 +16,8 @@ import ( "sync" "syscall" "time" + + "git.unkin.net/unkin/w10k/internal/gentypes" ) const ( @@ -469,6 +471,11 @@ func linkModule(root, rel, dir string) error { // prepare runs last before a worktree can be swapped in; its out-of-tree done file marks the worktree complete. func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods []resolved, started time.Time) error { + if d.cfg.W10k.GenerateTypes { + if err := gentypes.Generate(target, d.path("modules"), d.path("forge")); err != nil { + return fmt.Errorf("generate types: %w", err) + } + } r := deployResult{ Name: name, Signature: sha, diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 3b15c13..3c287f0 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -594,3 +594,55 @@ func TestJobsBoundGitProcesses(t *testing.T) { t.Fatalf("%d concurrent git processes with -j %d", peak, jobs) } } + +func TestGenerateTypesBeforeSwap(t *testing.T) { + f := newFixture(t) + f.cfg.W10k.GenerateTypes = true + typed := filepath.Join(f.root, "typed") + newRepo(t, typed) + commit(t, typed, map[string]string{ + "lib/puppet/type/typed.rb": "Puppet::Type.newtype(:typed) do\n newparam(:name, namevar: true)\nend\n", + "lib/puppet/provider/typed/posix.rb": "", + }) + commit(t, f.control, map[string]string{ + "Puppetfile": fmt.Sprintf("moduledir 'external_modules'\nmod 'typed', :git => '%s'\n", typed), + "environment.conf": "modulepath = site:external_modules:$basemodulepath\n", + "site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n ensurable\n newparam(:name)\nend\n", + }) + f.mustDeploy(false) + live := f.env("main") + pp := readFileT(t, filepath.Join(f.basedir, "main", ".resource_types", "typed.pp")) + if !strings.Contains(pp, "Puppet::Resource::Param(Any, 'provider')") || !exists(filepath.Join(live, ".resource_types", "local.pp")) { + t.Fatalf("types not generated:\n%s", pp) + } + + commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(dynamic)\nend\n"}) + if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "generate types") || !strings.Contains(err.Error(), "site/local/lib/puppet/type/local.rb") { + t.Fatalf("broken type must fail the deploy naming the file: %v", err) + } + if f.env("main") != live { + t.Fatal("failed generation must leave the live env untouched") + } + + commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name)\nend\n"}) + if err := os.Symlink("/tmp", filepath.Join(f.control, ".resource_types")); err != nil { + t.Fatal(err) + } + gitT(t, f.control, "add", "-A") + gitT(t, f.control, "commit", "-q", "-m", "link") + if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "not a directory") { + t.Fatalf("committed .resource_types symlink must fail: %v", err) + } + if f.env("main") != live { + t.Fatal("failed generation must leave the live env untouched") + } +} + +func readFileT(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go new file mode 100644 index 0000000..836d12f --- /dev/null +++ b/internal/gentypes/generate.go @@ -0,0 +1,278 @@ +// Package gentypes is a static port of `puppet generate types`. +package gentypes + +import ( + "bufio" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "sort" + "strings" + "time" +) + +const OutDir = ".resource_types" + +var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) + +type gen struct { + env string + roots []string +} + +// Generate writes /.resource_types; every file it reads must resolve inside env or one of roots. +func Generate(env string, roots ...string) error { + g := &gen{} + for i, r := range append([]string{env}, roots...) { + real, err := filepath.EvalSymlinks(r) + if i > 0 && errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return err + } + g.roots = append(g.roots, real) + } + g.env = g.roots[0] + mods, err := g.modules() + if err != nil { + return err + } + var inputs []string + providers := map[string][]string{} + for _, m := range mods { + files, err := g.glob(filepath.Join(m, "lib", "puppet", "type")) + if err != nil { + return err + } + inputs = append(inputs, files...) + dirs, err := g.list(filepath.Join(m, "lib", "puppet", "provider")) + if err != nil { + return err + } + for _, d := range dirs { + files, err := g.glob(d) + if err != nil { + return err + } + for _, f := range files { + typ, name := filepath.Base(d), strings.TrimSuffix(filepath.Base(f), ".rb") + if !slices.Contains(providers[typ], name) { + providers[typ] = append(providers[typ], name) + } + } + } + } + sort.Strings(inputs) + out := filepath.Join(g.env, OutDir) + if fi, err := os.Lstat(out); err == nil && !fi.IsDir() { + return fmt.Errorf("%s exists and is not a directory", out) + } else if errors.Is(err, os.ErrNotExist) { + if err := os.Mkdir(out, 0o755); err != nil { + return err + } + } else if err != nil { + return err + } + keep := map[string]bool{} + for _, in := range inputs { + keep[strings.TrimSuffix(filepath.Base(in), ".rb")+".pp"] = true + } + entries, err := os.ReadDir(out) + if err != nil { + return err + } + for _, e := range entries { + if !keep[e.Name()] && e.Type().IsRegular() { + if err := os.Remove(filepath.Join(out, e.Name())); err != nil { + return err + } + } + } + var errs []error + for _, in := range inputs { + if err := generateOne(in, out, providers); err != nil { + errs = append(errs, fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err)) + } + } + return errors.Join(errs...) +} + +func generateOne(in, out string, providers map[string][]string) error { + ifi, err := os.Stat(in) + if err != nil { + return err + } + name := strings.TrimSuffix(filepath.Base(in), ".rb") + dst := filepath.Join(out, name+".pp") + if ofi, err := os.Lstat(dst); err == nil && ofi.Mode().IsRegular() && ofi.ModTime().Equal(ifi.ModTime()) { + return nil + } + src, err := os.ReadFile(in) + if err != nil { + return err + } + types, err := parseFile(string(src)) + if err != nil { + return err + } + var t *rtype + for _, c := range types { + if c.name == name { + t = c + } + } + if t == nil { + return fmt.Errorf("custom type %q was not defined", name) + } + body, err := render(t, providers[name], time.Now()) + if err != nil { + return err + } + tmp, err := os.CreateTemp(out, "."+name+".*.tmp") + if err != nil { + return err + } + defer func() { _ = os.Remove(tmp.Name()) }() + if _, err := tmp.WriteString(body); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Chmod(0o644); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := os.Chtimes(tmp.Name(), ifi.ModTime(), ifi.ModTime()); err != nil { + return err + } + return os.Rename(tmp.Name(), dst) +} + +func (g *gen) confine(p string) (string, error) { + real, err := filepath.EvalSymlinks(p) + if err != nil { + return "", err + } + for _, r := range g.roots { + if real == r || strings.HasPrefix(real, r+string(filepath.Separator)) { + return real, nil + } + } + return "", fmt.Errorf("%s resolves outside the environment and module cache", p) +} + +// list returns the confined subdirectories of dir, or nothing when dir is absent. +func (g *gen) list(dir string) ([]string, error) { + if _, err := os.Lstat(dir); errors.Is(err, os.ErrNotExist) { + return nil, nil + } + real, err := g.confine(dir) + if err != nil { + return nil, err + } + entries, err := os.ReadDir(real) + if err != nil { + return nil, err + } + var out []string + for _, e := range entries { + p, err := g.confine(filepath.Join(real, e.Name())) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return nil, err + } + if fi, err := os.Stat(p); err == nil && fi.IsDir() { + out = append(out, filepath.Join(dir, e.Name())) + } + } + return out, nil +} + +// glob returns the confined regular *.rb files directly inside dir. +func (g *gen) glob(dir string) ([]string, error) { + if _, err := os.Lstat(dir); errors.Is(err, os.ErrNotExist) { + return nil, nil + } + real, err := g.confine(dir) + if err != nil { + return nil, err + } + entries, err := os.ReadDir(real) + if err != nil { + return nil, err + } + var out []string + for _, e := range entries { + if !strings.HasSuffix(e.Name(), ".rb") { + continue + } + p, err := g.confine(filepath.Join(real, e.Name())) + if err != nil { + return nil, err + } + if fi, err := os.Stat(p); err == nil && fi.Mode().IsRegular() { + out = append(out, filepath.Join(dir, e.Name())) + } + } + return out, nil +} + +// modules resolves environment.conf's modulepath to module dirs, first name wins; $basemodulepath is skipped. +func (g *gen) modules() ([]string, error) { + modulepath := "modules:$basemodulepath" + conf := filepath.Join(g.env, "environment.conf") + if _, err := os.Lstat(conf); err == nil { + real, err := g.confine(conf) + if err != nil { + return nil, err + } + f, err := os.Open(real) + if err != nil { + return nil, err + } + sc := bufio.NewScanner(f) + for sc.Scan() { + k, v, ok := strings.Cut(sc.Text(), "=") + if ok && strings.TrimSpace(k) == "modulepath" { + modulepath = strings.Trim(strings.TrimSpace(v), `"'`) + } + } + _ = f.Close() + if err := sc.Err(); err != nil { + return nil, err + } + } + seen := map[string]bool{} + var mods []string + for _, entry := range strings.Split(modulepath, ":") { + entry = strings.TrimSpace(entry) + if entry == "" || entry == "$basemodulepath" { + continue + } + if strings.Contains(entry, "$") { + return nil, fmt.Errorf("environment.conf: unsupported modulepath entry %q", entry) + } + if !filepath.IsAbs(entry) { + entry = filepath.Join(g.env, entry) + } + dirs, err := g.list(entry) + if err != nil { + return nil, err + } + for _, d := range dirs { + if name := filepath.Base(d); moduleName.MatchString(name) && !seen[name] { + seen[name] = true + mods = append(mods, d) + } + } + } + return mods, nil +} diff --git a/internal/gentypes/generate_test.go b/internal/gentypes/generate_test.go new file mode 100644 index 0000000..1960fe2 --- /dev/null +++ b/internal/gentypes/generate_test.go @@ -0,0 +1,391 @@ +package gentypes + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" +) + +var ( + commentLine = regexp.MustCompile(`(?m)^\s*#.*\n`) + blankRun = regexp.MustCompile(`\n{2,}`) +) + +func uncommented(s string) string { + return blankRun.ReplaceAllString(commentLine.ReplaceAllString(s, ""), "\n") +} + +// GENTYPES_ENV/GENTYPES_GOLDEN point the golden comparison at a full environment and its real `puppet generate types` output. +func TestGolden(t *testing.T) { + env, golden := "testdata/env", "testdata/golden" + if e := os.Getenv("GENTYPES_ENV"); e != "" { + env, golden = e, os.Getenv("GENTYPES_GOLDEN") + } + work := t.TempDir() + if err := os.CopyFS(work, os.DirFS(env)); err != nil { + t.Fatal(err) + } + if err := os.RemoveAll(filepath.Join(work, OutDir)); err != nil { + t.Fatal(err) + } + if err := Generate(work); err != nil { + t.Fatal(err) + } + want, _ := filepath.Glob(filepath.Join(golden, "*.pp")) + if len(want) == 0 { + t.Fatal("no golden files") + } + match := 0 + for _, w := range want { + name := filepath.Base(w) + t.Run(strings.TrimSuffix(name, ".pp"), func(t *testing.T) { + wb, _ := os.ReadFile(w) + gb, err := os.ReadFile(filepath.Join(work, OutDir, name)) + if err != nil { + t.Fatal(err) + } + if g, w := uncommented(string(gb)), uncommented(string(wb)); g != w { + t.Fatalf("mismatch:\n--- got\n%s\n--- want\n%s", g, w) + } + if _, gotDoc, _ := strings.Cut(string(gb), "\n"); !strings.Contains(string(wb), strings.SplitN(gotDoc, "Puppet::Resource::ResourceType3", 2)[0]) { + t.Error("type doc comments differ from golden") + } + match++ + }) + } + t.Logf("%d/%d golden files match", match, len(want)) +} + +func TestScrub(t *testing.T) { + for _, c := range []struct{ in, want string }{ + {" one line \n\n", "one line"}, + {"First line\n indented\n more\n\n back ", "First line\nindented\n more\n\nback"}, + {"\n Lead\n blank\n \n end\n ", "\nLead\nblank\n\nend"}, + {"a\n\tb\n\t\tc", "a\nb\n\tc"}, + {"a\nb\n c", "a\nb\n c"}, + } { + if got := scrub(c.in); got != c.want { + t.Errorf("scrub(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +func TestRegexRender(t *testing.T) { + for _, c := range []struct { + re regex + puppet string + inspect string + }{ + {regex{"(.*)", "m"}, "/(?m-ix:(.*))/", "/(.*)/m"}, + {regex{"^a/b$", ""}, `/^a\/b$/`, `/^a\/b$/`}, + {regex{`^a\/b$`, ""}, `/^a\/b$/`, `/^a\/b$/`}, + {regex{`^(.*):([a-z]:(/|\\).*)$`, "i"}, `/(?i-mx:^(.*):([a-z]:(\/|\\).*)$)/`, `/^(.*):([a-z]:(\/|\\).*)$/i`}, + {regex{"x", "xim"}, "/(?mix:x)/", "/x/mix"}, + {regex{"", ""}, "//", "//"}, + } { + got, err := c.re.puppet() + if err != nil || got != c.puppet { + t.Errorf("%+v puppet = %q (%v), want %q", c.re, got, err, c.puppet) + } + if got := c.re.inspect(); got != c.inspect { + t.Errorf("%+v inspect = %q, want %q", c.re, got, c.inspect) + } + } + if _, err := (regex{"(?i:a)", "m"}).puppet(); err == nil { + t.Error("leading inline group with flags must be rejected") + } +} + +func TestQuote(t *testing.T) { + for in, want := range map[string]string{"name": "'name'", "it's": `'it\'s'`, `a\b`: `'a\b'`, `end\`: `'end\'`, "a\nb": `"a\nb"`, "": "''"} { + if got := quote(in); got != want { + t.Errorf("quote(%q) = %s, want %s", in, got, want) + } + } +} + +func typeOf(t *testing.T, body string) []string { + t.Helper() + types, err := parseFile("Puppet::Type.newtype(:t) do\n" + body + "\nend\n") + if err != nil { + t.Fatal(err) + } + var out []string + for _, a := range append(types[0].props, types[0].params...) { + typ, err := a.puppetType() + if err != nil { + t.Fatal(err) + } + out = append(out, a.name+" "+typ) + } + return out +} + +func TestPuppetTypeMapping(t *testing.T) { + for _, c := range []struct{ body, want string }{ + {"newparam(:a)", "a Any"}, + {"newproperty(:a) do\n newvalues(:x, 'y')\nend", "a Enum['x', 'y']"}, + {"newparam(:a, parent: Puppet::Parameter::Boolean)", "a Variant[Boolean, Enum['true', 'false', 'yes', 'no']]"}, + {"newproperty(:a, :parent => Puppet::Property::Boolean)", "a Any"}, + {"newparam(:a) do\n newvalues(true, false)\nend", "a Variant[Boolean, Enum['true', 'false']]"}, + {"newparam(:a) do\n newvalues(%r{^\\d+$}, :absent)\nend", `a Variant[Enum['absent'], Pattern[/^\d+$/]]`}, + {"newparam(:a) do\n newvalue(:x)\n aliasvalue(:y, :x)\n newvalue(:z)\nend", "a Enum['x', 'y', 'z']"}, + {"newparam(:a) do\n newvalues(:x, :y)\n newvalue(:x) { }\nend", "a Enum['x', 'y']"}, + {"newparam(:a) do\n newvalues(nil, '')\nend", "a Enum['', '']"}, + {"ensurable", "ensure Enum['present', 'absent']"}, + {"ensurable do\n defaultvalues\n newvalue(:latest)\nend", "ensure Enum['present', 'absent', 'latest']"}, + } { + if got := strings.Join(typeOf(t, c.body), "\n"); got != c.want { + t.Errorf("%s:\n got %s\nwant %s", c.body, got, c.want) + } + } +} + +func TestResourceAPIMapping(t *testing.T) { + for typ, want := range map[string]string{ + "String": "Pattern[//]", + "Optional[String[1]]": "Pattern[//]", + "Integer[0,65535]": `Pattern[/^-?\d+$/]`, + "Boolean": "Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']]", + "Enum[present, absent]": "Enum['absent', 'present']", + "Optional[Enum[a, b]]": "Any", + "Array[String]": "Any", + "Sensitive[String]": "Any", + "Optional[Numeric]": "Pattern[/" + strings.ReplaceAll(numericRe, "/", `\/`) + "/]", + "Variant[String, Undef]": "Any", + } { + a := &attr{} + rsapiValues(a, typ) + if got, _ := a.puppetType(); got != want { + t.Errorf("%s = %s, want %s", typ, got, want) + } + } +} + +func TestHeredocs(t *testing.T) { + for src, want := range map[string]string{ + "x = <<~EOT\n a\n b\n\n \tc #{'d'}\n EOT\n": "a\n b\n\n\tc #{'d'}\n", + "x = <<-EOT\n a\\tb\n EOT\n": " a\tb\n", + "x = <<-'EOT'\n a\\tb\n EOT\n": " a\\tb\n", + "x = < ['name']\n },\n true,\n false)\n", + } { + if !strings.Contains(out, want) { + t.Errorf("output missing %q:\n%s", want, out) + } + } +} + +func writeFile(t *testing.T, p, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +const simpleType = "Puppet::Type.newtype(:%s) do\n newparam(:name, namevar: true)\nend\n" + +func TestGenerateFiles(t *testing.T) { + env := t.TempDir() + cache := t.TempDir() + mod := filepath.Join(cache, "mods", "foo") + writeFile(t, filepath.Join(mod, "lib/puppet/type/foo.rb"), strings.ReplaceAll(simpleType, "%s", "foo")) + writeFile(t, filepath.Join(mod, "lib/puppet/provider/foo/posix.rb"), "") + writeFile(t, filepath.Join(env, "modules/bar/lib/puppet/type/bar.rb"), strings.ReplaceAll(simpleType, "%s", "bar")) + writeFile(t, filepath.Join(env, "site/bar/lib/puppet/type/shadowed.rb"), "not ruby (") + writeFile(t, filepath.Join(env, "environment.conf"), "# comment\nmodulepath = modules:site:$basemodulepath\n") + if err := os.Symlink(mod, filepath.Join(env, "modules/foo")); err != nil { + t.Fatal(err) + } + out := filepath.Join(env, OutDir) + writeFile(t, filepath.Join(out, "stale.pp"), "old") + writeFile(t, filepath.Join(out, "keepdir", "x"), "") + if err := os.Symlink("/etc/passwd", filepath.Join(out, "link.pp")); err != nil { + t.Fatal(err) + } + + if err := Generate(env, cache); err != nil { + t.Fatal(err) + } + if exists(filepath.Join(out, "stale.pp")) || !exists(filepath.Join(out, "keepdir")) || !exists(filepath.Join(out, "link.pp")) { + t.Fatal("cleanup must remove only stale regular files") + } + foo, err := os.ReadFile(filepath.Join(out, "foo.pp")) + if err != nil || !strings.Contains(string(foo), "'provider'") { + t.Fatalf("foo.pp via symlinked module with provider: %v\n%s", err, foo) + } + bar := filepath.Join(out, "bar.pp") + in, _ := os.Stat(filepath.Join(env, "modules/bar/lib/puppet/type/bar.rb")) + if fi, err := os.Stat(bar); err != nil || !fi.ModTime().Equal(in.ModTime()) || strings.Contains(readFile(t, bar), "provider") { + t.Fatalf("bar.pp must carry the input mtime and no provider param: %v", err) + } + + writeFile(t, bar, "edited") + if err := os.Chtimes(bar, in.ModTime(), in.ModTime()); err != nil { + t.Fatal(err) + } + if err := Generate(env, cache); err != nil { + t.Fatal(err) + } + if readFile(t, bar) != "edited" { + t.Fatal("output with the input's mtime is up to date and must be kept") + } + if err := os.Chtimes(bar, in.ModTime(), in.ModTime().Add(-time.Hour)); err != nil { + t.Fatal(err) + } + if err := Generate(env, cache); err != nil { + t.Fatal(err) + } + if readFile(t, bar) == "edited" { + t.Fatal("output with a different mtime must be regenerated") + } +} + +func exists(p string) bool { + _, err := os.Lstat(p) + return err == nil +} + +func readFile(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func TestGenerateErrors(t *testing.T) { + t.Run("bad input names the file and keeps going", func(t *testing.T) { + env := t.TempDir() + writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/bad.rb"), "Puppet::Type.newtype(:bad) do\n newparam(dynamic)\nend\n") + writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/good.rb"), strings.ReplaceAll(simpleType, "%s", "good")) + writeFile(t, filepath.Join(env, OutDir, "bad.pp"), "previous") + err := Generate(env) + if err == nil || !strings.Contains(err.Error(), "modules/m/lib/puppet/type/bad.rb") { + t.Fatalf("got %v", err) + } + if !exists(filepath.Join(env, OutDir, "good.pp")) || readFile(t, filepath.Join(env, OutDir, "bad.pp")) != "previous" { + t.Fatal("good inputs still generate; a failing input's old output is kept") + } + }) + t.Run("wrong type name", func(t *testing.T) { + env := t.TempDir() + writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/a.rb"), strings.ReplaceAll(simpleType, "%s", "b")) + if err := Generate(env); err == nil || !strings.Contains(err.Error(), `"a" was not defined`) { + t.Fatalf("got %v", err) + } + }) + t.Run("output dir symlink", func(t *testing.T) { + env := t.TempDir() + if err := os.Symlink(t.TempDir(), filepath.Join(env, OutDir)); err != nil { + t.Fatal(err) + } + if err := Generate(env); err == nil || !strings.Contains(err.Error(), "not a directory") { + t.Fatalf("got %v", err) + } + }) + t.Run("input outside roots", func(t *testing.T) { + env, outside := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(outside, "evil.rb"), strings.ReplaceAll(simpleType, "%s", "evil")) + if err := os.MkdirAll(filepath.Join(env, "modules/m/lib/puppet/type"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(outside, "evil.rb"), filepath.Join(env, "modules/m/lib/puppet/type/evil.rb")); err != nil { + t.Fatal(err) + } + if err := Generate(env); err == nil || !strings.Contains(err.Error(), "outside") { + t.Fatalf("got %v", err) + } + }) + t.Run("modulepath outside roots", func(t *testing.T) { + env := t.TempDir() + writeFile(t, filepath.Join(env, "environment.conf"), "modulepath = "+t.TempDir()+"\n") + if err := Generate(env); err == nil || !strings.Contains(err.Error(), "outside") { + t.Fatalf("got %v", err) + } + }) +} diff --git a/internal/gentypes/lexer.go b/internal/gentypes/lexer.go new file mode 100644 index 0000000..adde2df --- /dev/null +++ b/internal/gentypes/lexer.go @@ -0,0 +1,637 @@ +package gentypes + +import ( + "fmt" + "strconv" + "strings" +) + +type kind int + +const ( + tEOF kind = iota + tNL + tIdent + tConst + tIVar + tGVar + tSym + tLabel + tStr + tRegex + tWords + tNum + tOp +) + +type part struct { + text string + code bool +} + +type token struct { + kind kind + text string + parts []part + words []string + flags string + line int + space bool +} + +type lexer struct { + src string + pos int + line int + toks []token + pending []heredoc +} + +type heredoc struct { + tok int + id string + squig bool + indent bool + raw bool +} + +func lex(src string) ([]token, error) { + l := &lexer{src: src, line: 1} + if err := l.run(); err != nil { + return nil, fmt.Errorf("line %d: %w", l.line, err) + } + l.toks = append(l.toks, token{kind: tEOF, line: l.line}) + return l.toks, nil +} + +func isIdentStart(c byte) bool { + return c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= 0x80 +} + +func isIdentChar(c byte) bool { return isIdentStart(c) || c >= '0' && c <= '9' } + +func (l *lexer) peek(off int) byte { + if l.pos+off < len(l.src) { + return l.src[l.pos+off] + } + return 0 +} + +func (l *lexer) emit(t token) { + t.line = l.line + l.toks = append(l.toks, t) +} + +func (l *lexer) last() *token { + if len(l.toks) == 0 { + return nil + } + return &l.toks[len(l.toks)-1] +} + +var keywords = map[string]bool{ + "if": true, "unless": true, "while": true, "until": true, "and": true, "or": true, "not": true, + "return": true, "when": true, "then": true, "else": true, "elsif": true, "do": true, "in": true, + "case": true, "begin": true, "yield": true, +} + +// valueBefore reports whether the previous token ends an operand, which decides /, % and << ambiguity. +func (l *lexer) valueBefore() bool { + t := l.last() + if t == nil { + return false + } + switch t.kind { + case tIdent: + return !keywords[t.text] + case tConst, tIVar, tGVar, tNum, tStr, tSym, tRegex, tWords: + return true + case tOp: + return t.text == ")" || t.text == "]" || t.text == "}" + } + return false +} + +// literalStart decides whether an ambiguous operator char starts a literal. +func (l *lexer) literalStart(space bool, oplen int) bool { + if !l.valueBefore() { + return true + } + t := l.last() + next := l.peek(oplen) + return t.kind == tIdent && space && next != ' ' && next != '=' && next != '\n' +} + +func (l *lexer) run() error { + space := false + for l.pos < len(l.src) { + c := l.src[l.pos] + atBOL := l.pos == 0 || l.src[l.pos-1] == '\n' + switch { + case c == ' ' || c == '\t' || c == '\r': + l.pos++ + space = true + continue + case c == '\\' && l.peek(1) == '\n': + l.pos += 2 + l.line++ + space = true + continue + case c == '\n': + l.pos++ + l.emit(token{kind: tNL}) + l.line++ + if err := l.readHeredocs(); err != nil { + return err + } + space = false + continue + case c == '#': + for l.pos < len(l.src) && l.src[l.pos] != '\n' { + l.pos++ + } + continue + case atBOL && strings.HasPrefix(l.src[l.pos:], "=begin"): + end := strings.Index(l.src[l.pos:], "\n=end") + if end < 0 { + return fmt.Errorf("unterminated =begin") + } + l.line += strings.Count(l.src[l.pos:l.pos+end+5], "\n") + l.pos += end + 5 + for l.pos < len(l.src) && l.src[l.pos] != '\n' { + l.pos++ + } + continue + case atBOL && strings.HasPrefix(l.src[l.pos:], "__END__") && (l.peek(7) == '\n' || l.peek(7) == 0): + l.pos = len(l.src) + continue + } + start := len(l.toks) + if err := l.next(space); err != nil { + return err + } + if len(l.toks) > start { + l.toks[start].space = space + } + space = false + } + if len(l.pending) > 0 { + return fmt.Errorf("unterminated heredoc %s", l.pending[0].id) + } + return nil +} + +func (l *lexer) next(space bool) error { + c := l.src[l.pos] + switch { + case c >= '0' && c <= '9': + s := l.pos + for l.pos < len(l.src) && (isIdentChar(l.src[l.pos]) || l.src[l.pos] == '.' && l.peek(1) >= '0' && l.peek(1) <= '9') { + l.pos++ + } + l.emit(token{kind: tNum, text: l.src[s:l.pos]}) + case isIdentStart(c): + s := l.pos + for l.pos < len(l.src) && isIdentChar(l.src[l.pos]) { + l.pos++ + } + if (l.peek(0) == '?' || l.peek(0) == '!') && l.peek(1) != '=' { + l.pos++ + } + word := l.src[s:l.pos] + if l.peek(0) == ':' && l.peek(1) != ':' { + if t := l.last(); t == nil || t.kind != tOp || t.text != "?" { + l.pos++ + l.emit(token{kind: tLabel, text: word}) + return nil + } + } + if c >= 'A' && c <= 'Z' { + l.emit(token{kind: tConst, text: word}) + } else { + l.emit(token{kind: tIdent, text: word}) + } + case c == '@' || c == '$': + s := l.pos + l.pos++ + if c == '@' && l.peek(0) == '@' { + l.pos++ + } + if c == '$' && !isIdentStart(l.peek(0)) { + l.pos++ + } + for l.pos < len(l.src) && isIdentChar(l.src[l.pos]) { + l.pos++ + } + k := tIVar + if c == '$' { + k = tGVar + } + l.emit(token{kind: k, text: l.src[s:l.pos]}) + case c == ':' && l.peek(1) == ':': + l.pos += 2 + l.emit(token{kind: tOp, text: "::"}) + case c == ':' && (l.peek(1) == '"' || l.peek(1) == '\''): + l.pos++ + parts, err := l.quoted(l.src[l.pos], l.src[l.pos], l.src[l.pos] == '"') + if err != nil { + return err + } + l.emit(token{kind: tSym, parts: parts}) + case c == ':' && isIdentStart(l.peek(1)): + l.pos++ + s := l.pos + for l.pos < len(l.src) && isIdentChar(l.src[l.pos]) { + l.pos++ + } + if c := l.peek(0); (c == '?' || c == '!' || c == '=') && l.peek(1) != '=' && l.peek(1) != '>' { + l.pos++ + } + l.emit(token{kind: tSym, text: l.src[s:l.pos]}) + case c == '"' || c == '\'' || c == '`': + parts, err := l.quoted(c, c, c != '\'') + if err != nil { + return err + } + l.emit(token{kind: tStr, parts: parts}) + case c == '/' && l.literalStart(space, 1): + return l.regex('/', '/') + case c == '%' && l.literalStart(space, 1) && l.percentLiteral(): + return l.percent() + case c == '<' && l.peek(1) == '<' && l.literalStart(space, 2) && l.heredocStart(): + return l.heredocHead() + default: + for _, op := range []string{"**=", "<=>", "===", "...", "||=", "&&=", "<<=", ">>=", "==", "!=", ">=", "<=", "&&", "||", "<<", ">>", "**", "=>", "->", "..", "+=", "-=", "*=", "/=", "%=", "|=", "&=", "=~", "!~", "&."} { + if strings.HasPrefix(l.src[l.pos:], op) { + l.pos += len(op) + l.emit(token{kind: tOp, text: op}) + return nil + } + } + l.pos++ + l.emit(token{kind: tOp, text: string(c)}) + } + return nil +} + +func closer(open byte) byte { + switch open { + case '(': + return ')' + case '[': + return ']' + case '{': + return '}' + case '<': + return '>' + } + return open +} + +func (l *lexer) percentLiteral() bool { + c := l.peek(1) + if strings.IndexByte("qQwWiIrs", c) >= 0 { + d := l.peek(2) + return d != 0 && !isIdentChar(d) && d != ' ' && d != '\n' + } + return c == '(' || c == '[' || c == '{' || c == '<' || c == '|' || c == '!' +} + +func (l *lexer) percent() error { + l.pos++ + typ := byte('Q') + if c := l.peek(0); isIdentStart(c) { + typ = c + l.pos++ + } + open := l.src[l.pos] + cl := closer(open) + switch typ { + case 'r': + return l.regex(open, cl) + case 'w', 'W', 'i', 'I': + parts, err := l.quoted(open, cl, false) + if err != nil { + return err + } + var body string + for _, p := range parts { + body += p.text + } + l.emit(token{kind: tWords, words: strings.Fields(body)}) + case 's': + parts, err := l.quoted(open, cl, false) + if err != nil { + return err + } + l.emit(token{kind: tSym, parts: parts}) + case 'q': + parts, err := l.quoted(open, cl, false) + if err != nil { + return err + } + l.emit(token{kind: tStr, parts: parts}) + default: + parts, err := l.quoted(open, cl, true) + if err != nil { + return err + } + l.emit(token{kind: tStr, parts: parts}) + } + return nil +} + +// scan reads a delimited body starting at the opening delimiter, returning raw text with nesting and #{} honoured. +func (l *lexer) scan(open, cl byte, interp bool) (string, error) { + l.pos++ + s := l.pos + depth := 0 + for l.pos < len(l.src) { + c := l.src[l.pos] + switch { + case c == '\\': + l.pos += 2 + continue + case interp && c == '#' && l.peek(1) == '{': + l.pos++ + if _, err := l.scan('{', '}', true); err != nil { + return "", err + } + continue + case c == cl && depth == 0: + body := l.src[s:l.pos] + l.pos++ + l.line += strings.Count(body, "\n") + return body, nil + case c == cl: + depth-- + case c == open && open != cl: + depth++ + } + l.pos++ + } + return "", fmt.Errorf("unterminated literal") +} + +func (l *lexer) quoted(open, cl byte, dq bool) ([]part, error) { + body, err := l.scan(open, cl, dq) + if err != nil { + return nil, err + } + if !dq { + return []part{{text: unescapeSingle(body, open, cl)}}, nil + } + return splitInterp(body) +} + +func unescapeSingle(s string, open, cl byte) string { + var b strings.Builder + for i := 0; i < len(s); i++ { + if s[i] == '\\' && i+1 < len(s) && (s[i+1] == '\\' || s[i+1] == open || s[i+1] == cl) { + i++ + } + b.WriteByte(s[i]) + } + return b.String() +} + +func splitInterp(body string) ([]part, error) { + var parts []part + var b strings.Builder + for i := 0; i < len(body); i++ { + c := body[i] + if c == '#' && i+1 < len(body) && body[i+1] == '{' { + depth, j := 0, i+1 + for ; j < len(body); j++ { + if body[j] == '{' { + depth++ + } else if body[j] == '}' { + depth-- + if depth == 0 { + break + } + } + } + if j >= len(body) { + return nil, fmt.Errorf("unterminated interpolation") + } + if b.Len() > 0 { + parts = append(parts, part{text: b.String()}) + b.Reset() + } + parts = append(parts, part{text: strings.TrimSpace(body[i+2 : j]), code: true}) + i = j + continue + } + if c == '#' && i+1 < len(body) && (body[i+1] == '@' || body[i+1] == '$') { + parts = append(parts, part{text: body[i:], code: true}) + break + } + if c != '\\' || i+1 >= len(body) { + b.WriteByte(c) + continue + } + i++ + switch e := body[i]; e { + case 'n': + b.WriteByte('\n') + case 't': + b.WriteByte('\t') + case 's': + b.WriteByte(' ') + case 'r': + b.WriteByte('\r') + case '0': + b.WriteByte(0) + case 'e': + b.WriteByte(0x1b) + case 'a': + b.WriteByte(7) + case 'b': + b.WriteByte(8) + case 'f': + b.WriteByte('\f') + case 'v': + b.WriteByte('\v') + case '\n': + case 'u': + hex := "" + if i+1 < len(body) && body[i+1] == '{' { + end := strings.IndexByte(body[i:], '}') + if end < 0 { + return nil, fmt.Errorf("bad \\u escape") + } + hex, i = body[i+2:i+end], i+end + } else if i+4 < len(body) { + hex, i = body[i+1:i+5], i+4 + } + r, err := strconv.ParseUint(hex, 16, 32) + if err != nil { + return nil, fmt.Errorf("bad \\u escape") + } + b.WriteString(string(rune(r))) + case 'x': + if i+2 >= len(body) { + return nil, fmt.Errorf("bad \\x escape") + } + r, err := strconv.ParseUint(body[i+1:i+3], 16, 8) + if err != nil { + return nil, fmt.Errorf("bad \\x escape") + } + b.WriteByte(byte(r)) + i += 2 + default: + b.WriteByte(e) + } + } + if b.Len() > 0 || len(parts) == 0 { + parts = append(parts, part{text: b.String()}) + } + return parts, nil +} + +func (l *lexer) regex(open, cl byte) error { + body, err := l.scan(open, cl, true) + if err != nil { + return err + } + if open == '/' { + body = strings.ReplaceAll(body, `\/`, "/") + } + s := l.pos + for l.pos < len(l.src) && strings.IndexByte("mixounse", l.src[l.pos]) >= 0 { + l.pos++ + } + l.emit(token{kind: tRegex, text: body, flags: l.src[s:l.pos]}) + return nil +} + +func (l *lexer) heredocStart() bool { + i := 2 + if c := l.peek(i); c == '-' || c == '~' { + i++ + } + c := l.peek(i) + return c == '\'' || c == '"' || isIdentStart(c) +} + +func (l *lexer) heredocHead() error { + l.pos += 2 + h := heredoc{tok: len(l.toks)} + switch l.peek(0) { + case '-': + h.indent = true + l.pos++ + case '~': + h.indent, h.squig = true, true + l.pos++ + } + if q := l.peek(0); q == '\'' || q == '"' { + end := strings.IndexByte(l.src[l.pos+1:], q) + if end < 0 { + return fmt.Errorf("bad heredoc identifier") + } + h.id, h.raw = l.src[l.pos+1:l.pos+1+end], q == '\'' + l.pos += end + 2 + } else { + s := l.pos + for l.pos < len(l.src) && isIdentChar(l.src[l.pos]) { + l.pos++ + } + h.id = l.src[s:l.pos] + } + l.pending = append(l.pending, h) + l.emit(token{kind: tStr}) + return nil +} + +func (l *lexer) readHeredocs() error { + for _, h := range l.pending { + var lines []string + for { + if l.pos >= len(l.src) { + return fmt.Errorf("unterminated heredoc %s", h.id) + } + end := strings.IndexByte(l.src[l.pos:], '\n') + var line string + if end < 0 { + line, l.pos = l.src[l.pos:], len(l.src) + } else { + line, l.pos = l.src[l.pos:l.pos+end], l.pos+end+1 + } + l.line++ + term := strings.TrimRight(line, "\r") + if h.indent { + term = strings.TrimLeft(term, " \t") + } + if term == h.id { + break + } + lines = append(lines, line+"\n") + } + if h.squig { + lines = dedent(lines) + } + body := strings.Join(lines, "") + if h.raw { + l.toks[h.tok].parts = []part{{text: body}} + continue + } + parts, err := splitInterp(body) + if err != nil { + return err + } + l.toks[h.tok].parts = parts + } + l.pending = nil + return nil +} + +func indentWidth(s string) (width, n int) { + for n < len(s) { + switch s[n] { + case ' ': + width++ + case '\t': + width = width/8*8 + 8 + default: + return width, n + } + n++ + } + return width, n +} + +// dedent applies <<~ semantics: strip the smallest indent of non-blank lines from every line. +func dedent(lines []string) []string { + min := -1 + for _, ln := range lines { + if strings.TrimSpace(ln) == "" { + continue + } + if w, _ := indentWidth(ln); min < 0 || w < min { + min = w + } + } + if min <= 0 { + return lines + } + out := make([]string, len(lines)) + for i, ln := range lines { + w, n := 0, 0 + for n < len(ln) && w < min && (ln[n] == ' ' || ln[n] == '\t') { + if ln[n] == '\t' { + nw := w/8*8 + 8 + if nw > min { + break + } + w = nw + } else { + w++ + } + n++ + } + out[i] = ln[n:] + } + return out +} diff --git a/internal/gentypes/parse.go b/internal/gentypes/parse.go new file mode 100644 index 0000000..e9adf70 --- /dev/null +++ b/internal/gentypes/parse.go @@ -0,0 +1,1144 @@ +package gentypes + +import ( + "fmt" + "regexp" + "slices" + "strings" +) + +type regex struct{ src, flags string } + +type value struct { + name string + re *regex + aliases []string +} + +type attr struct { + name string + doc string + namevar bool + features []string + values []*value + strs []*value + res []*value + ensure bool + defaults bool +} + +type pattern struct { + re regex + names []string +} + +type rtype struct { + name string + doc string + props []*attr + params []*attr + patterns []pattern + custom bool + rsapi bool +} + +type vkind int + +const ( + vStr vkind = iota + vSym + vRegex + vNum + vTrue + vFalse + vNil + vArray + vHash + vConst +) + +type rval struct { + k vkind + s string + re regex + arr []rval + keys []rval +} + +func (v rval) get(key string) (rval, bool) { + for i, k := range v.keys { + if (k.k == vSym || k.k == vStr) && k.s == key { + return v.arr[i], true + } + } + return rval{}, false +} + +type parser struct { + toks []token + i int + consts map[string]rval + used map[int]bool + types []*rtype +} + +var watched = map[string]bool{ + "newtype": true, "register_type": true, "newparam": true, "newproperty": true, "ensurable": true, + "newvalue": true, "newvalues": true, "aliasvalue": true, "isnamevar": true, "title_patterns": true, + "defaultvalues": true, "providify": true, +} + +func parseFile(src string) ([]*rtype, error) { + toks, err := lex(src) + if err != nil { + return nil, err + } + p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}} + if err := p.body("", p.topStmt); err != nil { + return nil, p.wrap(err) + } + for i, t := range p.toks { + if t.kind == tIdent && t.text == "def" && (i == 0 || p.toks[i-1].text != ".") { + p.i = i + p.skipStatement() + for j := i; j < p.i; j++ { + p.used[j] = true + } + } + } + for i, t := range p.toks { + dsl := t.kind == tIdent && watched[t.text] || t.kind == tIVar && t.text == "@isomorphic" + if p.used[i] || !dsl { + continue + } + var prev *token + if i > 0 { + prev = &p.toks[i-1] + } + next := p.toks[i+1] + dot := prev != nil && prev.kind == tOp && (prev.text == "." || prev.text == "&.") + local := next.kind == tOp && strings.Contains(" . &. = += ||= == [ ) , ", " "+next.text+" ") + if t.kind == tIVar || dot || (stmtStart(prev) || prev.kind == tOp && (prev.text == "{" || prev.text == "|")) && !local { + return nil, fmt.Errorf("line %d: unsupported use of %s", t.line, t.text) + } + } + return p.types, nil +} + +func (p *parser) wrap(err error) error { + if strings.HasPrefix(err.Error(), "line ") { + return err + } + return fmt.Errorf("line %d: %w", p.cur().line, err) +} + +func (p *parser) cur() token { return p.toks[p.i] } + +func (p *parser) at(off int) token { + if p.i+off < len(p.toks) { + return p.toks[p.i+off] + } + return p.toks[len(p.toks)-1] +} + +func (p *parser) is(k kind, text string) bool { + t := p.cur() + return t.kind == k && t.text == text +} + +func (p *parser) op(text string) bool { return p.is(tOp, text) } + +func (p *parser) take() token { + t := p.toks[p.i] + if t.kind != tEOF { + p.i++ + } + return t +} + +func (p *parser) expect(text string) error { + if !p.op(text) { + return fmt.Errorf("expected %q, found %s", text, describe(p.cur())) + } + p.i++ + return nil +} + +func (p *parser) skipNL() { + for p.cur().kind == tNL || p.op(";") { + p.i++ + } +} + +func describe(t token) string { + switch t.kind { + case tEOF: + return "end of file" + case tNL: + return "newline" + case tStr: + return "string" + case tRegex: + return "regex" + } + return fmt.Sprintf("%q", t.text) +} + +func (p *parser) closes(closeTok string) bool { + switch closeTok { + case "end": + return p.is(tIdent, "end") + case "}": + return p.op("}") + } + return p.cur().kind == tEOF +} + +// body runs stmt for every statement until closeTok ("end", "}" or "" for EOF), skipping statements it declines. +func (p *parser) body(closeTok string, stmt func() (bool, error)) error { + for { + p.skipNL() + if p.closes(closeTok) { + p.take() + return nil + } + if p.cur().kind == tEOF { + return fmt.Errorf("unexpected end of file, missing %q", closeTok) + } + start := p.cur() + ok, err := stmt() + if err != nil { + return err + } + if !ok { + p.skipStatement() + continue + } + if t := p.cur(); t.kind != tNL && !p.op(";") && !p.closes(closeTok) { + return fmt.Errorf("unsupported %s after %s", describe(t), describe(start)) + } + } +} + +func stmtStart(t *token) bool { + if t == nil { + return true + } + switch t.kind { + case tNL: + return true + case tOp: + return t.text != ")" && t.text != "]" && t.text != "}" + case tIdent: + return t.text == "then" || t.text == "do" || t.text == "else" || t.text == "begin" + } + return false +} + +func continues(prev token) bool { + return prev.kind == tOp && !strings.Contains(")]}|", prev.text) +} + +// skipStatement consumes one statement of arbitrary Ruby, tracking bracket and keyword nesting. +func (p *parser) skipStatement() { + depth, loop := 0, false + for { + t := p.cur() + var prev *token + if p.i > 0 { + prev = &p.toks[p.i-1] + } + afterDot := prev != nil && prev.kind == tOp && (prev.text == "." || prev.text == "&." || prev.text == "::") + switch { + case t.kind == tEOF: + return + case t.kind == tNL || t.kind == tOp && t.text == ";": + loop = false + if depth == 0 { + next := p.at(1) + if t.kind == tNL && (prev != nil && continues(*prev) || next.kind == tOp && (next.text == "." || next.text == "&.")) { + break + } + return + } + case t.kind == tOp && strings.Contains("([{", t.text): + depth++ + case t.kind == tOp && strings.Contains(")]}", t.text): + if depth == 0 { + return + } + depth-- + case t.kind == tIdent && !afterDot: + switch t.text { + case "end": + if depth == 0 { + return + } + depth-- + case "do": + if loop { + loop = false + } else { + depth++ + } + case "def", "class", "module", "begin", "case": + depth++ + case "for": + depth++ + loop = true + case "if", "unless", "while", "until": + if stmtStart(prev) { + depth++ + loop = t.text == "while" || t.text == "until" + } + } + } + p.i++ + } +} + +func (p *parser) constAssign() (bool, error) { + save := p.i + name := p.take().text + p.take() + v, err := p.expr() + if err != nil || p.cur().kind != tNL && p.cur().kind != tEOF && !p.op(";") { + p.i = save + return false, nil + } + p.consts[name] = v + return true, nil +} + +func (p *parser) topStmt() (bool, error) { + t := p.cur() + switch { + case t.kind == tIdent && t.text == "module": + p.take() + for p.cur().kind == tConst || p.op("::") { + p.take() + } + return true, p.body("end", p.topStmt) + case t.kind == tConst && p.methodCall("newtype"): + return true, p.newtype() + case t.kind == tConst && p.methodCall("register_type"): + return true, p.registerType() + case t.kind == tConst && p.at(1).kind == tOp && p.at(1).text == "=": + return p.constAssign() + } + return false, nil +} + +// methodCall matches Const(::Const)*.name at the cursor and advances past the name. +func (p *parser) methodCall(name string) bool { + j := 0 + for p.at(j).kind == tConst && p.at(j+1).kind == tOp && p.at(j+1).text == "::" { + j += 2 + } + if p.at(j).kind != tConst || p.at(j+1).kind != tOp || p.at(j+1).text != "." || p.at(j+2).kind != tIdent || p.at(j+2).text != name { + return false + } + j += p.i + recv := "" + for k := p.i; k <= j; k++ { + recv += p.toks[k].text + } + if (name == "newtype" && recv != "Puppet::Type" && recv != "Type") || (name == "register_type" && recv != "Puppet::ResourceApi") { + return false + } + p.used[j+2] = true + p.i = j + 3 + return true +} + +func symName(v rval) (string, error) { + switch v.k { + case vSym, vStr: + return v.s, nil + } + return "", fmt.Errorf("expected a symbol or string, found %s", v.kindName()) +} + +func (v rval) kindName() string { + return [...]string{"string", "symbol", "regex", "number", "true", "false", "nil", "array", "hash", "constant " + v.s}[v.k] +} + +func (p *parser) newtype() error { + args, err := p.args() + if err != nil { + return err + } + if len(args) != 1 { + return fmt.Errorf("newtype with options is not supported") + } + name, err := symName(args[0]) + if err != nil { + return err + } + t := &rtype{name: name} + p.types = append(p.types, t) + closeTok, err := p.blockOpen() + if err != nil { + return err + } + if closeTok == "" { + return fmt.Errorf("newtype without a block") + } + return p.body(closeTok, func() (bool, error) { return p.typeStmt(t) }) +} + +func (p *parser) blockOpen() (string, error) { + switch { + case p.is(tIdent, "do"): + p.take() + case p.op("{"): + p.take() + p.skipNL() + if p.op("|") { + return "", fmt.Errorf("unsupported block parameters") + } + return "}", nil + default: + return "", nil + } + if p.op("|") { + return "", fmt.Errorf("unsupported block parameters") + } + return "end", nil +} + +func (p *parser) docExpr() (string, error) { + v, err := p.expr() + if err != nil { + return "", err + } + if v.k != vStr { + return "", fmt.Errorf("doc must be a string literal, found %s", v.kindName()) + } + return v.s, nil +} + +func (p *parser) docStmt(doc *string) (bool, error) { + switch { + case p.is(tIdent, "desc"): + p.take() + args, err := p.args() + if err != nil { + return true, err + } + if len(args) != 1 || args[0].k != vStr { + return true, fmt.Errorf("desc must take one string literal") + } + *doc = args[0].s + return true, nil + case p.is(tIVar, "@doc") && p.at(1).kind == tOp && p.at(1).text == "=": + p.i += 2 + s, err := p.docExpr() + *doc = s + return true, err + } + return false, nil +} + +func (p *parser) typeStmt(t *rtype) (bool, error) { + if ok, err := p.docStmt(&t.doc); ok || err != nil { + return ok, err + } + c := p.cur() + switch { + case c.kind == tIdent && (c.text == "newparam" || c.text == "newproperty"): + p.used[p.i] = true + p.take() + return true, p.newattr(t, c.text == "newproperty") + case c.kind == tIdent && c.text == "ensurable": + p.used[p.i] = true + p.take() + a := &attr{name: "ensure", ensure: true} + closeTok, err := p.blockOpen() + if err != nil { + return true, err + } + if closeTok == "" { + a.defaultValues() + } else if err := p.body(closeTok, func() (bool, error) { return p.attrStmt(a) }); err != nil { + return true, err + } + t.addProp(a) + return true, nil + case c.kind == tIdent && c.text == "def" && p.at(1).kind == tIdent && p.at(1).text == "self" && p.at(2).text == "." && p.at(3).text == "title_patterns": + p.used[p.i+3] = true + p.i += 4 + return true, p.titlePatterns(t) + case c.kind == tConst && p.at(1).kind == tOp && p.at(1).text == "=": + return p.constAssign() + } + return false, nil +} + +func (t *rtype) addProp(a *attr) { + if a.name == "ensure" { + t.props = append([]*attr{a}, t.props...) + return + } + t.props = append(t.props, a) +} + +var parents = map[string][]string{ + "Puppet::Parameter::Boolean": {"true", "false", "yes", "no"}, + "Puppet::Property::Boolean": nil, + "Puppet::Parameter::Path": nil, + "Puppet::Property::Ensure": nil, + "Puppet::Type::File::Owner": nil, + "Puppet::Type::File::Group": nil, + "Puppet::Type::File::Mode": nil, +} + +func (p *parser) newattr(t *rtype, property bool) error { + args, err := p.args() + if err != nil { + return err + } + if len(args) == 0 { + return fmt.Errorf("attribute without a name") + } + name, err := symName(args[0]) + if err != nil { + return err + } + a := &attr{name: name} + if len(args) > 2 || len(args) == 2 && args[1].k != vHash { + return fmt.Errorf("attribute %s: unsupported arguments", name) + } + if len(args) == 2 { + opts := args[1] + if v, ok := opts.get("parent"); ok { + vals, known := parents[v.s] + if v.k != vConst || !known { + return fmt.Errorf("attribute %s: unsupported parent %s", name, v.s) + } + a.ensure = v.s == "Puppet::Property::Ensure" + for _, s := range vals { + a.addValue(s, nil) + } + } + if v, ok := opts.get("namevar"); ok && !property { + a.namevar = v.k != vFalse && v.k != vNil + } + if v, ok := opts.get("required_features"); ok { + if a.features, err = features(v); err != nil { + return fmt.Errorf("attribute %s: %w", name, err) + } + } + } + closeTok, err := p.blockOpen() + if err != nil { + return err + } + if closeTok != "" { + if err := p.body(closeTok, func() (bool, error) { return p.attrStmt(a) }); err != nil { + return err + } + } + if property { + t.addProp(a) + } else { + t.params = append(t.params, a) + } + return nil +} + +func features(v rval) ([]string, error) { + var out []string + var walk func(rval) error + walk = func(v rval) error { + switch v.k { + case vArray: + for _, e := range v.arr { + if err := walk(e); err != nil { + return err + } + } + case vStr, vSym: + out = append(out, strings.ToLower(v.s)) + default: + return fmt.Errorf("unsupported required_features %s", v.kindName()) + } + return nil + } + return out, walk(v) +} + +func valueName(v rval) (string, *regex, error) { + switch v.k { + case vStr: + if v.s == "" { + return "\x00", nil, nil + } + return v.s, nil, nil + case vSym, vNum, vNil: + return v.s, nil, nil + case vTrue: + return "true", nil, nil + case vFalse: + return "false", nil, nil + case vRegex: + re := v.re + return "", &re, nil + } + return "", nil, fmt.Errorf("unsupported value %s", v.kindName()) +} + +func (a *attr) defaultValues() { + a.addValue("present", nil) + a.addValue("absent", nil) + a.defaults = true +} + +func (a *attr) addValue(name string, re *regex) { + v := &value{name: name, re: re} + if re != nil { + a.res = append(a.res, v) + } else { + a.strs = append(a.strs, v) + } + for i, old := range a.values { + if old.re == nil && re == nil && old.name == name || old.re != nil && re != nil && *old.re == *re { + a.values[i] = v + return + } + } + a.values = append(a.values, v) +} + +func (p *parser) attrStmt(a *attr) (bool, error) { + if ok, err := p.docStmt(&a.doc); ok || err != nil { + return ok, err + } + c := p.cur() + if c.kind == tConst && p.at(1).kind == tOp && p.at(1).text == "=" { + return p.constAssign() + } + if c.kind != tIdent || !watched[c.text] { + return false, nil + } + p.used[p.i] = true + p.take() + switch c.text { + case "isnamevar": + a.namevar = true + return true, nil + case "defaultvalues": + if !a.ensure { + return true, fmt.Errorf("defaultvalues outside ensure") + } + a.defaultValues() + return true, nil + case "newvalue", "newvalues": + args, err := p.args() + if err != nil { + return true, err + } + if c.text == "newvalue" && (len(args) == 0 || len(args) > 2 || len(args) == 2 && args[1].k != vHash) { + return true, fmt.Errorf("unsupported newvalue arguments") + } + if c.text == "newvalue" { + args = args[:1] + } + for _, v := range args { + name, re, err := valueName(v) + if err != nil { + return true, err + } + a.addValue(name, re) + } + if p.is(tIdent, "do") || p.op("{") { + p.skipStatement() + } + return true, nil + case "aliasvalue": + args, err := p.args() + if err != nil { + return true, err + } + if len(args) != 2 { + return true, fmt.Errorf("aliasvalue takes two arguments") + } + alias, _, err := valueName(args[0]) + if err != nil { + return true, err + } + target, _, err := valueName(args[1]) + if err != nil { + return true, err + } + for _, v := range a.strs { + if v.name == target || slices.Contains(v.aliases, target) { + v.aliases = append(v.aliases, alias) + return true, nil + } + } + return true, fmt.Errorf("aliasvalue %s: no such value %s", alias, target) + } + return true, fmt.Errorf("unsupported %s inside an attribute", c.text) +} + +func (p *parser) titlePatterns(t *rtype) error { + if p.op("(") { + if err := p.expect("("); err != nil { + return err + } + if err := p.expect(")"); err != nil { + return err + } + } + p.skipNL() + v, err := p.expr() + if err != nil { + return fmt.Errorf("title_patterns: %w", err) + } + p.skipNL() + if !p.is(tIdent, "end") { + return fmt.Errorf("title_patterns must return a single literal array") + } + p.take() + if v.k != vArray { + return fmt.Errorf("title_patterns must return a literal array") + } + t.custom = true + for _, e := range v.arr { + if e.k != vArray || len(e.arr) != 2 || e.arr[0].k != vRegex || e.arr[1].k != vArray { + return fmt.Errorf("title_patterns entries must be [regex, [[:attr], ...]]") + } + pt := pattern{re: e.arr[0].re} + for _, n := range e.arr[1].arr { + if n.k != vArray || len(n.arr) != 1 { + return fmt.Errorf("title patterns that use procs are not supported") + } + s, err := symName(n.arr[0]) + if err != nil { + return err + } + pt.names = append(pt.names, s) + } + t.patterns = append(t.patterns, pt) + } + return nil +} + +// args parses call arguments in parens or bare up to a newline or block opener; trailing key: value pairs form one hash. +func (p *parser) args() ([]rval, error) { + paren := p.op("(") && !p.cur().space + if paren { + p.take() + } else if t := p.cur(); t.kind == tNL || t.kind == tEOF || p.op(";") || p.is(tIdent, "do") || p.op("{") || p.is(tIdent, "end") || p.op("}") || p.op(")") { + return nil, nil + } + var out []rval + var hash *rval + for { + if paren { + p.skipNL() + if p.op(")") { + p.take() + break + } + } + switch { + case p.cur().kind == tLabel: + k := rval{k: vSym, s: p.take().text} + if paren { + p.skipNL() + } + v, err := p.expr() + if err != nil { + return nil, err + } + if hash == nil { + out = append(out, rval{k: vHash}) + hash = &out[len(out)-1] + } + hash.keys, hash.arr = append(hash.keys, k), append(hash.arr, v) + case p.op("*"): + p.take() + v, err := p.expr() + if err != nil { + return nil, err + } + if v.k != vArray { + return nil, fmt.Errorf("splat of %s", v.kindName()) + } + out = append(out, v.arr...) + default: + v, err := p.expr() + if err != nil { + return nil, err + } + if p.op("=>") { + p.take() + if paren { + p.skipNL() + } + val, err := p.expr() + if err != nil { + return nil, err + } + if hash == nil { + out = append(out, rval{k: vHash}) + hash = &out[len(out)-1] + } + hash.keys, hash.arr = append(hash.keys, v), append(hash.arr, val) + } else { + out = append(out, v) + } + } + if paren { + p.skipNL() + } + if p.op(",") { + p.take() + if !paren && p.cur().kind == tNL { + p.skipNL() + } + continue + } + if paren { + if err := p.expect(")"); err != nil { + return nil, err + } + } + break + } + return out, nil +} + +func (p *parser) expr() (rval, error) { + v, err := p.primary() + if err != nil { + return v, err + } + for { + switch { + case p.op(".") && p.at(1).kind == tIdent && p.at(1).text == "freeze": + p.i += 2 + case v.k == vStr && p.cur().kind == tStr: + w, err := p.primary() + if err != nil { + return v, err + } + v.s += w.s + case v.k == vStr && p.op("+"): + p.take() + p.skipNL() + w, err := p.primary() + if err != nil { + return v, err + } + if w.k != vStr { + return v, fmt.Errorf("string + %s", w.kindName()) + } + v.s += w.s + default: + return v, nil + } + } +} + +func (p *parser) interp(parts []part) (string, error) { + var b strings.Builder + for _, pt := range parts { + if !pt.code { + b.WriteString(pt.text) + continue + } + toks, err := lex(pt.text) + if err != nil { + return "", fmt.Errorf("unsupported interpolation #{%s}", pt.text) + } + sub := &parser{toks: toks, consts: p.consts, used: map[int]bool{}} + c, err := sub.expr() + sub.skipNL() + if err != nil || c.k != vStr || sub.cur().kind != tEOF { + return "", fmt.Errorf("unsupported interpolation #{%s}", pt.text) + } + b.WriteString(c.s) + } + return b.String(), nil +} + +func (p *parser) primary() (rval, error) { + t := p.cur() + switch t.kind { + case tStr: + p.take() + s, err := p.interp(t.parts) + return rval{k: vStr, s: s}, err + case tSym: + p.take() + if t.parts != nil { + s, err := p.interp(t.parts) + return rval{k: vSym, s: s}, err + } + return rval{k: vSym, s: t.text}, nil + case tRegex: + p.take() + if strings.Contains(t.text, "#{") { + return rval{}, fmt.Errorf("unsupported interpolation in regex") + } + return rval{k: vRegex, re: regex{t.text, t.flags}}, nil + case tWords: + p.take() + v := rval{k: vArray} + for _, w := range t.words { + v.arr = append(v.arr, rval{k: vStr, s: w}) + } + return v, nil + case tNum: + p.take() + return rval{k: vNum, s: t.text}, nil + case tIdent: + switch t.text { + case "true": + p.take() + return rval{k: vTrue}, nil + case "false": + p.take() + return rval{k: vFalse}, nil + case "nil": + p.take() + return rval{k: vNil}, nil + case "_": + if p.at(1).kind == tOp && p.at(1).text == "(" { + p.i += 2 + p.skipNL() + v, err := p.expr() + if err != nil { + return v, err + } + p.skipNL() + if p.op(",") { + p.take() + p.skipNL() + } + return v, p.expect(")") + } + } + case tConst: + path := p.take().text + for p.op("::") && p.at(1).kind == tConst { + p.take() + path += "::" + p.take().text + } + if c, ok := p.consts[path]; ok { + return c, nil + } + return rval{k: vConst, s: path}, nil + case tOp: + switch t.text { + case "-": + if p.at(1).kind == tNum && !p.at(1).space { + p.take() + return rval{k: vNum, s: "-" + p.take().text}, nil + } + case "[": + p.take() + v := rval{k: vArray} + for { + p.skipNL() + if p.op("]") { + p.take() + return v, nil + } + e, err := p.expr() + if err != nil { + return v, err + } + v.arr = append(v.arr, e) + p.skipNL() + if p.op(",") { + p.take() + continue + } + p.skipNL() + return v, p.expect("]") + } + case "{": + p.take() + v := rval{k: vHash} + for { + p.skipNL() + if p.op("}") { + p.take() + return v, nil + } + var k rval + if p.cur().kind == tLabel { + k = rval{k: vSym, s: p.take().text} + } else { + var err error + if k, err = p.expr(); err != nil { + return v, err + } + p.skipNL() + if err := p.expect("=>"); err != nil { + return v, err + } + } + p.skipNL() + e, err := p.expr() + if err != nil { + return v, err + } + v.keys, v.arr = append(v.keys, k), append(v.arr, e) + p.skipNL() + if p.op(",") { + p.take() + continue + } + p.skipNL() + return v, p.expect("}") + } + } + } + return rval{}, fmt.Errorf("unsupported expression %s", describe(t)) +} + +func (p *parser) registerType() error { + args, err := p.args() + if err != nil { + return err + } + if len(args) != 1 || args[0].k != vHash { + return fmt.Errorf("register_type must take one literal hash") + } + t, err := resourceAPIType(args[0]) + if err != nil { + return err + } + p.types = append(p.types, t) + return nil +} + +var namedGroup = regexp.MustCompile(`\(\?(?:<([A-Za-z_]\w*)>|'([A-Za-z_]\w*)')`) + +const numericRe = `\A[[:blank:]]*([-+]?)[[:blank:]]*((0[xX][0-9A-Fa-f]+)|(0?\d+)((?:\.\d+)?(?:[eE]-?\d+)?))[[:blank:]]*\z` + +func str(v rval, ok bool) (string, bool) { + return v.s, ok && (v.k == vStr || v.k == vSym) +} + +func resourceAPIType(def rval) (*rtype, error) { + name, ok := str(def.get("name")) + if !ok { + return nil, fmt.Errorf("register_type: name must be a string") + } + t := &rtype{name: name, rsapi: true} + docV, hasDoc := def.get("desc") + if !hasDoc { + docV, hasDoc = def.get("docs") + } + if hasDoc { + if docV.k != vStr { + return nil, fmt.Errorf("register_type: docs must be a string") + } + t.doc = docV.s + } + attrs, ok := def.get("attributes") + if !ok || attrs.k != vHash { + return nil, fmt.Errorf("register_type: attributes must be a literal hash") + } + var namevars []string + insyncable := false + for _, opts := range attrs.arr { + if _, ok := opts.get("behaviour"); !ok { + insyncable = true + } + } + if feats, _ := def.get("features"); !insyncable && feats.k == vArray { + for _, f := range feats.arr { + if f.s == "custom_insync" { + t.props = append(t.props, &attr{name: "rsapi_custom_insync_trigger", doc: "A hidden property which enables a type with custom insync to perform an insync check without specifying any insyncable properties (a Enum[do_not_specify_in_manifest])"}) + } + } + } + for i, k := range attrs.keys { + an, ok := str(k, true) + opts := attrs.arr[i] + if !ok || opts.k != vHash { + return nil, fmt.Errorf("register_type: attribute %d must be name => hash", i) + } + typ, ok := str(opts.get("type")) + if !ok { + return nil, fmt.Errorf("attribute %s: type must be a string", an) + } + behaviour, hasB := str(opts.get("behaviour")) + a := &attr{name: an, namevar: behaviour == "namevar"} + if d, ok := str(opts.get("desc")); ok { + a.doc = d + " (a " + typ + ")" + } + property := !hasB || behaviour == "init_only" + switch { + case !hasB: + case behaviour == "namevar": + namevars = append(namevars, an) + case behaviour != "parameter" && behaviour != "read_only" && behaviour != "init_only": + return nil, fmt.Errorf("attribute %s: invalid behaviour %s", an, behaviour) + } + rsapiValues(a, typ) + if property { + t.addProp(a) + } else { + t.params = append(t.params, a) + } + } + t.custom = true + if tp, ok := def.get("title_patterns"); ok { + if tp.k != vArray { + return nil, fmt.Errorf("title_patterns must be a literal array") + } + for _, e := range tp.arr { + re, ok := e.get("pattern") + if e.k != vHash || !ok || re.k != vRegex { + return nil, fmt.Errorf("title_patterns entries need a literal regex pattern") + } + pt := pattern{re: re.re} + for _, m := range namedGroup.FindAllStringSubmatch(re.re.src, -1) { + if n := m[1] + m[2]; !slices.Contains(pt.names, n) { + pt.names = append(pt.names, n) + } + } + t.patterns = append(t.patterns, pt) + } + } else { + first := "" + if len(namevars) > 0 { + first = namevars[0] + } + t.patterns = []pattern{{re: regex{"(.*)", "m"}, names: []string{first}}} + } + return t, nil +} + +func rsapiValues(a *attr, typ string) { + inner := strings.TrimSpace(typ) + if strings.HasPrefix(inner, "Optional[") && strings.HasSuffix(inner, "]") { + inner = strings.TrimSpace(inner[len("Optional[") : len(inner)-1]) + } + base, _, _ := strings.Cut(inner, "[") + switch strings.TrimSpace(base) { + case "String": + a.addValue("", ®ex{}) + case "Boolean": + a.addValue("true", nil) + a.addValue("false", nil) + a.values[0].aliases = []string{"true", "true"} + a.values[1].aliases = []string{"false", "false"} + case "Integer": + a.addValue("", ®ex{src: `^-?\d+$`}) + case "Float", "Numeric": + a.addValue("", ®ex{src: numericRe}) + } + if typ == "Enum[present, absent]" { + a.addValue("absent", nil) + a.addValue("present", nil) + } +} diff --git a/internal/gentypes/render.go b/internal/gentypes/render.go new file mode 100644 index 0000000..9447ee2 --- /dev/null +++ b/internal/gentypes/render.go @@ -0,0 +1,331 @@ +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 +} diff --git a/internal/gentypes/testdata/env/environment.conf b/internal/gentypes/testdata/env/environment.conf new file mode 100644 index 0000000..55832b3 --- /dev/null +++ b/internal/gentypes/testdata/env/environment.conf @@ -0,0 +1 @@ +modulepath = external_modules:modules:$basemodulepath diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/LICENSE b/internal/gentypes/testdata/env/external_modules/alternatives/LICENSE new file mode 100644 index 0000000..7a69c7c --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/alternatives/LICENSE @@ -0,0 +1,178 @@ +Copyright 2013 Adrien Thebo + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/chkconfig.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/chkconfig.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/dpkg.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/dpkg.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/chkconfig.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/chkconfig.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/dpkg.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/dpkg.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/type/alternative_entry.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/type/alternative_entry.rb new file mode 100644 index 0000000..28a2cb5 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/type/alternative_entry.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true + +Puppet::Type.newtype(:alternative_entry) do + ensurable + + newparam(:name) do + desc 'The path to the actual alternative' + + isnamevar + + validate do |path| + raise ArgumentError, 'path must be a fully qualified path' unless absolute_path? path + end + end + + newparam(:altlink) do + desc 'The name of the generic symlink for this alternative entry' + + isnamevar + + validate do |path| + raise ArgumentError, 'path must be a fully qualified path' unless absolute_path? path + end + end + + newproperty(:altlink_ro, readonly: true) do + desc 'The name of the generic symlink for this alternative entry as parameter. This is readonly.' + end + + newproperty(:altname) do + desc 'The name of symlink in the alternatives directory' + end + + newproperty(:priority) do + desc 'The value of the priority of this alternative' + + validate do |prio| + Integer(prio) + rescue StandardError + raise ArgumentError, 'priority must be an integer' + end + end + + def self.title_patterns + [ + [ + %r{^([^:]+)$}, + [ + [:name] + ] + ], + [ + %r{^(.*):([a-z]:(/|\\).*)$}i, + [ + [:name], + [:altlink] + ] + ], + [ + %r{^(.*):(.*)$}, + [ + [:name], + [:altlink] + ] + ] + ] + end +end diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/type/alternatives.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/type/alternatives.rb new file mode 100644 index 0000000..4998835 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/type/alternatives.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +Puppet::Type.newtype(:alternatives) do + feature :mode, 'The alternative can provide auto and manual modes' + + newparam(:name, isnamevar: true) do + desc 'The name of the alternative.' + end + + newproperty(:path) do + desc 'The path of the desired source for the given alternative. On RedHat, a family can be specified instead' + + def insync?(is) + if absolute_path? should + is == should + else + provider.family == should + end + end + + validate do |path| + raise ArgumentError, 'path must be a fully qualified path' unless (absolute_path? path) || (Facter.value('os.family') == 'RedHat') + end + end + + newproperty(:mode, required_features: [:mode]) do + desc 'Use the automatic option for this alternative' + + newvalue('auto') + newvalue('manual') + end + + validate do + case self[:mode] + when :auto + raise Puppet::Error, "Mode cannot be 'auto' if a path is given" if self[:path] + when :manual + raise Puppet::Error, "Mode cannot be 'manual' without a path" unless self[:path] + end + end + + autorequire(:alternative_entry) do + self[:path] + end +end diff --git a/internal/gentypes/testdata/env/external_modules/archive/LICENSE b/internal/gentypes/testdata/env/external_modules/archive/LICENSE new file mode 100644 index 0000000..7145cbd --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/archive/LICENSE @@ -0,0 +1,203 @@ + Copyright 2014 Bodeco Inc + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/curl.rb b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/curl.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/ruby.rb b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/ruby.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/wget.rb b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/wget.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/type/archive.rb b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/type/archive.rb new file mode 100644 index 0000000..6535e86 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/type/archive.rb @@ -0,0 +1,283 @@ +# frozen_string_literal: true + +require 'pathname' +require 'uri' +require 'puppet/util' +require 'puppet/parameter/boolean' + +Puppet::Type.newtype(:archive) do + @doc = 'Manage archive file download, extraction, and cleanup.' + + ensurable do + desc 'whether archive file should be present/absent (default: present)' + + newvalue(:present) do + provider.create + end + + newvalue(:absent) do + provider.destroy + end + + defaultto(:present) + + # The following changes allows us to notify if the resource is being replaced + def is_to_s(value) + return "(#{resource[:checksum_type]})#{provider.archive_checksum}" if provider.archive_checksum + + super + end + + def should_to_s(value) + return "(#{resource[:checksum_type]})#{resource[:checksum]}" if provider.archive_checksum + + super + end + + def change_to_s(currentvalue, newvalue) + if currentvalue == :absent || currentvalue.nil? + extract = resource[:extract] == :true ? "and extracted in #{resource[:extract_path]}" : '' + cleanup = resource[:cleanup] == :true ? 'with cleanup' : 'without cleanup' + + if provider.archive_checksum + "replace archive: #{provider.archive_filepath} from #{is_to_s(currentvalue)} to #{should_to_s(newvalue)}" + else + "download archive from #{resource[:source]} to #{provider.archive_filepath} #{extract} #{cleanup}" + end + elsif newvalue == :absent + "remove archive: #{provider.archive_filepath} " + else + super + end + rescue StandardError + super + end + end + + newparam(:path, namevar: true) do + desc 'namevar, archive file fully qualified file path.' + validate do |value| + raise ArgumentError, "archive path must be absolute: #{value}" unless Puppet::Util.absolute_path? value + end + end + + newparam(:filename) do + desc 'archive file name (derived from path).' + end + + newparam(:extract) do + desc 'whether archive will be extracted after download (true|false).' + newvalues(:true, :false) + defaultto(:false) + end + + newparam(:extract_path) do + desc 'target folder path to extract archive.' + validate do |value| + raise ArgumentError, "archive extract_path must be absolute: #{value}" unless Puppet::Util.absolute_path? value + end + end + newparam(:target) do + desc 'target folder path to extract archive. (this parameter is for camptocamp/archive compatibility)' + validate do |value| + raise ArgumentError, "archive extract_path must be absolute: #{value}" unless Puppet::Util.absolute_path? value + end + munge do |val| + resource[:extract_path] = val + end + end + + newparam(:extract_command) do + desc "custom extraction command ('tar xvf example.tar.gz'), also support sprintf format ('tar xvf %s') which will be processed with the filename: sprintf('tar xvf %s', filename)" + end + + newparam(:temp_dir) do + desc 'Specify an alternative temporary directory to use for copying files, if unset then the operating system default will be used.' + validate do |value| + raise ArgumentError, "Invalid temp_dir #{value}" unless Puppet::Util.absolute_path?(value) + end + end + + newparam(:extract_flags) do + desc "custom extraction options, this replaces the default flags. A string such as 'xvf' for a tar file would replace the default xf flag. A hash is useful when custom flags are needed for different platforms. {'tar' => 'xzf', '7z' => 'x -aot'}." + defaultto(:undef) + end + + newproperty(:creates) do + desc 'if file/directory exists, will not download/extract archive.' + + def should_to_s(value) + "extracting in #{resource[:extract_path]} to create #{value}" + end + end + + newparam(:cleanup) do + desc 'whether archive file will be removed after extraction (true|false).' + newvalues(:true, :false) + defaultto(:true) + end + + newparam(:source) do + desc 'archive file source, supports puppet|http|https|ftp|file|s3|gs uri.' + validate do |value| + raise ArgumentError, "invalid source url: #{value}" unless value =~ %r{puppet|http|https|ftp|file|s3|gs} || Puppet::Util.absolute_path?(value) + end + end + + newparam(:url) do + desc 'archive file source, supports http|https|ftp|file uri. + (for camptocamp/archive compatibility)' + validate do |value| + raise ArgumentError, "invalid source url: #{value}" unless value =~ %r{http|https|file|ftp} + end + munge do |val| + resource[:source] = val + end + end + + newparam(:cookie) do + desc 'archive file download cookie.' + end + + newparam(:checksum) do + desc 'archive file checksum (match checksum_type).' + newvalues(%r{\b[0-9a-f]{5,128}\b}, :true, :false, :undef, nil, '') + munge do |val| + if val.nil? || val.empty? || val == :undef + :false + elsif %i[true false].include? val + resource[:checksum_verify] = val + else + val + end + end + end + newparam(:digest_string) do + desc 'archive file checksum (match checksum_type) + (this parameter is for camptocamp/archive compatibility).' + newvalues(%r{\b[0-9a-f]{5,128}\b}) + munge do |val| + if !val.nil? && !val.empty? + resource[:checksum] = val + else + val + end + end + end + + newparam(:checksum_url) do + desc 'archive file checksum source (instead of specifying checksum)' + end + newparam(:digest_url) do + desc 'archive file checksum source (instead of specifying checksum) + (this parameter is for camptocamp/archive compatibility)' + munge do |val| + resource[:checksum_url] = val + end + end + + newparam(:checksum_type) do + desc 'archive file checksum type (none|md5|sha1|sha2|sha256|sha384|sha512).' + newvalues(:none, :md5, :sha1, :sha2, :sha256, :sha384, :sha512) + defaultto(:none) + end + newparam(:digest_type) do + desc 'archive file checksum type (none|md5|sha1|sha2|sha256|sha384|sha512) + (this parameter is camptocamp/archive compatibility).' + newvalues(:none, :md5, :sha1, :sha2, :sha256, :sha384, :sha512) + munge do |val| + resource[:checksum_type] = val + end + end + + newparam(:checksum_verify) do + desc 'whether checksum wil be verified (true|false).' + newvalues(:true, :false) + defaultto(:true) + end + + newparam(:username) do + desc 'username to download source file.' + end + + newparam(:password) do + desc 'password to download source file.' + end + + newparam(:headers) do + desc 'optional header(s) to pass.' + + validate do |val| + raise ArgumentError, "headers must be an array: #{val}" unless val.is_a?(Array) + end + end + + newparam(:user) do + desc 'extract command user (using this option will configure the archive file permission to 0644 so the user can read the file).' + end + + newparam(:group) do + desc 'extract command group (using this option will configure the archive file permisison to 0644 so the user can read the file).' + end + + newparam(:proxy_type) do + desc 'proxy type (none|ftp|http|https)' + newvalues(:none, :ftp, :http, :https) + end + + newparam(:proxy_server) do + desc 'proxy address to use when accessing source' + end + + newparam(:allow_insecure, boolean: true, parent: Puppet::Parameter::Boolean) do + desc 'ignore HTTPS certificate errors' + defaultto :false + end + + newparam(:download_options) do + desc 'provider download options (affects curl, wget, gs, and only s3 downloads for ruby provider)' + + validate do |val| + raise ArgumentError, "download_options should be String or Array: #{val}" unless val.is_a?(String) || val.is_a?(Array) + end + + munge do |val| + case val + when String + [val] + else + val + end + end + end + + autorequire(:file) do + [ + Pathname.new(self[:path]).parent.to_s, + self[:extract_path], + '/root/.aws/config', + '/root/.aws/credentials' + ].compact + end + + autorequire(:exec) do + ['install_aws_cli'] + end + + autorequire(:exec) do + ['install_gsutil'] + end + + validate do + filepath = Pathname.new(self[:path]) + self[:filename] = filepath.basename.to_s + raise ArgumentError, "invalid parameter: url (#{self[:url]}) and source (#{self[:source]}) are mutually exclusive." if !self[:source].nil? && !self[:url].nil? && self[:source] != self[:url] + raise ArgumentError, "invalid parameter: checksum_url (#{self[:checksum_url]}) and digest_url (#{self[:digest_url]}) are mutually exclusive." if !self[:checksum_url].nil? && !self[:digest_url].nil? && self[:checksum_url] != self[:digest_url] + + if self[:proxy_server] + self[:proxy_type] ||= URI(self[:proxy_server]).scheme.to_sym + else + self[:proxy_type] = :none + end + end +end diff --git a/internal/gentypes/testdata/env/external_modules/concat/LICENSE b/internal/gentypes/testdata/env/external_modules/concat/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/concat/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/concat/NOTICE b/internal/gentypes/testdata/env/external_modules/concat/NOTICE new file mode 100644 index 0000000..53ff2a7 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/concat/NOTICE @@ -0,0 +1,15 @@ +Puppet Module - puppetlabs-concat + +Copyright 2018 Puppet, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/internal/gentypes/testdata/env/external_modules/concat/lib/puppet/type/concat_file.rb b/internal/gentypes/testdata/env/external_modules/concat/lib/puppet/type/concat_file.rb new file mode 100644 index 0000000..ddde4f0 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/concat/lib/puppet/type/concat_file.rb @@ -0,0 +1,362 @@ +# frozen_string_literal: true + +require 'puppet/type/file/owner' +require 'puppet/type/file/group' +require 'puppet/type/file/mode' +require 'puppet/util/checksums' + +Puppet::Type.newtype(:concat_file) do + @doc = <<-DOC + @summary + Generates a file with content from fragments sharing a common unique tag. + + @example + Concat_fragment <<| tag == 'unique_tag' |>> + + concat_file { '/tmp/file': + tag => 'unique_tag', # Optional. Default to undef + path => '/tmp/file', # Optional. If given it overrides the resource name + owner => 'root', # Optional. Default to undef + group => 'root', # Optional. Default to undef + mode => '0644' # Optional. Default to undef + order => 'numeric' # Optional, Default to 'numeric' + ensure_newline => false # Optional, Defaults to false + } + DOC + + ensurable do + desc <<-DOC + Specifies whether the destination file should exist. Setting to 'absent' tells Puppet to delete the destination file if it exists, and + negates the effect of any other parameters. + DOC + + defaultvalues + + defaultto { :present } + end + + def exists? + self[:ensure] == :present + end + + newparam(:tag) do + desc 'Required. Specifies a unique tag reference to collect all concat_fragments with the same tag.' + end + + newparam(:path, namevar: true) do + desc <<-DOC + Specifies a destination file for the combined fragments. Valid options: a string containing an absolute path. Default value: the + title of your declared resource. + DOC + + validate do |value| + unless Puppet::Util.absolute_path?(value, :posix) || Puppet::Util.absolute_path?(value, :windows) + raise ArgumentError, _("File paths must be fully qualified, not '%{_value}'") % { _value: value } + end + end + end + + newparam(:owner, parent: Puppet::Type::File::Owner) do + desc <<-DOC + Specifies the owner of the destination file. Valid options: a string containing a username or integer containing a uid. + DOC + end + + newparam(:group, parent: Puppet::Type::File::Group) do + desc <<-DOC + Specifies a permissions group for the destination file. Valid options: a string containing a group name or integer containing a + gid. + DOC + end + + newparam(:mode, parent: Puppet::Type::File::Mode) do + desc <<-DOC + Specifies the permissions mode of the destination file. Valid options: a string containing a permission mode value in octal notation. + DOC + end + + newparam(:order) do + desc <<-DOC + Specifies a method for sorting your fragments by name within the destination file. You can override this setting for individual + fragments by adjusting the order parameter in their concat::fragment declarations. + DOC + + newvalues(:alpha, :numeric) + + defaultto :numeric + end + + newparam(:backup) do + desc <<-DOC + Specifies whether (and how) to back up the destination file before overwriting it. Your value gets passed on to Puppet's native file + resource for execution. Valid options: true, false, or a string representing either a target filebucket or a filename extension + beginning with ".".' + DOC + + validate do |value| + raise ArgumentError, _('Backup must be a Boolean or String') unless [TrueClass, FalseClass, String].include?(value.class) + end + end + + newparam(:replace, boolean: true, parent: Puppet::Parameter::Boolean) do + desc 'Specifies whether to overwrite the destination file if it already exists.' + defaultto true + end + + newparam(:validate_cmd) do + desc <<-DOC + Specifies a validation command to apply to the destination file. Requires Puppet version 3.5 or newer. Valid options: a string to + be passed to a file resource. + DOC + + validate do |value| + raise ArgumentError, _('Validate_cmd must be a String') unless value.is_a?(String) + end + end + + newparam(:ensure_newline, boolean: true, parent: Puppet::Parameter::Boolean) do + desc "Specifies whether to add a line break at the end of each fragment that doesn't already end in one." + defaultto false + end + + newparam(:format) do + desc <<-DOC + Specify what data type to merge the fragments as. Valid options: 'plain', 'yaml', 'json', 'json-array', 'json-pretty', 'json-array-pretty'. + DOC + + newvalues(:plain, :yaml, :json, :'json-array', :'json-pretty', :'json-array-pretty') + + defaultto :plain + end + + newparam(:force, boolean: true, parent: Puppet::Parameter::Boolean) do + desc 'Specifies whether to merge data structures, keeping the values with higher order.' + + defaultto false + end + + newparam(:selinux_ignore_defaults, boolean: true, parent: Puppet::Parameter::Boolean) do + desc <<-DOC + See the file type's selinux_ignore_defaults documentention: + https://docs.puppetlabs.com/references/latest/type.html#file-attribute-selinux_ignore_defaults. + DOC + end + + newparam(:selrange) do + desc "See the file type's selrange documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-selrange" + validate do |value| + raise ArgumentError, _('Selrange must be a String') unless value.is_a?(String) + end + end + + newparam(:selrole) do + desc "See the file type's selrole documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-selrole" + validate do |value| + raise ArgumentError, _('Selrole must be a String') unless value.is_a?(String) + end + end + + newparam(:seltype) do + desc "See the file type's seltype documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-seltype" + validate do |value| + raise ArgumentError, _('Seltype must be a String') unless value.is_a?(String) + end + end + + newparam(:seluser) do + desc "See the file type's seluser documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-seluser" + validate do |value| + raise ArgumentError, _('Seluser must be a String') unless value.is_a?(String) + end + end + + newparam(:show_diff, boolean: true, parent: Puppet::Parameter::Boolean) do + desc <<-DOC + Specifies whether to set the show_diff parameter for the file resource. Useful for hiding secrets stored in hiera from insecure + reporting methods. + DOC + end + + newparam(:create_empty_file, boolean: true, parent: Puppet::Parameter::Boolean) do + desc 'Specifies whether to create an empty file if no fragments are defined.' + defaultto true + end + + # Autorequire the file we are generating below + # Why is this necessary ? + autorequire(:file) do + [self[:path]] + end + + def fragments + # Collect fragments that target this resource by path, title or tag. + @fragments ||= catalog.resources.map { |resource| + next unless resource.is_a?(Puppet::Type.type(:concat_fragment)) + + if resource[:target] == self[:path] || resource[:target] == title || + (resource[:tag] && resource[:tag] == self[:tag]) + resource + end + }.compact + end + + def decompound(d) + d.split('___', 2).map { |v| (v =~ %r{^\d+$}) ? v.to_i : v } + end + + def should_content + return @generated_content if @generated_content + + @generated_content = '' + content_fragments = [] + + fragments.each do |r| + content_fragments << ["#{r[:order]}___#{r[:name]}", fragment_content(r)] + end + + sorted = if self[:order] == :numeric + content_fragments.sort do |a, b| + decompound(a[0]) <=> decompound(b[0]) + end + else + content_fragments.sort_by do |a| + a_order, a_name = a[0].split('__', 2) + [a_order, a_name] + end + end + + case self[:format] + when :plain + @generated_content = sorted.map { |cf| cf[1] }.join + when :yaml + content_array = sorted.map do |cf| + YAML.safe_load(cf[1]) + end + content_hash = content_array.reduce({}) do |memo, current| + nested_merge(memo, current) + end + @generated_content = content_hash.to_yaml + when :json, :'json-array', :'json-pretty', :'json-array-pretty' + content_array = sorted.map do |cf| + JSON.parse(cf[1]) + end + + if [:json, :'json-pretty'].include?(self[:format]) + content_hash = content_array.reduce({}) do |memo, current| + nested_merge(memo, current) + end + + @generated_content = + if self[:format] == :json + content_hash.to_json + else + JSON.pretty_generate(content_hash) + end + else + @generated_content = + if self[:format] == :'json-array' + content_array.to_json + else + JSON.pretty_generate(content_array) + end + end + end + + @generated_content + end + + def nested_merge(hash1, hash2) + # If a hash is nil or empty, simply return the other + return hash1 if hash2.nil? || hash2.empty? + return hash2 if hash1.nil? || hash1.empty? + + # Unique merge for arrays + return (hash1 + hash2).uniq if hash1.is_a?(Array) && hash2.is_a?(Array) + + # Deep-merge Hashes; higher order value is kept + hash1.merge(hash2) do |k, v1, v2| + if (v1.is_a?(Hash) && v2.is_a?(Hash)) || (v1.is_a?(Array) && v2.is_a?(Array)) + nested_merge(v1, v2) + else + # Fail if there are duplicate keys without force + unless v1 == v2 + unless self[:force] + err_message = [ + "Duplicate key '#{k}' found with values '#{v1}' and #{v2}'.", + "Use 'force' attribute to merge keys.", + ] + raise(_(err_message.join(' '))) + end + Puppet.debug("Key '#{k}': replacing '#{v2}' with '#{v1}'.") + end + v1 + end + end + end + + def fragment_content(r) + if r[:content].nil? == false + # Explicitly resolve deferred values. + fragment_content = r[:content].respond_to?(:resolve) ? r[:content].resolve : r[:content] + elsif r[:source].nil? == false + @source = nil + Array(r[:source]).each do |source| + if Puppet::FileServing::Metadata.indirection.find(source) + @source = source + break + end + end + raise _('Could not retrieve source(s) %{_array}') % { _array: Array(r[:source]).join(', ') } unless @source + + tmp = Puppet::FileServing::Content.indirection.find(@source) + fragment_content = tmp.content unless tmp.nil? + end + + if self[:ensure_newline] + newline = Puppet::Util::Platform.windows? ? "\r\n" : "\n" + fragment_content = fragment_content.dup << newline unless %r{#{newline}\Z}.match?(fragment_content) + end + + fragment_content + end + + def generate + file_opts = { + ensure: (self[:ensure] == :absent) ? :absent : :file + } + + [:path, + :owner, + :group, + :mode, + :replace, + :backup, + :selinux_ignore_defaults, + :selrange, + :selrole, + :seltype, + :seluser, + :validate_cmd, + :show_diff].each do |param| + file_opts[param] = self[param] unless self[param].nil? + end + + excluded_metaparams = [:before, :notify, :require, :subscribe, :tag] + + Puppet::Type.metaparams.each do |metaparam| + file_opts[metaparam] = self[metaparam] unless self[metaparam].nil? || excluded_metaparams.include?(metaparam) + end + + [Puppet::Type.type(:file).new(file_opts)] + end + + def eval_generate + content = should_content + + catalog.resource("File[#{self[:path]}]")[:content] = content unless content.nil? + + catalog.resource("File[#{self[:path]}]")[:ensure] = :absent if !self[:create_empty_file] && (content.nil? || content.empty?) + + [catalog.resource("File[#{self[:path]}]")] + end +end diff --git a/internal/gentypes/testdata/env/external_modules/firewall/LICENSE b/internal/gentypes/testdata/env/external_modules/firewall/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/firewall/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/firewall/NOTICE b/internal/gentypes/testdata/env/external_modules/firewall/NOTICE new file mode 100644 index 0000000..95e1959 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/firewall/NOTICE @@ -0,0 +1,23 @@ +Puppet Module - puppetlabs-firewall + +Copyright 2018 Puppet, Inc. +Copyright 2011 Jonathan Boyett +Copyright 2011 Media Temple, Inc. + +Some of the iptables code was taken from puppet-iptables which was: + +Copyright 2011 Bob.sh Limited +Copyright 2008 Camptocamp Association +Copyright 2007 Dmitri Priimak + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewall/firewall.rb b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewall/firewall.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewallchain/firewallchain.rb b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewallchain/firewallchain.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/type/firewall.rb b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/type/firewall.rb new file mode 100644 index 0000000..de92760 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/type/firewall.rb @@ -0,0 +1,1548 @@ +# frozen_string_literal: true + +# lib/puppet/type/iptables.rb +require 'puppet/resource_api' + +Puppet::ResourceApi.register_type( + name: 'firewall', + docs: <<-DESC, + This type provides the capability to manage firewall rules within puppet via iptables. + + **Autorequires:** + + If Puppet is managing the iptables chains specified in the + `chain` or `jump` parameters, the firewall resource will autorequire + those firewallchain resources. + + If Puppet is managing the iptables, iptables-persistent, or iptables-services packages, + the firewall resource will autorequire those packages to ensure that any required binaries are + installed. + + #### Providers + * Required binaries: iptables-save, iptables. + * Default for kernel == linux. + * Supported features: address_type, clusterip, connection_limiting, conntrack, dnat, icmp_match, + interface_match, iprange, ipsec_dir, ipsec_policy, ipset, iptables, isfragment, length, + log_level, log_prefix, log_uid, log_tcp_sequence, log_tcp_options, log_ip_options, + mark, mask, mss, netmap, nflog_group, nflog_prefix, + nflog_range, nflog_threshold, owner, pkttype, queue_bypass, queue_num, rate_limiting, + recent_limiting, reject_type, snat, socket, state_match, string_matching, tcp_flags, bpf. + + #### Features + * address_type: The ability to match on source or destination address type. + + * clusterip: Configure a simple cluster of nodes that share a certain IP and MAC address without an explicit load balancer in front of them. + + * condition: Match if a specific condition variable is (un)set (requires xtables-addons) + + * connection_limiting: Connection limiting features. + + * conntrack: Connection tracking features. + + * dnat: Destination NATing. + + * hop_limiting: Hop limiting features. + + * icmp_match: The ability to match ICMP types. + + * interface_match: Interface matching. + + * iprange: The ability to match on source or destination IP range. + + * ipsec_dir: The ability to match IPsec policy direction. + + * ipsec_policy: The ability to match IPsec policy. + + * iptables: The provider provides iptables features. + + * isfirstfrag: The ability to match the first fragment of a fragmented ipv6 packet. + + * isfragment: The ability to match fragments. + + * ishasmorefrags: The ability to match a non-last fragment of a fragmented ipv6 packet. + + * islastfrag: The ability to match the last fragment of an ipv6 packet. + + * length: The ability to match the length of the layer-3 payload. + + * log_level: The ability to control the log level. + + * log_prefix: The ability to add prefixes to log messages. + + * log_uid: The ability to log the userid of the process which generated the packet. + + * log_tcp_sequence: The ability to log TCP sequence numbers. + + * log_tcp_options: The ability to log TCP packet header. + + * log_ip_options: The ability to log IP/IPv6 packet header. + + * mark: The ability to match or set the netfilter mark value associated with the packet. + + * mask: The ability to match recent rules based on the ipv4 mask. + + * nflog_group: The ability to set the group number for NFLOG. + + * nflog_prefix: The ability to set a prefix for nflog messages. + + * nflog_size: Set the max size of a message to send to nflog. + + * nflog_threshold: The ability to set nflog_threshold. + + * owner: The ability to match owners. + + * pkttype: The ability to match a packet type. + + * rate_limiting: Rate limiting features. + + * recent_limiting: The netfilter recent module. + + * reject_type: The ability to control reject messages. + + * set_mss: Set the TCP MSS of a packet. + + * snat: Source NATing. + + * socket: The ability to match open sockets. + + * state_match: The ability to match stateful firewall states. + + * string_matching: The ability to match a given string by using some pattern matching strategy. + + * tcp_flags: The ability to match on particular TCP flag settings. + + * netmap: The ability to map entire subnets via source or destination nat rules. + + * hashlimit: The ability to use the hashlimit-module. + + * bpf: The ability to use Berkeley Paket Filter rules. + + * ipvs: The ability to match IP Virtual Server packets. + + * ct_target: The ability to set connection tracking parameters for a packet or its associated connection. + + * random_fully: The ability to use --random-fully flag. + DESC + features: ['custom_insync'], + attributes: { + ensure: { + type: "Enum[present, absent, 'present', 'absent']", + default: 'present', + desc: <<-DESC + Whether this rule should be present or absent on the target system. + DESC + }, + name: { + type: 'Pattern[/(^\d+(?:[ \t-]\S+)+$)/]', + behaviour: :namevar, + desc: <<-DESC + The canonical name of the rule. This name is also used for ordering + so make sure you prefix the rule with a number: + + 000 this runs first + 999 this runs last + + Depending on the provider, the name of the rule can be stored using + the comment feature of the underlying firewall subsystem. + DESC + }, + line: { + type: 'Optional[String[1]]', + behaviour: :read_only, + desc: <<-DESC + A read only attribute containing the full rule, used when deleting and when applying firewallchain purge attributes. + DESC + }, + protocol: { + type: "Enum['iptables', 'ip6tables', 'IPv4', 'IPv6']", + default: 'IPv4', + desc: <<-DESC + The protocol used to set the rule, it's allowed values have been expanded to bring it closer to its `firewallchain` counterpart. + Defaults to `IPv4` + + Noted: this was previously defined as `provider`, however the resource_api does not allow this to be used as an attribute title. + DESC + }, + table: { + type: "Enum['nat', 'mangle', 'filter', 'raw', 'rawpost', 'broute', 'security']", + default: 'filter', + desc: <<-DESC + The table the rule will exist in. + Valid options are: + + * nat + * mangle + * filter + * raw + * rawpost + + Defaults to 'filter' + DESC + }, + chain: { + type: 'String[1]', + default: 'INPUT', + desc: <<-DESC + Name of the chain the rule will be a part of, ensure the chain you choose exists within your set table. + Can be one of the built-in chains: + + * INPUT + * FORWARD + * OUTPUT + * PREROUTING + * POSTROUTING + + Or you can provide a user-based chain. + Defaults to 'INPUT' + DESC + }, + source: { + type: 'Optional[String[1]]', + desc: <<-DESC + The source address. For example: + + source => '192.168.2.0/24' + + You can also negate a mask by putting ! in front. For example: + + source => '! 192.168.2.0/24' + + The source can also be an IPv6 address if your provider supports it. + DESC + }, + destination: { + type: 'Optional[String[1]]', + desc: <<-DESC + The destination address to match. For example: + + destination => '192.168.1.0/24' + + You can also negate a mask by putting ! in front. For example: + + destination => '! 192.168.2.0/24' + + The destination can also be an IPv6 address if your provider supports it. + DESC + }, + iniface: { + type: 'Optional[Pattern[/^(?:!\s)?[a-zA-Z0-9\-\._\+\:@]+$/]]', + desc: <<-DESC + Input interface to filter on. Supports interface alias like eth0:0. + To negate the match try this: + + iniface => '! lo', + DESC + }, + outiface: { + type: 'Optional[Pattern[/^(?:!\s)?[a-zA-Z0-9\-\._\+\:@]+$/]]', + desc: <<-DESC + Output interface to filter on. Supports interface alias like eth0:0. + To negate the match try this: + + outiface => '! lo', + DESC + }, + physdev_in: { + type: 'Optional[Pattern[/^(?:!\s)?[a-zA-Z0-9\-\._\+]+$/]]', + desc: <<-DESC + Match if the packet is entering a bridge from the given interface. + To negate the match try this: + + physdev_in => '! lo', + DESC + }, + physdev_out: { + type: 'Optional[Pattern[/^(?:!\s)?[a-zA-Z0-9\-\._\+]+$/]]', + desc: <<-DESC + Match if the packet is leaving a bridge via the given interface. + To negate the match try this: + + physdev_out => '! lo', + DESC + }, + physdev_is_bridged: { + type: 'Optional[Boolean]', + desc: <<-DESC + Match if the packet is transversing a bridge. + DESC + }, + physdev_is_in: { + type: 'Optional[Boolean]', + desc: <<-DESC + Matches if the packet has entered through a bridge interface. + DESC + }, + physdev_is_out: { + type: 'Optional[Boolean]', + desc: <<-DESC + Matches if the packet will leave through a bridge interface. + DESC + }, + proto: { + type: 'Optional[Pattern[/^(?:!\s)?(?:ip(?:encap)?|tcp|udp|icmp|esp|ah|vrrp|carp|igmp|ipv4|ospf|gre|cbt|sctp|pim|all)/]]', + default: 'tcp', + desc: <<-DESC + The specific protocol to match for this rule. + DESC + }, + isfragment: { + type: 'Optional[Boolean]', + desc: <<-DESC + Set to true to match tcp fragments (requires proto to be set to tcp) + DESC + }, + isfirstfrag: { + type: 'Optional[Boolean]', + desc: <<-DESC + Matches if the packet is the first fragment. + Specific to IPv6. + DESC + }, + ishasmorefrags: { + type: 'Optional[Boolean]', + desc: <<-DESC + Matches if the packet has it's 'more fragments' bit set. + Specific to IPv6. + DESC + }, + islastfrag: { + type: 'Optional[Boolean]', + desc: <<-DESC + Matches if the packet is the last fragment. + Specific to IPv6. + DESC + }, + stat_mode: { + type: 'Optional[Enum[nth, random]]', + desc: <<-DESC + Set the matching mode for statistic matching. + DESC + }, + stat_every: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Match one packet every nth packet. Requires `stat_mode => 'nth'` + DESC + }, + stat_packet: { + type: 'Optional[Integer]', + desc: <<-DESC + Set the initial counter value for the nth mode. Must be between 0 and the value of `stat_every`. + Defaults to 0. Requires `stat_mode => 'nth'` + DESC + }, + stat_probability: { + type: 'Optional[Variant[Integer[0,1], Float[0.0,1.0]]]', + desc: <<-DESC + Set the probability from 0 to 1 for a packet to be randomly matched. It works only with `stat_mode => 'random'`. + DESC + }, + src_range: { + type: 'Optional[String[1]]', + desc: <<-DESC + The source IP range. For example: + + src_range => '192.168.1.1-192.168.1.10' + + You can also negate the range by apending a `!`` to the front. For example: + + src_range => '! 192.168.1.1-192.168.1.10' + + The source IP range must be in 'IP1-IP2' format. + DESC + }, + dst_range: { + type: 'Optional[String[1]]', + desc: <<-DESC + The destination IP range. For example: + + dst_range => '192.168.1.1-192.168.1.10' + + You can also negate the range by putting ! in front. For example: + + dst_range => '! 192.168.1.1-192.168.1.10' + + The destination IP range must be in 'IP1-IP2' format. + DESC + }, + tcp_option: { + type: 'Optional[Variant[Pattern[/^(?:!\s)?(?:[0-1][0-9]{0,2}|2[0-4][0-9]|25[0-5])$/], Integer[0,255]]]', + desc: <<-DESC + Match when the TCP option is present or absent. + Given as a single TCP option, optionally prefixed with '! ' to match + on absence instead. Only one TCP option can be matched in a given rule. + TCP option numbers are an eight-bit field, so valid option numbers range + from 0-255. + DESC + }, + tcp_flags: { + type: 'Optional[Pattern[/^(?:!\s)?((FIN|SYN|RST|PSH|ACK|URG|ALL|NONE),?)+\s((FIN|SYN|RST|PSH|ACK|URG|ALL|NONE),?)+$/]]', + desc: <<-DESC + Match when the TCP flags are as specified. + Is a string with a list of comma-separated flag names for the mask, + then a space, then a comma-separated list of flags that should be set. + The flags are: FIN SYN RST PSH ACK URG ALL NONE + Note that you specify them in the order that iptables --list-rules + would list them to avoid having puppet think you changed the flags. + + Example: FIN,SYN,RST,ACK SYN matches packets with the SYN bit set and the + ACK,RST and FIN bits cleared. Such packets are used to request + TCP connection initiation. + Can be negated by placing ! in front, i.e. + ! FIN,SYN,RST,ACK SYN + DESC + }, + uid: { + type: 'Optional[Variant[String[1], Integer]]', + desc: <<-DESC + UID or Username owner matching rule. Accepts a single argument + only, as iptables does not accept multiple uid in a single + statement. + To negate add a space seperated '!' in front of the value. + DESC + }, + gid: { + type: 'Optional[Variant[String[1], Integer]]', + desc: <<-DESC + GID or Group owner matching rule. Accepts a single argument + only, as iptables does not accept multiple gid in a single + statement. + To negate add a space seperated '!' in front of the value. + DESC + }, + mac_source: { + type: 'Optional[Pattern[/^(?:!\s)?([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})$/]]', + desc: <<-DESC + MAC Source + DESC + }, + sport: { + type: 'Optional[Variant[Array[Variant[Pattern[/^(?:!\s)?\d+(?:(?:\:|-)\d+)?$/],Integer]],Pattern[/^(?:!\s)?\d+(?:(?:\:|-)\d+)?$/],Integer]]', + desc: <<-DESC + The source port to match for this filter (if the protocol supports + ports). Will accept a single element or an array. + + For some firewall providers you can pass a range of ports in the format: + + sport => '1:1024' + + This would cover ports 1 to 1024. + + You can also negate a port by putting ! in front. For example: + + sport => '! 54' + + If you wish to negate multiple ports at once, then place a ! at the start of the first array + variable. For example: + + sport => ['! 54','23'] + + Note: + This will negate all passed ports, it is not possible to negate a single one of the array. + In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + DESC + }, + dport: { + type: 'Optional[Variant[Array[Variant[Pattern[/^(?:!\s)?\d+(?:(?:\:|-)\d+)?$/],Integer]],Pattern[/^(?:!\s)?\d+(?:(?:\:|-)\d+)?$/],Integer]]', + desc: <<-DESC + The source port to match for this filter (if the protocol supports + ports). Will accept a single element or an array. + + For some firewall providers you can pass a range of ports in the format: + + dport => '1:1024' + + This would cover ports 1 to 1024. + + You can also negate a port by putting ! in front. For example: + + dport => '! 54' + + If you wish to negate multiple ports at once, then place a ! at the start of the first array + variable. For example: + + dport => ['! 54','23'] + + Note: + This will negate all passed ports, it is not possible to negate a single one of the array. + In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + DESC + }, + src_type: { + type: 'Optional[Variant[ + Array[Pattern[/^(?:!\s)?(?:UNSPEC|UNICAST|LOCAL|BROADCAST|ANYCAST|MULTICAST|BLACKHOLE|UNREACHABLE|UNREACHABLE|PROHIBIT|THROW|NAT|XRESOLVE)(?:\s--limit-iface-(?:in|out))?$/]], + Pattern[/^(?:!\s)?(?:UNSPEC|UNICAST|LOCAL|BROADCAST|ANYCAST|MULTICAST|BLACKHOLE|UNREACHABLE|UNREACHABLE|PROHIBIT|THROW|NAT|XRESOLVE)(?:\s--limit-iface-(?:in|out))?$/]]]', + desc: <<-DESC + The source address type. For example: + + src_type => 'LOCAL' + + Can be one of: + + * UNSPEC - an unspecified address + * UNICAST - a unicast address + * LOCAL - a local address + * BROADCAST - a broadcast address + * ANYCAST - an anycast packet + * MULTICAST - a multicast address + * BLACKHOLE - a blackhole address + * UNREACHABLE - an unreachable address + * PROHIBIT - a prohibited address + * THROW - undocumented + * NAT - undocumented + * XRESOLVE - undocumented + + In addition, it accepts '--limit-iface-in' and '--limit-iface-out' flags, specified as: + + src_type => ['LOCAL --limit-iface-in'] + + It can also be negated using '!': + + src_type => ['! LOCAL'] + + Will accept a single element or an array. Each element of the array should be negated seperately. + DESC + }, + dst_type: { + type: 'Optional[Variant[ + Array[Pattern[/^(?:!\s)?(?:UNSPEC|UNICAST|LOCAL|BROADCAST|ANYCAST|MULTICAST|BLACKHOLE|UNREACHABLE|UNREACHABLE|PROHIBIT|THROW|NAT|XRESOLVE)(?:\s--limit-iface-(?:in|out))?$/]], + Pattern[/^(?:!\s)?(?:UNSPEC|UNICAST|LOCAL|BROADCAST|ANYCAST|MULTICAST|BLACKHOLE|UNREACHABLE|UNREACHABLE|PROHIBIT|THROW|NAT|XRESOLVE)(?:\s--limit-iface-(?:in|out))?$/]]]', + desc: <<-DESC + The destination address type. For example: + + dst_type => ['LOCAL'] + + Can be one of: + + * UNSPEC - an unspecified address + * UNICAST - a unicast address + * LOCAL - a local address + * BROADCAST - a broadcast address + * ANYCAST - an anycast packet + * MULTICAST - a multicast address + * BLACKHOLE - a blackhole address + * UNREACHABLE - an unreachable address + * PROHIBIT - a prohibited address + * THROW - undocumented + * NAT - undocumented + * XRESOLVE - undocumented + + In addition, it accepts '--limit-iface-in' and '--limit-iface-out' flags, specified as: + + dst_type => ['LOCAL --limit-iface-in'] + + Each value can be negated seperately using '!': + + dst_type => ['! UNICAST', '! LOCAL'] + + Will accept a single element or an array. + DESC + }, + socket: { + type: 'Optional[Boolean]', + desc: <<-DESC + If true, matches if an open socket can be found by doing a coket lookup + on the packet. + DESC + }, + pkttype: { + type: "Optional[Enum['unicast', 'broadcast', 'multicast']]", + desc: <<-DESC + Sets the packet type to match. + DESC + }, + ipsec_dir: { + type: "Optional[Enum['in', 'out']]", + desc: <<-DESC + Sets the ipsec policy direction + DESC + }, + ipsec_policy: { + type: "Optional[Enum['none', 'ipsec']]", + desc: <<-DESC + Sets the ipsec policy type. May take a combination of arguments for any flags that can be passed to `--pol ipsec` such as: `--strict`, `--reqid 100`, `--next`, `--proto esp`, etc. + DESC + }, + state: { + type: 'Optional[Variant[Pattern[/^(?:!\s)?(?:INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED)$/], Array[Pattern[/^(?:!\s)?(?:INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED)$/]]]]', + desc: <<-DESC + Matches a packet based on its state in the firewall stateful inspection + table. Values can be: + + * INVALID + * ESTABLISHED + * NEW + * RELATED + * UNTRACKED + * SNAT + * DNAT + + Can be passed either as a single String or as an Array: + + state => 'INVALID' + state => ['INVALID', 'ESTABLISHED'] + + Values can be negated by adding a '!'. + If you wish to negate multiple states at once, then place a ! at the start of the first array + variable. For example: + + state => ['! INVALID', 'ESTABLISHED'] + + Note: + This will negate all passed states, it is not possible to negate a single one of the array. + In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + DESC + }, + ctstate: { + type: 'Optional[Variant[Pattern[/^(?:!\s)?(?:INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED|SNAT|DNAT)$/], Array[Pattern[/^(?:!\s)?(?:INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED|SNAT|DNAT)$/]]]]', + desc: <<-DESC + Matches a packet based on its state in the firewall stateful inspection + table, using the conntrack module. Values can be: + + * INVALID + * ESTABLISHED + * NEW + * RELATED + * UNTRACKED + * SNAT + * DNAT + + Can be passed either as a single String or as an Array, if passed as an array values should be passed in order: + + ctstate => 'INVALID' + ctstate => ['INVALID', 'ESTABLISHED'] + + Values can be negated by adding a '!'. + If you wish to negate multiple states at once, then place a ! at the start of the first array + variable. For example: + + ctstate => ['! INVALID', 'ESTABLISHED'] + + Note: + This will negate all passed states, it is not possible to negate a single one of the array. + In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + DESC + }, + ctproto: { + type: 'Optional[Variant[Pattern[/^(?:!\s)?\d+$/],Integer]]', + desc: <<-DESC + The specific layer-4 protocol number to match for this rule using the + conntrack module. + DESC + }, + ctorigsrc: { + type: 'Optional[String[1]]', + desc: <<-DESC + The original source address using the conntrack module. For example: + + ctorigsrc => '192.168.2.0/24' + + You can also negate a mask by putting ! in front. For example: + + ctorigsrc => '! 192.168.2.0/24' + + The ctorigsrc can also be an IPv6 address if your provider supports it. + DESC + }, + ctorigdst: { + type: 'Optional[String[1]]', + desc: <<-DESC + The original destination address using the conntrack module. For example: + + ctorigdst => '192.168.2.0/24' + + You can also negate a mask by putting ! in front. For example: + + ctorigdst => '! 192.168.2.0/24' + + The ctorigdst can also be an IPv6 address if your provider supports it. + DESC + }, + ctreplsrc: { + type: 'Optional[String[1]]', + desc: <<-DESC + The reply source address using the conntrack module. For example: + + ctreplsrc => '192.168.2.0/24' + + You can also negate a mask by putting ! in front. For example: + + ctreplsrc => '! 192.168.2.0/24' + + The ctreplsrc can also be an IPv6 address if your provider supports it. + DESC + }, + ctrepldst: { + type: 'Optional[String[1]]', + desc: <<-DESC + The reply destination address using the conntrack module. For example: + + ctrepldst => '192.168.2.0/24' + + You can also negate a mask by putting ! in front. For example: + + ctrepldst => '! 192.168.2.0/24' + + The ctrepldst can also be an IPv6 address if your provider supports it. + DESC + }, + ctorigsrcport: { + type: 'Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]', + desc: <<-DESC + The original source port to match for this filter using the conntrack module. + For example: + + ctorigsrcport => '80' + + You can also specify a port range: For example: + + ctorigsrcport => '80:81' + + You can also negate a port by putting ! in front. For example: + + ctorigsrcport => '! 80' + DESC + }, + ctorigdstport: { + type: 'Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]', + desc: <<-DESC + The original destination port to match for this filter using the conntrack module. + For example: + + ctorigdstport => '80' + + You can also specify a port range: For example: + + ctorigdstport => '80:81' + + You can also negate a port by putting ! in front. For example: + + ctorigdstport => '! 80' + DESC + }, + ctreplsrcport: { + type: 'Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]', + desc: <<-DESC + The reply source port to match for this filter using the conntrack module. + For example: + + ctreplsrcport => '80' + + You can also specify a port range: For example: + + ctreplsrcport => '80:81' + + You can also negate a port by putting ! in front. For example: + + ctreplsrcport => '! 80' + DESC + }, + ctrepldstport: { + type: 'Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]', + desc: <<-DESC + The reply destination port to match for this filter using the conntrack module. + For example: + + ctrepldstport => '80' + + You can also specify a port range: For example: + + ctrepldstport => '80:81' + + You can also negate a port by putting ! in front. For example: + + ctrepldstport => '! 80' + DESC + }, + ctstatus: { + type: 'Optional[Variant[Pattern[/^(?:!\s)?(?:EXPECTED|SEEN_REPLY|ASSURED|CONFIRMED|NONE)$/], Array[Pattern[/^(?:!\s)?(?:EXPECTED|SEEN_REPLY|ASSURED|CONFIRMED|NONE)$/]]]]', + desc: <<-DESC + Matches a packet based on its status using the conntrack module. Values can be: + + * EXPECTED + * SEEN_REPLY + * ASSURED + * CONFIRMED + * NONE + + Can be passed either as a single String or as an Array: + + ctstatus => 'EXPECTED' + ctstatus => ['EXPECTED', 'CONFIRMED'] + + Values can be negated by adding a '!'. + If you wish to negate multiple states at once, then place a ! at the start of the first array + variable. For example: + + ctstatus => ['! EXPECTED', 'CONFIRMED'] + + Note:#{' '} + This will negate all passed states, it is not possible to negate a single one of the array. + In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + DESC + }, + ctexpire: { + type: 'Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]', + desc: <<-DESC + Matches a packet based on lifetime remaining in seconds or range of seconds + using the conntrack module. For example: + + ctexpire => '100' + ctexpire => '100:150' + DESC + }, + ctdir: { + type: "Optional[Enum['REPLY', 'ORIGINAL']]", + desc: <<-DESC + Matches a packet that is flowing in the specified direction using the + conntrack module. If this flag is not specified at all, matches packets + in both directions. Values can be: + + * REPLY + * ORIGINAL + DESC + }, + hop_limit: { + type: 'Optional[Variant[Pattern[/^(?:!\s)?\d+$/],Integer]]', + desc: <<-DESC + Hop limiting value for matched packets. + To negate add a space seperated `!` the the beginning of the value + This is IPv6 specific. + DESC + }, + icmp: { + type: 'Optional[Variant[String[1],Integer]]', + desc: <<-DESC + When matching ICMP packets, this is the type of ICMP packet to match. + + A value of "any" is not supported. To achieve this behaviour the + parameter should simply be omitted or undefined. + An array of values is also not supported. To match against multiple ICMP + types, please use separate rules for each ICMP type. + DESC + }, + limit: { + type: 'Optional[Pattern[/^\d+\/(?:sec(?:ond)?|min(?:ute)?|hour|day)$/]]', + desc: <<-DESC + Rate limiting value for matched packets. The format is: + rate/[/second/|/minute|/hour|/day] + + Example values are: '50/sec', '40/min', '30/hour', '10/day'." + DESC + }, + burst: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Rate limiting burst value (per second) before limit checks apply. + DESC + }, + length: { + type: 'Optional[Pattern[/^([0-9]+)(:)?([0-9]+)?$/]]', + desc: <<-DESC + Sets the length of layer-3 payload to match. + + Example values are: '500', '5:400' + DESC + }, + recent: { + type: "Optional[Enum['set', 'update', 'rcheck', 'remove', '! set', '! update', '! rcheck', '! remove']]", + desc: <<-DESC + Enable the recent module. Takes as an argument one of set, update, + rcheck or remove. For example: + + ``` + # If anyone's appeared on the 'badguy' blacklist within + # the last 60 seconds, drop their traffic, and update the timestamp. + firewall { '100 Drop badguy traffic': + recent => 'update', + rseconds => 60, + rsource => true, + rname => 'badguy', + jump => 'DROP', + chain => 'FORWARD', + } + ``` + + + ``` + # No-one should be sending us traffic on eth0 from the + # localhost, Blacklist them + firewall { '101 blacklist strange traffic': + recent => 'set', + rsource => true, + rname => 'badguy', + destination => '127.0.0.0/8', + iniface => 'eth0', + jump => 'DROP', + chain => 'FORWARD', + } + ``` + DESC + }, + rseconds: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Recent module; used in conjunction with one of `recent => 'rcheck'` or + `recent => 'update'`. When used, this will narrow the match to only + happen when the address is in the list and was seen within the last given + number of seconds. + DESC + }, + reap: { + type: 'Optional[Boolean]', + desc: <<-DESC + Recent module; can only be used in conjunction with the `rseconds` + attribute. When used, this will cause entries older than 'seconds' to be + purged. Must be boolean true. + DESC + }, + rhitcount: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Recent module; used in conjunction with `recent => 'update'` or `recent + => 'rcheck'. When used, this will narrow the match to only happen when + the address is in the list and packets had been received greater than or + equal to the given value. + DESC + }, + rttl: { + type: 'Optional[Boolean]', + desc: <<-DESC + Recent module; may only be used in conjunction with one of `recent => + 'rcheck'` or `recent => 'update'`. When used, this will narrow the match + to only happen when the address is in the list and the TTL of the current + packet matches that of the packet which hit the `recent => 'set'` rule. + This may be useful if you have problems with people faking their source + address in order to DoS you via this module by disallowing others access + to your site by sending bogus packets to you. Must be boolean true. + DESC + }, + rname: { + type: 'Optional[String[1]]', + desc: <<-DESC + Recent module; The name of the list. + The recent module defaults this to `DEFAULT` when recent is set + DESC + }, + mask: { + type: 'Optional[Pattern[/^\d+\.\d+\.\d+\.\d+$/]]', + desc: <<-DESC + Recent module; sets the mask to use when `recent` is enabled. + The recent module defaults this to `255.255.255.255` when recent is set + DESC + }, + rsource: { + type: 'Optional[Boolean]', + desc: <<-DESC + Recent module; add the source IP address to the list. + Mutually exclusive with `rdest` + The recent module defaults this behaviour to true when recent is set. + DESC + }, + rdest: { + type: 'Optional[Boolean]', + desc: <<-DESC + Recent module; add the destination IP address to the list. + Mutually exclusive with `rsource` + Must be boolean true. + DESC + }, + ipset: { + type: 'Optional[Variant[Pattern[/^(?:!\s)?[\w\-:_]+\s(?:src|dst)(?:,src|,dst)?$/], Array[Pattern[/^(?:!\s)?[\w\-:_]+\s(?:src|dst)(?:,src|,dst)?$/]]]]', + desc: <<-DESC + Matches against the specified ipset list. + Requires ipset kernel module. Will accept a single element or an array. + The value is the name of the denylist, followed by a space, and then + 'src' and/or 'dst' separated by a comma. + For example: 'denylist src,dst' + To negate simply place a space seperated `!` at the beginning of a value. + Values can de negated independently. + DESC + }, + string: { + type: 'Optional[String[1]]', + desc: <<-DESC + String matching feature. Matches the packet against the pattern + given as an argument. + To negate, add a space seperated `!` to the beginning of the string. + DESC + }, + string_hex: { + type: 'Optional[Pattern[/^(?:!\s)?\|[a-zA-Z0-9\s]+\|$/]]', + desc: <<-DESC + String matching feature. Matches the packet against the pattern + given as an argument. + To negate, add a space seperated `!` to the beginning of the string. + DESC + }, + string_algo: { + type: "Optional[Enum['bm', 'kmp']]", + desc: <<-DESC + String matching feature, pattern matching strategy. + DESC + }, + string_from: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + String matching feature, offset from which we start looking for any matching. + DESC + }, + string_to: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + String matching feature, offset up to which we should scan. + DESC + }, + jump: { + type: 'Optional[String[1]]', + desc: <<-DESC + This value for the iptables --jump parameter and the action to perform on a match. Common values are: + + * ACCEPT - the packet is accepted + * REJECT - the packet is rejected with a suitable ICMP response + * DROP - the packet is dropped + + But can also be one of the following: + + * QUEUE + * RETURN + * DNAT + * SNAT + * LOG + * NFLOG + * NETMAP + * MASQUERADE + * REDIRECT + * MARK + * CT + + And any valid chain name is also allowed. + + If you specify no value it will simply match the rule but perform no action. + DESC + }, + goto: { + type: 'Optional[String[1]]', + desc: <<-DESC + The value for the iptables --goto parameter. Normal values are: + + * QUEUE + * RETURN + * DNAT + * SNAT + * LOG + * MASQUERADE + * REDIRECT + * MARK + + But any valid chain name is allowed. + DESC + }, + clusterip_new: { + type: 'Optional[Boolean]', + desc: <<-DESC + Used with the CLUSTERIP jump target. + Create a new ClusterIP. You always have to set this on the first rule for a given ClusterIP. + This is IPv4 specific. + DESC + }, + clusterip_hashmode: { + type: "Optional[Enum['sourceip', 'sourceip-sourceport', 'sourceip-sourceport-destport']]", + desc: <<-DESC + Used with the CLUSTERIP jump target. + Specify the hashing mode. + This is IPv4 specific. + DESC + }, + clusterip_clustermac: { + type: 'Optional[Pattern[/^([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})$/]]', + desc: <<-DESC + Used with the CLUSTERIP jump target. + Specify the ClusterIP MAC address. Has to be a link-layer multicast address. + This is IPv4 specific. + DESC + }, + clusterip_total_nodes: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Used with the CLUSTERIP jump target. + Number of total nodes within this cluster. + This is IPv4 specific. + DESC + }, + clusterip_local_node: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Used with the CLUSTERIP jump target. + Specify the random seed used for hash initialization. + This is IPv4 specific. + DESC + }, + clusterip_hash_init: { + type: 'Optional[String[1]]', + desc: <<-DESC + Used with the CLUSTERIP jump target. + Specify the random seed used for hash initialization. + This is IPv4 specific. + DESC + }, + queue_num: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Used with NFQUEUE jump target. + What queue number to send packets to + DESC + }, + queue_bypass: { + type: 'Optional[Boolean]', + desc: <<-DESC + Allow packets to bypass :queue_num if userspace process is not listening + DESC + }, + nflog_group: { + type: 'Optional[Integer[1, 65535]]', + desc: <<-DESC + Used with the jump target NFLOG. + The netlink group (0 - 2^16-1) to which packets are (only applicable + for nfnetlink_log). Defaults to 0. + DESC + }, + nflog_prefix: { + type: 'Optional[String]', + desc: <<-DESC + Used with the jump target NFLOG. + A prefix string to include in the log message, up to 64 characters long, + useful for distinguishing messages in the logs. + DESC + }, + nflog_range: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Used with the jump target NFLOG. + This has never worked, use nflog_size instead. + DESC + }, + nflog_size: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Used with the jump target NFLOG. + The number of bytes to be copied to userspace (only applicable for nfnetlink_log). + nfnetlink_log instances may specify their own size, this option overrides it. + DESC + }, + nflog_threshold: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Used with the jump target NFLOG. + Number of packets to queue inside the kernel before sending them to userspace + (only applicable for nfnetlink_log). Higher values result in less overhead + per packet, but increase delay until the packets reach userspace. Defaults to 1. + DESC + }, + gateway: { + type: 'Optional[Pattern[/^(\d+.\d+.\d+.\d+|\w+:\w+::\w+)$/]]', + desc: <<-DESC + The TEE target will clone a packet and redirect this clone to another + machine on the local network segment. + Gateway is the target host's IP. + DESC + }, + clamp_mss_to_pmtu: { + type: 'Optional[Boolean]', + desc: <<-DESC + Sets the clamp mss to pmtu flag. + DESC + }, + set_mss: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Sets the TCP MSS value for packets. + DESC + }, + set_dscp: { + type: 'Optional[String[1]]', + desc: <<-DESC + Set DSCP Markings. + DESC + }, + set_dscp_class: { + type: "Optional[Enum['af11', 'af12', 'af13', 'af21', 'af22', 'af23', 'af31', 'af32', 'af33', 'af41', 'af42', 'af43', 'cs1', 'cs2', 'cs3', 'cs4', 'cs5', 'cs6', 'cs7', 'ef']]", + desc: <<-DESC + This sets the DSCP field according to a predefined DiffServ class. + DESC + }, + todest: { + type: 'Optional[String[1]]', + desc: <<-DESC + When using jump => "DNAT" you can specify the new destination address using this paramter. + Can specify a single new destination IP address or an inclusive range of IP addresses. + Optionally a port or a port range with a possible follow up baseport can be provided. + Input structure: [ipaddr[-ipaddr]][:port[-port[/baseport]]] + DESC + }, + tosource: { + type: 'Optional[String[1]]', + desc: <<-DESC + When using jump => "SNAT" you can specify the new source address using this paramter. + Can specify a single new destination IP address or an inclusive range of IP addresses. + Input structure: [ipaddr[-ipaddr]][:port[-port]] + DESC + }, + toports: { + type: 'Optional[Variant[Integer[0, 65535], Pattern[/^\d+(?:-\d+)?$/]]]', + desc: <<-DESC + For REDIRECT/MASQUERADE this is the port that will replace the destination/source port. + Can specify a single new port or an inclusive range of ports. + DESC + }, + to: { + type: 'Optional[String[1]]', + desc: <<-DESC + For NETMAP this will replace the destination IP + DESC + }, + checksum_fill: { + type: 'Optional[Boolean]', + desc: <<-DESC + Compute and fill missing packet checksums. + DESC + }, + random_fully: { + type: 'Optional[Boolean]', + desc: <<-DESC + When using a jump value of "MASQUERADE", "DNAT", "REDIRECT", or "SNAT" this boolean will enable fully randomized port mapping. + DESC + }, + random: { + type: 'Optional[Boolean]', + desc: <<-DESC + When using a jump value of "MASQUERADE", "DNAT", "REDIRECT", or "SNAT" this boolean will enable randomized port mapping. + DESC + }, + log_prefix: { + type: 'Optional[String[1]]', + desc: <<-DESC + When combined with jump => "LOG" specifies the log prefix to use when logging. + DESC + }, + log_level: { + type: 'Optional[Variant[Integer[0,7],String[1]]]', + desc: <<-DESC + When combined with jump => "LOG" specifies the system log level to log to. + + Note: log level 4/warn is the default setting and as such it is not returned by iptables-save. + As a result, explicitly setting `log_level` to this can result in idempotency errors. + DESC + }, + log_uid: { + type: 'Optional[Boolean]', + desc: <<-DESC + When combined with jump => "LOG" specifies the uid of the process making the connection. + DESC + }, + log_tcp_sequence: { + type: 'Optional[Boolean]', + desc: <<-DESC + When combined with jump => "LOG" enables logging of the TCP sequence numbers. + DESC + }, + log_tcp_options: { + type: 'Optional[Boolean]', + desc: <<-DESC + When combined with jump => "LOG" logging of the TCP packet header. + DESC + }, + log_ip_options: { + type: 'Optional[Boolean]', + desc: <<-DESC + When combined with jump => "LOG" logging of the TCP IP/IPv6 packet header. + DESC + }, + reject: { + type: "Optional[Enum['icmp-net-unreachable', 'icmp-host-unreachable', 'icmp-port-unreachable', 'icmp-proto-unreachable', + 'icmp-net-prohibited', 'icmp-host-prohibited', 'icmp-admin-prohibited', 'icmp6-no-route', 'no-route', + 'icmp6-adm-prohibited', 'adm-prohibited', 'icmp6-addr-unreachable', 'addr-unreach', 'icmp6-port-unreachable', + 'tcp-reset']]", + desc: <<-DESC + When combined with jump => "REJECT" you can specify a different icmp response to be sent back to the packet sender. + Valid values differ depending on if the protocol is `IPv4` or `IPv6`. + IPv4 allows: icmp-net-unreachable, icmp-host-unreachable, icmp-port-unreachable, icmp-proto-unreachable, icmp-net-prohibited, + icmp-host-prohibited, icmp-admin-prohibited, or tcp-reset. + IPv6 allows: icmp6-no-route, no-route, icmp6-adm-prohibited, adm-prohibited, icmp6-addr-unreachable, addr-unreach, + icmp6-port-unreachable, or tcp-reset. + DESC + }, + set_mark: { + type: 'Optional[Pattern[/^[a-fA-F0-9x]+(?:\/[a-fA-F0-9x]+)?$/]]', + desc: <<-DESC + Set the Netfilter mark value associated with the packet. Accepts either of mark/mask or mark. + These will be converted to hex if they are not already. + DESC + }, + match_mark: { + type: 'Optional[Pattern[/^(?:!\s)?[a-fA-F0-9x]+(?:\/[a-fA-F0-9x]+)?$/]]', + desc: <<-DESC + Match the Netfilter mark value associated with the packet. Accepts either of mark/mask or mark. + This value will be converted to hex if it is not already. + This value can be negated by adding a space seperated `!` to the beginning. + DESC + }, + mss: { + type: 'Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]', + desc: <<-DESC + Match a given TCP MSS value or range. + This value can be negated by adding a space seperated `!` to the beginning. + DESC + }, + connlimit_upto: { + type: 'Optional[Integer]', + desc: <<-DESC + Connection limiting value for matched connections below or equal to n. + DESC + }, + connlimit_above: { + type: 'Optional[Integer]', + desc: <<-DESC + Connection limiting value for matched connections above n. + DESC + }, + connlimit_mask: { + type: 'Optional[Integer[0,128]]', + desc: <<-DESC + Connection limiting by subnet mask for matched connections. + IPv4: 0-32 + IPv6: 0-128 + DESC + }, + connmark: { + type: 'Optional[Pattern[/^(?:!\s)?[a-fA-F0-9x]+(?:\/[a-fA-F0-9x]+)?$/]]', + desc: <<-DESC + Match the Netfilter mark value associated with the packet. Accepts either of mark/mask or mark. + This value will be converted to hex if it is not already. + This value can be negated by adding a space seperated `!` to the beginning. + DESC + }, + time_start: { + type: 'Optional[Pattern[/^([0-9]|[0-1][0-9]|2[0-3])\:[0-5][0-9](?:\:[0-5][0-9])?/]]', + desc: <<-DESC + Only match during the given daytime. The possible time range is 00:00:00 to 23:59:59. + Leading zeroes are allowed (e.g. "06:03") and correctly interpreted as base-10. + DESC + }, + time_stop: { + type: 'Optional[Pattern[/^([0-9]|[0-1][0-9]|2[0-3])\:[0-5][0-9](?:\:[0-5][0-9])?/]]', + desc: <<-DESC + Only match during the given daytime. The possible time range is 00:00:00 to 23:59:59. + Leading zeroes are allowed (e.g. "06:03") and correctly interpreted as base-10. + DESC + }, + month_days: { + type: 'Optional[Variant[Integer[0,31], Array[Integer[0,31]]]]', + desc: <<-DESC + Only match on the given days of the month. Possible values are 1 to 31. + Note that specifying 31 will of course not match on months which do not have a 31st day; + the same goes for 28-day or 29-day February. + + Can be passed either as a single value or an array of values: + month_days => 5, + month_days => [5, 9, 23], + DESC + }, + week_days: { + type: "Optional[Variant[Enum['Mon','Tue','Wed','Thu','Fri','Sat','Sun'], Array[Enum['Mon','Tue','Wed','Thu','Fri','Sat','Sun']]]]", + desc: <<-DESC + Only match on the given weekdays. + + Can be passed either as a single value or an array of values: + week_days => 'Mon', + week_days => ['Mon', 'Tue', 'Wed'], + DESC + }, + date_start: { + type: 'Optional[Pattern[/^[0-9]{4}\-(?:0[0-9]|1[0-2])\-(?:[0-2][0-9]|3[0-1])T(?:[0-1][0-9]|2[0-3])\:[0-5][0-9]\:[0-5][0-9]$/]]', + desc: <<-DESC + Only match during the given time, which must be in ISO 8601 "T" notation. + The possible time range is 1970-01-01T00:00:00 to 2038-01-19T04:17:07 + DESC + }, + date_stop: { + type: 'Optional[Pattern[/^[0-9]{4}\-(?:0[0-9]|1[0-2])\-(?:[0-2][0-9]|3[0-1])T(?:[0-1][0-9]|2[0-3])\:[0-5][0-9]\:[0-5][0-9]$/]]', + desc: <<-DESC + Only match during the given time, which must be in ISO 8601 "T" notation. + The possible time range is 1970-01-01T00:00:00 to 2038-01-19T04:17:07 + DESC + }, + time_contiguous: { + type: 'Optional[Boolean]', + desc: <<-DESC + When time_stop is smaller than time_start value, match this as a single time period instead distinct intervals. + DESC + }, + kernel_timezone: { + type: 'Optional[Boolean]', + desc: <<-DESC + Use the kernel timezone instead of UTC to determine whether a packet meets the time regulations. + DESC + }, + u32: { + type: 'Optional[Pattern[/^0x[0-9a-fA-F]+&0x[0-9a-fA-F]+=0x[0-9a-fA-F]+(?::0x[0-9a-fA-F]+)?(?:&&0x[0-9a-fA-F]+&0x[0-9a-fA-F]+=0x[0-9a-fA-F]+(?::0x[0-9a-fA-F]+)?)*$/]]', + desc: <<-DESC + Enable the u32 module. Takes as an argument one of set, update, + rcheck or remove. For example: + firewall { '032 u32 test': + ensure => present, + table => 'mangle', + chain => 'PREROUTING', + u32 => '0x4&0x1fff=0x0&&0x0&0xf000000=0x5000000', + jump => 'DROP', + } + DESC + }, + src_cc: { + type: 'Optional[Pattern[/^[A-Z]{2}(,[A-Z]{2})*$/]]', + desc: <<-DESC + src attribute for the module geoip + DESC + }, + dst_cc: { + type: 'Optional[Pattern[/^[A-Z]{2}(,[A-Z]{2})*$/]]', + desc: <<-DESC + dst attribute for the module geoip + DESC + }, + hashlimit_upto: { + type: 'Optional[Pattern[/^\d+(?:\/(?:sec|min|hour|day))?$/]]', + desc: <<-DESC + Match if the rate is below or equal to amount/quantum. It is specified either as a number, with an optional time quantum suffix (the default is 3/hour), or as amountb/second (number of bytes per second). + This parameter or `hashlimit_above` and `hashlimit_name` are required when setting any other hashlimit values. + Allowed forms are '40','40/sec','40/min','40/hour','40/day'. + DESC + }, + hashlimit_above: { + type: 'Optional[Pattern[/^\d+(?:\/(?:sec|min|hour|day))?$/]]', + desc: <<-DESC + Match if the rate is above amount/quantum. + This parameter or `hashlimit_upto` and `hashlimit_name` are required when setting any other hashlimit values. + Allowed forms are '40','40/sec','40/min','40/hour','40/day'. + DESC + }, + hashlimit_name: { + type: 'Optional[String[1]]', + desc: <<-DESC + The name for the /proc/net/ipt_hashlimit/foo entry. + This parameter and either `hashlimit_upto` or `hashlimit_above` are required when setting any other hashlimit values. + DESC + }, + hashlimit_burst: { + type: 'Optional[Integer[1]]', + desc: <<-DESC + Maximum initial number of packets to match: this number gets recharged by one every time the limit specified above is not reached, up to this number; the default is 5. + When byte-based rate matching is requested, this option specifies the amount of bytes that can exceed the given rate. + This option should be used with caution -- if the entry expires, the burst value is reset too. + DESC + }, + hashlimit_mode: { + type: 'Optional[Pattern[/^(?:srcip|srcport|dstip|dstport)(?:\,(?:srcip|srcport|dstip|dstport))*$/]]', + desc: <<-DESC + A comma-separated list of objects to take into consideration. + If no --hashlimit-mode option is given, hashlimit acts like limit, but at the expensive of doing the hash housekeeping. + Allowed values are: srcip, srcport, dstip, dstport + DESC + }, + hashlimit_srcmask: { + type: 'Optional[Integer[0,32]]', + desc: <<-DESC + When --hashlimit-mode srcip is used, all source addresses encountered will be grouped according to the given prefix length + and the so-created subnet will be subject to hashlimit. + Prefix must be between (inclusive) 0 and 32. + Note that --hashlimit-srcmask 0 is basically doing the same thing as not specifying srcip for --hashlimit-mode, but is technically more expensive. + DESC + }, + hashlimit_dstmask: { + type: 'Optional[Integer[0,32]]', + desc: <<-DESC + When --hashlimit-mode srcip is used, all destination addresses encountered will be grouped according to the given prefix length + and the so-created subnet will be subject to hashlimit. + Prefix must be between (inclusive) 0 and 32. + Note that --hashlimit-dstmask 0 is basically doing the same thing as not specifying srcip for --hashlimit-mode, but is technically more expensive. + DESC + }, + hashlimit_htable_size: { + type: 'Optional[Integer]', + desc: <<-DESC + The number of buckets of the hash table + DESC + }, + hashlimit_htable_max: { + type: 'Optional[Integer]', + desc: <<-DESC + Maximum entries in the hash. + DESC + }, + hashlimit_htable_expire: { + type: 'Optional[Integer]', + desc: <<-DESC + After how many milliseconds do hash entries expire. + DESC + }, + hashlimit_htable_gcinterval: { + type: 'Optional[Integer]', + desc: <<-DESC + How many milliseconds between garbage collection intervals. + DESC + }, + bytecode: { + type: 'Optional[String[1]]', + desc: <<-DESC + Match using Linux Socket Filter. Expects a BPF program in decimal format. + This is the format generated by the nfbpf_compile utility. + DESC + }, + ipvs: { + type: 'Optional[Boolean]', + desc: <<-DESC + Match using Linux Socket Filter. Expects a BPF program in decimal format. + This is the format generated by the nfbpf_compile utility. + DESC + }, + zone: { + type: 'Optional[Integer]', + desc: <<-DESC + Assign this packet to zone id and only have lookups done in that zone. + DESC + }, + helper: { + type: 'Optional[String[1]]', + desc: <<-DESC + Invoke the nf_conntrack_xxx helper module for this packet. + DESC + }, + cgroup: { + type: 'Optional[String[1]]', + desc: <<-DESC + Matches against the net_cls cgroup ID of the packet. + + To negate add a space seperate `!` to the beginning of the string + DESC + }, + rpfilter: { + type: "Optional[Variant[Enum['loose', 'validmark', 'accept-local', 'invert'], Array[Enum['loose', 'validmark', 'accept-local', 'invert']]]]", + desc: <<-DESC + Enable the rpfilter module. + DESC + }, + condition: { + type: 'Optional[String[1]]', + desc: <<-DESC + Match on boolean value (0/1) stored in /proc/net/nf_condition/name. + DESC + }, + notrack: { + type: 'Optional[Boolean]', + desc: <<-DESC + Invoke the disable connection tracking for this packet. + This parameter can be used with iptables version >= 1.8.3 + DESC + } + }, +) diff --git a/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/type/firewallchain.rb b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/type/firewallchain.rb new file mode 100644 index 0000000..6c86ccc --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/type/firewallchain.rb @@ -0,0 +1,91 @@ +# frozen_string_literal: true + +# lib/puppet/type/firewallchain.rb +require 'puppet/resource_api' + +Puppet::ResourceApi.register_type( + name: 'firewallchain', + features: ['custom_generate', 'custom_insync'], + docs: <<-DESC, + This type provides the capability to manage rule chains for firewalls. + + Currently this supports only iptables, ip6tables and ebtables on Linux. And + provides support for setting the default policy on chains and tables that + allow it. + + #### Providers + * iptables_chain is the only provider that supports firewallchain. + + #### Features + * iptables_chain: The provider provides iptables chain features. + * policy: Default policy (inbuilt chains only). + DESC + attributes: { + ensure: { + type: 'Enum[present, absent]', + default: 'present', + desc: <<-DESC + Whether this chain should be present or absent on the target system. + Setting this to absent will first remove all rules associated with this chain and then delete the chain itself. + Inbuilt chains however will merely remove any added rules and, if it has been changed, return their policy to the default. + DESC + }, + name: { + type: 'Pattern[/^(?:\S+):(?:nat|mangle|filter|raw|rawpost|broute|security):(?:IP(?:v[46])?|ethernet)$/]', + desc: 'The canonical name of the chain with the required format being `{chain}:{table}:{protocol}`.', + behaviour: :namevar + }, + policy: { + type: "Optional[Enum['accept', 'drop', 'queue', 'return']]", + desc: <<-DESC + This action to take when the end of the chain is reached. + This can only be set on inbuilt chains (i.e. INPUT, FORWARD, OUTPUT, + PREROUTING, POSTROUTING) and can be one of: + + * accept - the packet is accepted + * drop - the packet is dropped + * queue - the packet is passed userspace + * return - the packet is returned to calling (jump) queue + or the default of inbuilt chains + DESC + }, + purge: { + type: 'Boolean', + default: false, + desc: 'Whether or not to purge unmanaged rules in this chain' + }, + ignore: { + type: 'Optional[Variant[String[1], Array[String[1]]]]', + desc: <<-DESC + Regex to perform on firewall rules to exempt unmanaged rules from purging. + This is matched against the output of `iptables-save`. + + This can be a single regex, or an array of them. + To support flags, use the ruby inline flag mechanism. + Meaning a regex such as + /foo/i + can be written as + '(?i)foo' or '(?i:foo)' + + Full example: + ``` + firewallchain { 'INPUT:filter:IPv4': + purge => true, + ignore => [ + '-j fail2ban-ssh', # ignore the fail2ban jump rule + '--comment "[^"]*(?i:ignore)[^"]*"', # ignore any rules with "ignore" (case insensitive) in the comment in the rule + ], + } + ``` + DESC + }, + ignore_foreign: { + type: 'Boolean', + default: false, + desc: <<-DESC + Ignore rules that do not match the puppet title pattern "^\d+[[:graph:][:space:]]" when purging unmanaged firewall rules in this chain. + This can be used to ignore rules that were not put in by puppet. Beware that nothing keeps other systems from configuring firewall rules with a comment that starts with digits, and is indistinguishable from puppet-configured rules. + DESC + } + }, +) diff --git a/internal/gentypes/testdata/env/external_modules/grafana/LICENSE b/internal/gentypes/testdata/env/external_modules/grafana/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/grafana/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/provider/grafana_plugin/grafana_cli.rb b/internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/provider/grafana_plugin/grafana_cli.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/type/grafana_plugin.rb b/internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/type/grafana_plugin.rb new file mode 100644 index 0000000..9e97019 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/type/grafana_plugin.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +Puppet::Type.newtype(:grafana_plugin) do + desc <<~DESC + manages grafana plugins + + @example Install a grafana plugin + grafana_plugin { 'grafana-simple-json-datasource': } + + @example Install a grafana plugin from different repo + grafana_plugin { 'grafana-simple-json-datasource': + ensure => 'present', + repo => 'https://nexus.company.com/grafana/plugins', + } + + @example Install a grafana plugin from a plugin url + grafana_plugin { 'grafana-example-custom-plugin': + ensure => 'present', + plugin_url => 'https://github.com/example/example-custom-plugin/zipball/v1.0.0' + } + + @example Uninstall a grafana plugin + grafana_plugin { 'grafana-simple-json-datasource': + ensure => 'absent', + } + + @example Show resources + $ puppet resource grafana_plugin + DESC + + ensurable do + defaultto(:present) + newvalue(:present) do + provider.create + end + newvalue(:absent) do + provider.destroy + end + end + + newparam(:name, namevar: true) do + desc 'The name of the plugin to enable' + newvalues(%r{^\S+$}) + end + + newparam(:repo) do + desc 'The URL of an internal plugin server' + validate do |value| + raise ArgumentError, format('%s is not a valid URL', value) unless value =~ %r{^https?://} + end + end + + newparam(:plugin_url) do + desc 'Full url to the plugin zip file' + validate do |value| + raise ArgumentError, format('%s is not a valid URL', value) unless value =~ %r{^https?://} + end + end +end diff --git a/internal/gentypes/testdata/env/external_modules/inifile/LICENSE b/internal/gentypes/testdata/env/external_modules/inifile/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/inifile/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/inifile/NOTICE b/internal/gentypes/testdata/env/external_modules/inifile/NOTICE new file mode 100644 index 0000000..bb6ff91 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/inifile/NOTICE @@ -0,0 +1,19 @@ +inifile puppet module + +Copyright (C) 2012-2016 Puppet Labs, Inc. +Copyright (C) 2012 Chris Price + +Puppet Labs can be contacted at: info@puppetlabs.com + + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/type/ini_setting.rb b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/type/ini_setting.rb new file mode 100644 index 0000000..53cd5c2 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/type/ini_setting.rb @@ -0,0 +1,153 @@ +# frozen_string_literal: true + +require 'digest/md5' +require 'puppet/parameter/boolean' + +Puppet::Type.newtype(:ini_setting) do + desc 'ini_settings is used to manage a single setting in an INI file' + ensurable do + desc 'Ensurable method handles modeling creation. It creates an ensure property' + newvalue(:present) do + provider.create + end + newvalue(:absent) do + provider.destroy + end + def insync?(current) + if @resource[:refreshonly] + true + else + current == should + end + end + defaultto :present + end + + def munge_boolean_md5(value) + case value + when true, :true, 'true', :yes, 'yes' + :true + when false, :false, 'false', :no, 'no' + :false + when :md5, 'md5' + :md5 + else + raise(_('expected a boolean value or :md5')) + end + end + newparam(:name, namevar: true) do + desc 'An arbitrary name used as the identity of the resource.' + end + + newparam(:section) do + desc 'The name of the section in the ini file in which the setting should be defined.' + defaultto('') + end + + newparam(:setting) do + desc 'The name of the setting to be defined.' + munge do |value| + Puppet.warn('Settings should not have spaces in the value, we are going to strip the whitespace') if value.match?(%r{(^\s|\s$)}) + value.strip + end + end + + newparam(:force_new_section_creation, boolean: true, parent: Puppet::Parameter::Boolean) do + desc 'Create setting only if the section exists' + defaultto(true) + end + + newparam(:path) do + desc 'The ini file Puppet will ensure contains the specified setting.' + validate do |value| + raise(Puppet::Error, _("File paths must be fully qualified, not '%{value}'") % { value: value }) unless Puppet::Util.absolute_path?(value) + end + end + + newparam(:show_diff) do + desc 'Whether to display differences when the setting changes.' + + defaultto :true + + newvalues(:true, :md5, :false) + + munge do |value| + @resource.munge_boolean_md5(value) + end + end + + newparam(:key_val_separator) do + desc 'The separator string to use between each setting name and value.' + defaultto(' = ') + end + + newproperty(:value) do + desc 'The value of the setting to be defined.' + + munge do |value| + value = value.unwrap if value.respond_to?(:unwrap) + if ([true, false].include? value) || value.is_a?(Numeric) + value.to_s + else + value.strip.to_s + end + end + + def should_to_s(newvalue) + if @resource[:show_diff] == :true && Puppet[:show_diff] + newvalue + elsif @resource[:show_diff] == :md5 && Puppet[:show_diff] + "{md5}#{Digest::MD5.hexdigest(newvalue.to_s)}" + else + '[redacted sensitive information]' + end + end + + def is_to_s(value) # rubocop:disable Naming/PredicateName : Changing breaks the code (./.bundle/gems/gems/puppet-5.3.3-universal-darwin/lib/puppet/parameter.rb:525:in `to_s') + should_to_s(value) + end + + def insync?(current) + if @resource[:refreshonly] + true + else + current == should + end + end + end + + newparam(:section_prefix) do + desc 'The prefix to the section name\'s header.' + defaultto('[') + end + + newparam(:section_suffix) do + desc 'The suffix to the section name\'s header.' + defaultto(']') + end + + newparam(:indent_char) do + desc 'The character to indent new settings with.' + defaultto(' ') + end + + newparam(:indent_width) do + desc 'The number of indent_chars to use to indent a new setting.' + end + + newparam(:refreshonly, boolean: true, parent: Puppet::Parameter::Boolean) do + desc 'A flag indicating whether or not the ini_setting should be updated only when called as part of a refresh event' + defaultto false + end + + def refresh + return provider.destroy if self[:ensure] == :absent && self[:refreshonly] + + # update the value in the provider, which will save the value to the ini file + provider.value = self[:value] if self[:refreshonly] + end + + autorequire(:file) do + Pathname.new(self[:path]).parent.to_s + end +end diff --git a/internal/gentypes/testdata/env/external_modules/minio/LICENSE b/internal/gentypes/testdata/env/external_modules/minio/LICENSE new file mode 100644 index 0000000..933cfd4 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/minio/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2016-2017 Kogito UG + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/minio/lib/puppet/provider/minio_client_alias/minio_client_alias.rb b/internal/gentypes/testdata/env/external_modules/minio/lib/puppet/provider/minio_client_alias/minio_client_alias.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/minio/lib/puppet/type/minio_client_alias.rb b/internal/gentypes/testdata/env/external_modules/minio/lib/puppet/type/minio_client_alias.rb new file mode 100644 index 0000000..98aa872 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/minio/lib/puppet/type/minio_client_alias.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true + +require 'puppet/resource_api' + +Puppet::ResourceApi.register_type( + name: 'minio_client_alias', + docs: <<-EOS, +@summary Manages minio client aliases +@example + minio_client_alias { 'localminio': + ensure => 'present', + endpoint => 'http://localhost:9000', + access_key => 'admin', + secret_key => 'password', + api_signature => 'S3v4', + path_lookup_support =>'on', + } + +@example + minio_client_alias { 'default': + ensure => 'present', + endpoint => 'http://localhost:9000', + access_key => 'admin', + secret_key => Sensitive('password'), + } + +**Autorequires**: +* `File[/root/.minioclient]` +EOS + features: ['custom_insync'], + attributes: { + ensure: { + type: 'Enum[present, absent]', + desc: 'Whether this resource should be present or absent on the target system.', + default: 'present', + }, + name: { + type: 'String', + desc: 'The name of the resource you want to manage.', + behaviour: :namevar, + }, + endpoint: { + type: 'String[1]', + desc: 'The API endpoint url', + }, + access_key: { + type: 'Optional[String]', + desc: 'The API access key', + }, + secret_key: { + type: 'Optional[Variant[Sensitive[String], String]]', + desc: 'The API access secret', + }, + api_signature: { + type: "Optional[Enum['S3v4', 'S3v2']]", + desc: 'The API signature', + }, + path_lookup_support: { + type: "Optional[Enum['on', 'off', 'auto']]", + desc: 'Indicate whether dns or path style url requests are supported by the server.', + }, + }, + autorequire: { + file: '/root/.minioclient', + }, +) diff --git a/internal/gentypes/testdata/env/external_modules/mysql/LICENSE b/internal/gentypes/testdata/env/external_modules/mysql/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/mysql/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/mysql/NOTICE b/internal/gentypes/testdata/env/external_modules/mysql/NOTICE new file mode 100644 index 0000000..efe67c4 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/mysql/NOTICE @@ -0,0 +1,15 @@ +Puppet Module - puppetlabs-mysql + +Copyright 2018 Puppet, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/inifile.rb b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/inifile.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/mysql_login_path.rb b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/mysql_login_path.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/sensitive.rb b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/sensitive.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/type/mysql_login_path.rb b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/type/mysql_login_path.rb new file mode 100644 index 0000000..84c8b06 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/type/mysql_login_path.rb @@ -0,0 +1,82 @@ +# frozen_string_literal: true + +require 'puppet/resource_api' + +Puppet::ResourceApi.register_type( + name: 'mysql_login_path', + + docs: <<-DESCRIPTION, + @summary Manage a MySQL login path. + @see + https://dev.mysql.com/doc/refman/8.0/en/mysql-config-editor.html + @example + mysql_login_path { 'local_socket': + owner => 'root', + host => 'localhost', + user => 'root', + password => Sensitive('secure'), + socket => '/var/run/mysql/mysql.sock', + ensure => present, + } + + mysql_login_path { 'local_tcp': + owner => 'root', + host => '127.0.0.1', + user => 'root', + password => Sensitive('more_secure'), + port => 3306, + ensure => present, + } + + This type provides Puppet with the capabilities to store authentication credentials in an obfuscated login path file + named .mylogin.cnf created with the mysql_config_editor utility. Supports only MySQL Community Edition > v5.6.6. + DESCRIPTION + features: ['simple_get_filter', 'canonicalize'], + title_patterns: [ + { + pattern: %r{^(?.*[^-])-(?.*)$}, + desc: 'Where the name of the and the owner are provided with a hyphen seperator' + }, + { + pattern: %r{^(?.*)$}, + desc: 'Where only the name is provided' + }, + ], + attributes: { + ensure: { + type: 'Enum[present, absent]', + desc: 'Whether this resource should be present or absent on the target system.' + }, + name: { + type: 'String', + desc: 'Name of the login path you want to manage.', + behaviour: :namevar + }, + owner: { + type: 'String', + desc: 'The user to whom the logon path should belong.', + behaviour: :namevar, + default: 'root' + }, + host: { + type: 'Optional[String]', + desc: 'Host name to be entered into the login path.' + }, + user: { + type: 'Optional[String]', + desc: 'Username to be entered into the login path.' + }, + password: { + type: 'Optional[Sensitive[String[1]]]', + desc: 'Password to be entered into login path' + }, + socket: { + type: 'Optional[String]', + desc: 'Socket path to be entered into login path' + }, + port: { + type: 'Optional[Integer[0,65535]]', + desc: 'Port number to be entered into login path.' + } + }, +) diff --git a/internal/gentypes/testdata/env/external_modules/network/LICENSE b/internal/gentypes/testdata/env/external_modules/network/LICENSE new file mode 100644 index 0000000..e84166d --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/network/LICENSE @@ -0,0 +1,178 @@ +Copyright 2012 Adrien Thebo + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/interfaces.rb b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/interfaces.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/redhat.rb b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/redhat.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/sles.rb b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/sles.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/type/network_config.rb b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/type/network_config.rb new file mode 100644 index 0000000..92b05e6 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/type/network_config.rb @@ -0,0 +1,155 @@ +require 'puppet/property/boolean' + +begin + require 'ipaddr' +rescue LoadError + Puppet.warning("#{__FILE__}:#{__LINE__}: ipaddr gem was not found") +end + +Puppet::Type.newtype(:network_config) do + @doc = 'Manage non-volatile network configuration information' + + feature :provider_options, <<-EOD + The provider can accept a hash of arbitrary options. The semantics of + these options will depend on the provider. + EOD + + feature :hotpluggable, 'The system can hotplug interfaces' + + feature :reconfigurable, <<-EOD + The provider can update live interface configuration after the non-volatile + network configuration is updated. This may entail a momentary network + disruption as it may mean bringing down the interface for a short period. + EOD + + feature :startmode, 'The system can define startmode of an interface' + + ensurable + + newparam(:name) do + isnamevar + desc 'The name of the physical or logical network device' + end + + newproperty(:ipaddress) do + desc 'The IP address of the network interfaces' + if defined? IPAddr + validate do |value| + IPAddr.new value + rescue IPAddr::InvalidAddressError + raise ArgumentError, "#{self.class} requires a valid ipaddress for the ipaddress property" + # provider.validate + end + end + end + + newproperty(:netmask) do + desc 'The subnet mask to apply to the interface' + if defined? IPAddr + validate do |value| + ipa = IPAddr.new '127.0.0.1' + ipa.mask(value) + rescue IPAddr::InvalidAddressError + begin + ipz = IPAddr.new '::1' + ipz.mask(value) + rescue IPAddr::InvalidAddressError + raise ArgumentError, "#{self.class} requires a valid netmask for the netmask property" + end + # provider.validate + end + end + end + + newproperty(:method) do + desc 'The method for determining an IP address for the interface' + newvalues(:static, :manual, :dhcp, :loopback) + + # Redhat systems frequently use 'none' in place of 'static', although + # ultimately any values but dhcp or bootp are ignored and the interface + # is static + aliasvalue(:none, :static) + + defaultto :dhcp + end + + newproperty(:family) do + desc 'The address family to use for the interface' + newvalues(:inet, :inet6) + aliasvalue(:inet4, :inet) + defaultto :inet + end + + newproperty(:onboot, parent: Puppet::Property::Boolean) do + desc 'Whether to bring the interface up on boot' + defaultto :true + end + + newproperty(:hotplug, required_features: :hotpluggable, parent: Puppet::Property::Boolean) do + desc 'Allow/disallow hotplug support for this interface' + defaultto :true + end + + newproperty(:startmode, required_features: :startmode) do + desc 'Allow/disallow startmode support for this interface' + defaultto :auto + end + + newparam(:reconfigure, required_features: :reconfigurable, parent: Puppet::Property::Boolean) do + desc 'Reconfigure the interface after the configuration has been updated' + end + + newproperty(:mtu) do + desc 'The Maximum Transmission Unit size to use for the interface' + validate do |value| + # reject floating point and negative integers + # XXX this lets 1500.0 pass + if value.is_a? Numeric + raise ArgumentError, "#{value} is not a valid mtu (must be a positive integer)" unless value.integer? + else + raise ArgumentError, "#{value} is not a valid mtu (must be a positive integer)" unless value =~ %r{^\d+$} + end + + # Intel 82598 & 82599 chips support MTUs up to 16110; is there any + # hardware in the wild that supports larger frames? + # + # It appears loopback devices routinely have large MTU values; Eg. 65536 + # + # Frames small than 64bytes are discarded as runts. Smallest valid MTU + # is 42 with a 802.1q header and 46 without. + min_mtu = 42 + max_mtu = 65_536 + raise ArgumentError, "#{value} is not in the valid mtu range (#{min_mtu} .. #{max_mtu})" unless (min_mtu..max_mtu).cover?(value.to_i) + end + end + + newproperty(:mode) do + desc 'The exclusive mode the interface should operate in' + # :bond and :bridge may be added in the future + newvalues(:raw, :vlan) + + defaultto :raw + end + + # `:options` provides an arbitrary passthrough for provider properties, so + # that provider specific behavior doesn't clutter up the main type but still + # allows for more powerful actions to be taken. + newproperty(:options, required_features: :provider_options) do + desc 'Provider specific options to be passed to the provider' + + def s?(hash = @is) + hash.keys.sort.map { |key| "#{key} => #{hash[key]}" }.join(', ') + end + + def should_to_s(hash = @should) + hash.keys.sort.map { |key| "#{key} => #{hash[key]}" }.join(', ') + end + + defaultto {} + + validate do |value| + raise ArgumentError, "#{self.class} requires a hash for the 'options' parameter" unless value.is_a? Hash + # provider.validate + end + end +end diff --git a/internal/gentypes/testdata/env/external_modules/reboot/LICENSE b/internal/gentypes/testdata/env/external_modules/reboot/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/reboot/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/reboot/NOTICE b/internal/gentypes/testdata/env/external_modules/reboot/NOTICE new file mode 100644 index 0000000..fe97fc9 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/reboot/NOTICE @@ -0,0 +1,15 @@ +Puppet Module - puppetlabs-reboot + +Copyright 2013 - 2018 Puppet, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/linux.rb b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/linux.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/posix.rb b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/posix.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/windows.rb b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/windows.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/type/reboot.rb b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/type/reboot.rb new file mode 100644 index 0000000..07e0e33 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/type/reboot.rb @@ -0,0 +1,214 @@ +# frozen_string_literal: true + +Puppet::Type.newtype(:reboot) do + @doc = _(<<-'EOT', + Manages system reboots. The `reboot` type is typically + used in situations where a resource performs a change, e.g. + package install, and a reboot is required to complete + installation. Only if the package is installed should the + reboot be triggered. + + Sample usage: + + package { 'Microsoft .NET Framework 4.5': + ensure => installed, + source => '\\server\share\dotnetfx45_full_x86_x64.exe', + install_options => ['/Passive', '/NoRestart'], + provider => windows, + } + reboot { 'after': + subscribe => Package['Microsoft .NET Framework 4.5'], + } + + A reboot resource can also check if the system is in a + reboot pending state, and if so, reboot the system. For + example, if you have a package that cannot be installed + while a reboot is pending. + + Sample usage: + + reboot { 'before': + when => pending, + } + package { 'Microsoft .NET Framework 4.5': + ensure => installed, + source => '\\server\share\dotnetfx45_full_x86_x64.exe', + install_options => ['/Passive', '/NoRestart'], + provider => windows, + require => Reboot['before'], + } + + A reboot resource can also finish the run and then reboot the system. For + example, if you have a few packages that all require reboots but will not block + each other during the run. + + Sample usage: + + package { 'Microsoft .NET Framework 4.5': + ensure => installed, + source => '\\server\share\dotnetfx45_full_x86_x64.exe', + install_options => ['/Passive', '/NoRestart'], + provider => windows, + } + reboot { 'after_run': + apply => finished, + subscribe => Package['Microsoft .NET Framework 4.5'], + } + + On windows we can limit the reasons for a pending reboot. + + Sample usage: + + reboot { 'renames only': + when => pending, + onlyif => 'pending_rename_file_operations', + } + EOT + ) + + feature :manages_reboot_pending, _('The provider can detect if a reboot is pending, and reboot as needed.') + + newparam(:name) do + desc _('The name of the reboot resource. Used for uniqueness.') + isnamevar + end + + newproperty(:when) do + desc "When to check for, and if needed, perform a reboot. If `pending`, + then the provider will check if a reboot is pending, and only + if needed, reboot the system. If `refreshed` then the reboot + will only be performed in response to a refresh event from + another resource, e.g. `package`." + newvalue(:refreshed) + newvalue(:pending, required_features: :manages_reboot_pending) + defaultto :refreshed + + def insync?(is) + case should + when :refreshed + true # we're always insync + else + super + end + end + end + + newparam(:onlyif, required_features: [:manages_reboot_pending]) do + desc "For pending reboots, only reboot if the reboot is pending + for one of the supplied reasons." + + possible_values = [ + :reboot_required, :component_based_servicing, :windows_auto_update, + :pending_file_rename_operations, :package_installer, + :pending_computer_rename, :pending_dsc_reboot, :pending_ccm_reboot, :pending_domain_join + ] + + validate do |values| + raise ArgumentError, _('There must be at least one element in the list') if values == [] + + values = [values] unless values.is_a?(Array) + + values.each do |value| + value = value.to_sym if value.is_a?(String) + + raise ArgumentError, _("value must be one of %{possible_values.join(', ')}") % { possible_values: 'translateable' } unless possible_values.include?(value) + end + end + + munge do |values| + values = [values] unless values.is_a?(Array) + + values.map(&:to_sym) + end + end + + newparam(:unless, required_features: [:manages_reboot_pending]) do + desc 'For pending reboots, ignore the supplied reasons when checking pennding reboot' + + possible_values = [ + :reboot_required, :component_based_servicing, :windows_auto_update, + :pending_file_rename_operations, :package_installer, + :pending_computer_rename, :pending_dsc_reboot, :pending_ccm_reboot, :pending_domain_join + ] + + validate do |values| + raise ArgumentError, _('There must be at least one element in the list') if values == [] + + values = [values] unless values.is_a?(Array) + + values.each do |value| + value = value.to_sym if value.is_a?(String) + + raise ArgumentError, _("value must be one of %{possible_values.join(', ')}") % { possible_values: 'translateable' } unless possible_values.include?(value) + end + end + + munge do |values| + values = [values] unless values.is_a?(Array) + + values.map(&:to_sym) + end + end + + newparam(:apply) do + desc "When to apply the reboot. If `immediately`, then the provider + will stop applying additional resources and apply the reboot once + puppet has finished syncing. If `finished`, it will continue + applying resources and then perform a reboot at the end of the + run. The default is `immediately`." + newvalues(:immediately, :finished) + defaultto :immediately + end + + newparam(:message) do + desc _('The message to log when the reboot is performed.') + + validate do |value| + raise ArgumentError, _('A non-empty message must be specified.') if value.nil? || value == '' + + # Maximum command line length in Windows is 8191 characters, so this is + # an approximation based on the other parts of the shutdown command + raise ArgumentError, _('The given message must not exceed 8000 characters.') if value.length > 8000 + end + + defaultto 'Puppet is rebooting the computer' + end + + newparam(:timeout) do + desc "The amount of time in seconds to wait between the time the reboot + is requested and when the reboot is performed. The default timeout + is 60 seconds. Note that this time starts once puppet has exited the + current run." + + validate do |value| + raise ArgumentError, _('The timeout must be an integer.') unless %r{^\d+$}.match?(value.to_s) + end + + defaultto 60 + end + + @rebooting = false + + class << self + attr_reader :rebooting + end + + class << self + attr_writer :rebooting + end + + def refresh + case self[:when] + when :refreshed + if self.class.rebooting + Puppet.debug('Reboot already scheduled; skipping') + else + self.class.rebooting = true + Puppet.notice("Scheduling system reboot with message: \"#{self[:message]}\"") + provider.reboot + end + else + Puppet.debug('Skipping reboot') + end + end +end diff --git a/internal/gentypes/testdata/env/external_modules/stdlib/LICENSE b/internal/gentypes/testdata/env/external_modules/stdlib/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/stdlib/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/stdlib/NOTICE b/internal/gentypes/testdata/env/external_modules/stdlib/NOTICE new file mode 100644 index 0000000..3c8c03a --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/stdlib/NOTICE @@ -0,0 +1,23 @@ +stdlib puppet module + +Copyright (C) 2011-2016 Puppet Labs, Inc. + +and some parts: + +Copyright (C) 2011 Krzysztof Wilczynski + + +Puppet Labs can be contacted at: info@puppetlabs.com + + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/provider/file_line/ruby.rb b/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/provider/file_line/ruby.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/type/anchor.rb b/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/type/anchor.rb new file mode 100644 index 0000000..64a111e --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/type/anchor.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +Puppet::Type.newtype(:anchor) do + desc <<-DOC + @summary + A simple resource type intended to be used as an anchor in a composite class. + + > Note: this has been replaced by core puppet `contain()` method. Please see https://puppet.com/docs/puppet/latest/lang_containment.html for more information. + + In Puppet 2.6, when a class declares another class, the resources in the + interior class are not contained by the exterior class. This interacts badly + with the pattern of composing complex modules from smaller classes, as it + makes it impossible for end users to specify order relationships between the + exterior class and other modules. + + The anchor type lets you work around this. By sandwiching any interior + classes between two no-op resources that _are_ contained by the exterior + class, you can ensure that all resources in the module are contained. + + ``` + class ntp { + # These classes will have the correct order relationship with each + # other. However, without anchors, they won't have any order + # relationship to Class['ntp']. + class { 'ntp::package': } + -> class { 'ntp::config': } + -> class { 'ntp::service': } + + # These two resources "anchor" the composed classes within the ntp + # class. + anchor { 'ntp::begin': } -> Class['ntp::package'] + Class['ntp::service'] -> anchor { 'ntp::end': } + } + ``` + + This allows the end user of the ntp module to establish require and before + relationships with Class['ntp']: + + ``` + class { 'ntp': } -> class { 'mcollective': } + class { 'mcollective': } -> class { 'ntp': } + ``` + + DOC + + newparam :name do + desc 'The name of the anchor resource.' + end + def refresh + # We don't do anything with them, but we need this to + # show that we are "refresh aware" and not break the + # chain of propagation. + end +end diff --git a/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/type/file_line.rb b/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/type/file_line.rb new file mode 100644 index 0000000..bcb74f3 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/type/file_line.rb @@ -0,0 +1,194 @@ +# frozen_string_literal: true + +Puppet::Type.newtype(:file_line) do + desc <<-DOC + @summary + Ensures that a given line is contained within a file. + + The implementation matches the full line, including whitespace at the + beginning and end. If the line is not contained in the given file, Puppet + will append the line to the end of the file to ensure the desired state. + Multiple resources may be declared to manage multiple lines in the same file. + + * Ensure Example + ``` + file_line { 'sudo_rule': + path => '/etc/sudoers', + line => '%sudo ALL=(ALL) ALL', + } + + file_line { 'sudo_rule_nopw': + path => '/etc/sudoers', + line => '%sudonopw ALL=(ALL) NOPASSWD: ALL', + } + ``` + In this example, Puppet will ensure both of the specified lines are + contained in the file /etc/sudoers. + + * Match Example + + ``` + file_line { 'bashrc_proxy': + ensure => present, + path => '/etc/bashrc', + line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', + match => '^export HTTP_PROXY=', + } + ``` + + In this code example match will look for a line beginning with export + followed by HTTP_PROXY and replace it with the value in line. + + * Examples With `ensure => absent`: + + This type has two behaviors when `ensure => absent` is set. + + One possibility is to set `match => ...` and `match_for_absence => true`, + as in the following example: + + ``` + file_line { 'bashrc_proxy': + ensure => absent, + path => '/etc/bashrc', + match => '^export HTTP_PROXY=', + match_for_absence => true, + } + ``` + + In this code example match will look for a line beginning with export + followed by HTTP_PROXY and delete it. If multiple lines match, an + error will be raised unless the `multiple => true` parameter is set. + + Note that the `line => ...` parameter would be accepted BUT IGNORED in + the above example. + + The second way of using `ensure => absent` is to specify a `line => ...`, + and no match: + + ``` + file_line { 'bashrc_proxy': + ensure => absent, + path => '/etc/bashrc', + line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', + } + ``` + + > *Note:* + When ensuring lines are absent this way, the default behavior + this time is to always remove all lines matching, and this behavior + can't be disabled. + + * Encoding example: + + ``` + file_line { "XScreenSaver": + ensure => present, + path => '/root/XScreenSaver', + line => "*lock: 10:00:00", + match => '^*lock:', + encoding => "iso-8859-1", + } + ``` + + Files with special characters that are not valid UTF-8 will give the + error message "invalid byte sequence in UTF-8". In this case, determine + the correct file encoding and specify the correct encoding using the + encoding attribute, the value of which needs to be a valid Ruby character + encoding. + + **Autorequires:** If Puppet is managing the file that will contain the line + being managed, the file_line resource will autorequire that file. + DOC + + ensurable do + desc 'Manage the state of this type.' + defaultvalues + defaultto :present + end + + newparam(:name, namevar: true) do + desc 'An arbitrary name used as the identity of the resource.' + end + + newparam(:match) do + desc 'An optional ruby regular expression to run against existing lines in the file. + If a match is found, we replace that line rather than adding a new line. + A regex comparison is performed against the line value and if it does not + match an exception will be raised.' + end + + newparam(:match_for_absence) do + desc 'An optional value to determine if match should be applied when ensure => absent. + If set to true and match is set, the line that matches match will be deleted. + If set to false (the default), match is ignored when ensure => absent. + When `ensure => present`, match_for_absence is ignored.' + newvalues(true, false) + defaultto false + end + + newparam(:multiple) do + desc 'An optional value to determine if match can change multiple lines. + If set to false, an exception will be raised if more than one line matches' + newvalues(true, false) + end + + newparam(:after) do + desc 'An optional value used to specify the line after which we will add any new lines. (Existing lines are added in place) + This is also takes a regex.' + end + + # The line property never changes; the type only ever performs a create() or + # destroy(). line is a property in order to allow it to correctly handle + # Sensitive type values. Because it is a property which will never change, + # it should never be considered out of sync. + newproperty(:line) do + desc 'The line to be appended to the file or used to replace matches found by the match attribute.' + + def retrieve + @resource[:line] + end + end + + newparam(:path) do + desc 'The file Puppet will ensure contains the line specified by the line parameter.' + validate do |value| + raise Puppet::Error, "File paths must be fully qualified, not '#{value}'" unless Puppet::Util.absolute_path?(value) + end + end + + newparam(:replace) do + desc 'If true, replace line that matches. If false, do not write line if a match is found' + newvalues(true, false) + defaultto true + end + + newparam(:replace_all_matches_not_matching_line) do + desc 'Configures the behavior of replacing all lines in a file which match the `match` parameter regular expression, regardless of whether the specified line is already present in the file.' + + newvalues(true, false) + defaultto false + end + + newparam(:encoding) do + desc 'For files that are not UTF-8 encoded, specify encoding such as iso-8859-1' + defaultto 'UTF-8' + end + + newparam(:append_on_no_match) do + desc 'If true, append line if match is not found. If false, do not append line if a match is not found' + newvalues(true, false) + defaultto true + end + + # Autorequire the file resource if it's being managed + autorequire(:file) do + self[:path] + end + validate do + raise(Puppet::Error, 'multiple must be true when replace_all_matches_not_matching_line is true') if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:multiple].to_s == 'false' + raise(Puppet::Error, 'replace must be true when replace_all_matches_not_matching_line is true') if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:replace].to_s == 'false' + + raise(Puppet::Error, 'line is a required attribute') if !self[:line] && !((self[:ensure].to_s == 'absent') && (self[:match_for_absence].to_s == 'true') && self[:match]) + raise(Puppet::Error, 'path is a required attribute') unless self[:path] + end +end diff --git a/internal/gentypes/testdata/env/external_modules/yumrepo_core/LICENSE b/internal/gentypes/testdata/env/external_modules/yumrepo_core/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/yumrepo_core/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb b/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/type/yumrepo.rb b/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/type/yumrepo.rb new file mode 100644 index 0000000..3502bc4 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/type/yumrepo.rb @@ -0,0 +1,462 @@ +require 'uri' + +Puppet::Type.newtype(:yumrepo) do + @doc = <<-'EOT' + @summary The client-side description of a yum repository. + + Repository configurations are found by parsing `/etc/yum.conf` and the files + indicated by the `reposdir` option in that file (see `yum.conf(5)` for + details). + + Most parameters are identical to the ones documented + in the `yum.conf(5)` man page. + + Continuation lines that yum supports (for the `baseurl`, for example) + are not supported. This type does not attempt to read or verify the + existence of files listed in the `include` attribute." + + EOT + + # Ensure yumrepos can be removed too. + ensurable + # Doc string for properties that can be made 'absent' + ABSENT_DOC = 'Set this to `absent` to remove it from the file completely.'.freeze + # False can be false/0/no and True can be true/1/yes in yum. + YUM_BOOLEAN = %r{^(true|false|0|1|no|yes)$}.freeze + YUM_BOOLEAN_DOC = 'Valid values are: false/0/no or true/1/yes.'.freeze + + # Common munge logic for YUM_BOOLEAN values. Munges for two requirements: + # 1) Because of how regex validation works in Puppet::Parameter::Value, + # Boolean false and lowercase false will not be considered invalid. However, + # if the user specified false (or true), they meant False (or True). + # 2) In order for parameter removal to work correctly, when absent is passed + # as a string it needs to be munged back to a symbol. + munge_yum_bool = proc do |val| + (val.to_s == 'absent') ? :absent : val.to_s.capitalize + end + + VALID_SCHEMES = ['file', 'http', 'https', 'ftp'].freeze + + newparam(:name, namevar: true) do + desc "The name of the repository. This corresponds to the + `repositoryid` parameter in `yum.conf(5)`." + end + + newparam(:target) do + desc 'The filepath of the local repository file, can be either relative or absolute. If a valid filepath is not specified, the target is created as a new section in `yum.conf(5)`' + + defaultto :absent + end + + newproperty(:descr) do + desc "A human-readable description of the repository. + This corresponds to the name parameter in `yum.conf(5)`. + #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + end + + newproperty(:mirrorlist) do + desc "The URL that holds the list of mirrors for this repository. + #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + validate do |value| + next if value.to_s == 'absent' + parsed = URI.parse(value) + + unless VALID_SCHEMES.include?(parsed.scheme) + raise _('Must be a valid URL') + end + end + end + + newproperty(:baseurl) do + desc "The URL for this repository. #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + validate do |value| + next if value.to_s == 'absent' + + value.split(%r{\s+}).each do |uri| + parsed = URI.parse(uri) + + unless VALID_SCHEMES.include?(parsed.scheme) + raise _('Must be a valid URL') + end + end + end + end + + newproperty(:enabled) do + desc "Whether this repository is enabled. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:gpgcheck) do + desc "Whether to check the GPG signature on packages installed + from this repository. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:payload_gpgcheck) do + desc "Whether to check the GPG signature of the packages payload. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:repo_gpgcheck) do + desc "Whether to check the GPG signature on repodata. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:gpgkey) do + desc "The URL for the GPG key with which packages from this + repository are signed. #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + validate do |value| + next if value.to_s == 'absent' + + value.split(%r{\s+}).each do |uri| + parsed = URI.parse(uri) + + unless VALID_SCHEMES.include?(parsed.scheme) + raise _('Must be a valid URL') + end + end + end + end + + newproperty(:mirrorlist_expire) do + desc "Time (in seconds) after which the mirrorlist locally cached + will expire.\n#{ABSENT_DOC}" + + newvalues(%r{^[0-9]+$}, :absent) + end + + newproperty(:include) do + desc "The URL of a remote file containing additional yum configuration + settings. Puppet does not check for this file's existence or validity. + #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + validate do |value| + next if value.to_s == 'absent' + parsed = URI.parse(value) + + unless VALID_SCHEMES.include?(parsed.scheme) + raise _('Must be a valid URL') + end + end + end + + newproperty(:exclude) do + desc "The string of package names or shell globs separated by spaces to exclude. + Packages that match the package name given or shell globs will never be + considered in updates or installs for this repo. + #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + end + + newproperty(:gpgcakey) do + desc "The URL for the GPG CA key for this repository. #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + validate do |value| + next if value.to_s == 'absent' + parsed = URI.parse(value) + + unless VALID_SCHEMES.include?(parsed.scheme) + raise _('Must be a valid URL') + end + end + end + + newproperty(:includepkgs) do + desc "The string of package names or shell globs separated by spaces to + include. If this is set, only packages matching one of the package + names or shell globs will be considered for update or install + from this repository. #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + end + + newproperty(:enablegroups) do + desc "Whether yum will allow the use of package groups for this + repository. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:module_hotfixes) do + desc "Whether packages from this repo can be installed into modules. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:failovermethod) do + desc "The failover method for this repository; should be either + `roundrobin` or `priority`. #{ABSENT_DOC}" + + newvalues(%r{^roundrobin|priority$}, :absent) + end + + newproperty(:keepalive) do + desc "Whether HTTP/1.1 keepalive should be used with this repository. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:retries) do + desc "Set the number of times any attempt to retrieve a file should + retry before returning an error. Setting this to `0` makes yum + try forever.\n#{ABSENT_DOC}" + + newvalues(%r{^[0-9]+$}, :absent) + end + + newproperty(:http_caching) do + desc "What to cache from this repository. #{ABSENT_DOC}" + + newvalues(%r{^(packages|all|none)$}, :absent) + end + + newproperty(:timeout) do + desc "Number of seconds to wait for a connection before timing + out. #{ABSENT_DOC}" + + newvalues(%r{^\d+$}, :absent) + end + + newproperty(:metadata_expire) do + desc "Number of seconds after which the metadata will expire. + #{ABSENT_DOC}" + + newvalues(%r{^([0-9]+[dhm]?|never)$}, :absent) + end + + newproperty(:protect) do + desc "Enable or disable protection for this repository. Requires + that the `protectbase` plugin is installed and enabled. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:priority) do + desc "Priority of this repository. Can be any integer value + (including negative). Requires that the `priorities` plugin + is installed and enabled. + #{ABSENT_DOC}" + + newvalues(%r{^-?\d+$}, :absent) + end + + newproperty(:minrate) do + desc "Sets the low speed threshold in bytes per second. + If the server is sending data slower than this for at least + `timeout` seconds, Yum aborts the connection. The default is + `1000`. + #{ABSENT_DOC}" + + newvalues(%r{^\d+$}, :absent) + end + + newproperty(:throttle) do + desc "Enable bandwidth throttling for downloads. This option + can be expressed as a absolute data rate in bytes/sec or a + percentage `60%`. An SI prefix (k, M or G) may be appended + to the data rate values.\n#{ABSENT_DOC}" + + newvalues(%r{^\d+[kMG%]?$}, :absent) + end + + newproperty(:bandwidth) do + desc "Use to specify the maximum available network bandwidth + in bytes/second. Used with the `throttle` option. If `throttle` + is a percentage and `bandwidth` is `0` then bandwidth throttling + will be disabled. If `throttle` is expressed as a data rate then + this option is ignored.\n#{ABSENT_DOC}" + + newvalues(%r{^\d+[kMG]?$}, :absent) + end + + newproperty(:cost) do + desc "Cost of this repository. #{ABSENT_DOC}" + + newvalues(%r{^\d+$}, :absent) + end + + newproperty(:proxy) do + desc "URL of a proxy server that Yum should use when accessing this repository. + This attribute can also be set to '_none_' (or '' for EL >= 8 only), + which will make Yum bypass any global proxy settings when accessing this repository. + #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + validate do |value| + next if %r{^(absent|_none_)$}.match?(value.to_s) + next if value.to_s.empty? && Facter.value('os.release.major').to_i >= 8 + + parsed = URI.parse(value) + unless VALID_SCHEMES.include?(parsed.scheme) + raise _('Must be a valid URL') + end + end + + munge do |value| + return '' if Facter.value('os.distro.release.major').to_i >= 8 && value.to_s == '_none_' + super(value) + end + end + + newproperty(:proxy_username) do + desc "Username for this proxy. #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + end + + newproperty(:proxy_password) do + desc "Password for this proxy. #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + end + + newproperty(:s3_enabled) do + desc "Access the repository via S3. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:sslcacert) do + desc "Path to the directory containing the databases of the + certificate authorities yum should use to verify SSL certificates. + #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + end + + newproperty(:sslverify) do + desc "Should yum verify SSL certificates/hosts at all. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:sslclientcert) do + desc "Path to the SSL client certificate yum should use to connect + to repositories/remote sites. #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + end + + newproperty(:sslclientkey) do + desc "Path to the SSL client key yum should use to connect + to repositories/remote sites. #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + end + + newproperty(:metalink) do + desc "Metalink for mirrors. #{ABSENT_DOC}" + + newvalues(%r{.*}, :absent) + validate do |value| + next if value.to_s == 'absent' + parsed = URI.parse(value) + + unless VALID_SCHEMES.include?(parsed.scheme) + raise _('Must be a valid URL') + end + end + end + + newproperty(:skip_if_unavailable) do + desc "Should yum skip this repository if unable to reach it. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:assumeyes) do + desc "Determines if yum prompts for confirmation of critical actions. + #{YUM_BOOLEAN_DOC} + #{ABSENT_DOC}" + + newvalues(YUM_BOOLEAN, :absent) + munge(&munge_yum_bool) + end + + newproperty(:deltarpm_percentage) do + desc "Percentage value that determines when to use deltas for this repository. + When the delta is larger than this percentage value of the package, the + delta is not used. + #{ABSENT_DOC}" + + newvalues(%r{^\d+$}, :absent) + end + + newproperty(:deltarpm_metadata_percentage) do + desc "Percentage value that determines when to download deltarpm metadata. + When the deltarpm metadata is larger than this percentage value of the + package, deltarpm metadata is not downloaded. + #{ABSENT_DOC}" + + newvalues(%r{^\d+$}, :absent) + end + + newproperty(:username) do + desc "Username to use for basic authentication to a repo or really any url. + #{ABSENT_DOC}" + newvalues(%r{.*}, :absent) + end + + newproperty(:password) do + desc "Password to use with the username for basic authentication. + #{ABSENT_DOC}" + newvalues(%r{.*}, :absent) + end + + private + + def set_sensitive_parameters(sensitive_parameters) + parameter(:password).sensitive = true if parameter(:password) + parameter(:proxy_password).sensitive = true if parameter(:proxy_password) + super(sensitive_parameters) + end +end diff --git a/internal/gentypes/testdata/golden/alternative_entry.pp b/internal/gentypes/testdata/golden/alternative_entry.pp new file mode 100644 index 0000000..0cc560b --- /dev/null +++ b/internal/gentypes/testdata/golden/alternative_entry.pp @@ -0,0 +1,47 @@ +# This file was automatically generated on 2026-11-08 17:31:23 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'alternative_entry', + [ + # The basic property that the resource should be in. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # The name of the generic symlink for this alternative entry as parameter. This is readonly. + Puppet::Resource::Param(Any, 'altlink_ro'), + + # The name of symlink in the alternatives directory + Puppet::Resource::Param(Any, 'altname'), + + # The value of the priority of this alternative + Puppet::Resource::Param(Any, 'priority') + ], + [ + # The path to the actual alternative + Puppet::Resource::Param(Any, 'name', true), + + # The name of the generic symlink for this alternative entry + Puppet::Resource::Param(Any, 'altlink', true), + + # The specific backend to use for this `alternative_entry` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # chkconfig + # : * Required binaries: `/usr/sbin/alternatives`. + # * Default for `os.family` == `redhat`. + # + # dpkg + # : * Required binaries: `update-alternatives`. + # * Default for `{"os.name"=>[:debian, :ubuntu], "os.family"=>:suse}` == ``. + Puppet::Resource::Param(Any, 'provider') + ], + { + /^([^:]+)$/ => ['name'], + /(?i-mx:^(.*):([a-z]:(\/|\\).*)$)/ => ['name', 'altlink'], + /^(.*):(.*)$/ => ['name', 'altlink'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/alternatives.pp b/internal/gentypes/testdata/golden/alternatives.pp new file mode 100644 index 0000000..3fa748d --- /dev/null +++ b/internal/gentypes/testdata/golden/alternatives.pp @@ -0,0 +1,40 @@ +# This file was automatically generated on 2026-11-08 17:31:23 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'alternatives', + [ + # The path of the desired source for the given alternative. On RedHat, a family can be specified instead + Puppet::Resource::Param(Any, 'path'), + + # Use the automatic option for this alternative + # + # Valid values are `auto`, `manual`. + # + # Requires features mode. + Puppet::Resource::Param(Enum['auto', 'manual'], 'mode') + ], + [ + # The name of the alternative. + Puppet::Resource::Param(Any, 'name'), + + # The specific backend to use for this `alternatives` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # chkconfig + # : * Required binaries: `alternatives`. + # * Default for `os.family` == `redhat`. + # * Supported features: `mode`. + # + # dpkg + # : * Required binaries: `update-alternatives`. + # * Default for `{"os.name"=>[:debian, :ubuntu], "os.family"=>:suse}` == ``. + # * Supported features: `mode`. + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/anchor.pp b/internal/gentypes/testdata/golden/anchor.pp new file mode 100644 index 0000000..1c78094 --- /dev/null +++ b/internal/gentypes/testdata/golden/anchor.pp @@ -0,0 +1,55 @@ +# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# @summary +# A simple resource type intended to be used as an anchor in a composite class. +# +# > Note: this has been replaced by core puppet `contain()` method. Please see https://puppet.com/docs/puppet/latest/lang_containment.html for more information. +# +# In Puppet 2.6, when a class declares another class, the resources in the +# interior class are not contained by the exterior class. This interacts badly +# with the pattern of composing complex modules from smaller classes, as it +# makes it impossible for end users to specify order relationships between the +# exterior class and other modules. +# +# The anchor type lets you work around this. By sandwiching any interior +# classes between two no-op resources that _are_ contained by the exterior +# class, you can ensure that all resources in the module are contained. +# +# ``` +# class ntp { +# # These classes will have the correct order relationship with each +# # other. However, without anchors, they won't have any order +# # relationship to Class['ntp']. +# class { 'ntp::package': } +# -> class { 'ntp::config': } +# -> class { 'ntp::service': } +# +# # These two resources "anchor" the composed classes within the ntp +# # class. +# anchor { 'ntp::begin': } -> Class['ntp::package'] +# Class['ntp::service'] -> anchor { 'ntp::end': } +# } +# ``` +# +# This allows the end user of the ntp module to establish require and before +# relationships with Class['ntp']: +# +# ``` +# class { 'ntp': } -> class { 'mcollective': } +# class { 'mcollective': } -> class { 'ntp': } +# ``` +Puppet::Resource::ResourceType3.new( + 'anchor', + [ + + ], + [ + # The name of the anchor resource. + Puppet::Resource::Param(Any, 'name') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/archive.pp b/internal/gentypes/testdata/golden/archive.pp new file mode 100644 index 0000000..67771af --- /dev/null +++ b/internal/gentypes/testdata/golden/archive.pp @@ -0,0 +1,143 @@ +# This file was automatically generated on 2026-11-08 17:31:23 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# Manage archive file download, extraction, and cleanup. +Puppet::Resource::ResourceType3.new( + 'archive', + [ + # whether archive file should be present/absent (default: present) + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # if file/directory exists, will not download/extract archive. + Puppet::Resource::Param(Any, 'creates') + ], + [ + # namevar, archive file fully qualified file path. + Puppet::Resource::Param(Any, 'path', true), + + # archive file name (derived from path). + Puppet::Resource::Param(Any, 'filename'), + + # whether archive will be extracted after download (true|false). + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'extract'), + + # target folder path to extract archive. + Puppet::Resource::Param(Any, 'extract_path'), + + # target folder path to extract archive. (this parameter is for camptocamp/archive compatibility) + Puppet::Resource::Param(Any, 'target'), + + # custom extraction command ('tar xvf example.tar.gz'), also support sprintf format ('tar xvf %s') which will be processed with the filename: sprintf('tar xvf %s', filename) + Puppet::Resource::Param(Any, 'extract_command'), + + # Specify an alternative temporary directory to use for copying files, if unset then the operating system default will be used. + Puppet::Resource::Param(Any, 'temp_dir'), + + # custom extraction options, this replaces the default flags. A string such as 'xvf' for a tar file would replace the default xf flag. A hash is useful when custom flags are needed for different platforms. {'tar' => 'xzf', '7z' => 'x -aot'}. + Puppet::Resource::Param(Any, 'extract_flags'), + + # whether archive file will be removed after extraction (true|false). + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'cleanup'), + + # archive file source, supports puppet|http|https|ftp|file|s3|gs uri. + Puppet::Resource::Param(Any, 'source'), + + # archive file source, supports http|https|ftp|file uri. + # (for camptocamp/archive compatibility) + Puppet::Resource::Param(Any, 'url'), + + # archive file download cookie. + Puppet::Resource::Param(Any, 'cookie'), + + # archive file checksum (match checksum_type). + # + # Valid values are `true`, `false`, `undef`, ``, ``. Values can match `/\b[0-9a-f]{5,128}\b/`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'undef', '', ''], Pattern[/\b[0-9a-f]{5,128}\b/]], 'checksum'), + + # archive file checksum (match checksum_type) + # (this parameter is for camptocamp/archive compatibility). + # + # Values can match `/\b[0-9a-f]{5,128}\b/`. + Puppet::Resource::Param(Pattern[/\b[0-9a-f]{5,128}\b/], 'digest_string'), + + # archive file checksum source (instead of specifying checksum) + Puppet::Resource::Param(Any, 'checksum_url'), + + # archive file checksum source (instead of specifying checksum) + # (this parameter is for camptocamp/archive compatibility) + Puppet::Resource::Param(Any, 'digest_url'), + + # archive file checksum type (none|md5|sha1|sha2|sha256|sha384|sha512). + # + # Valid values are `none`, `md5`, `sha1`, `sha2`, `sha256`, `sha384`, `sha512`. + Puppet::Resource::Param(Enum['none', 'md5', 'sha1', 'sha2', 'sha256', 'sha384', 'sha512'], 'checksum_type'), + + # archive file checksum type (none|md5|sha1|sha2|sha256|sha384|sha512) + # (this parameter is camptocamp/archive compatibility). + # + # Valid values are `none`, `md5`, `sha1`, `sha2`, `sha256`, `sha384`, `sha512`. + Puppet::Resource::Param(Enum['none', 'md5', 'sha1', 'sha2', 'sha256', 'sha384', 'sha512'], 'digest_type'), + + # whether checksum wil be verified (true|false). + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'checksum_verify'), + + # username to download source file. + Puppet::Resource::Param(Any, 'username'), + + # password to download source file. + Puppet::Resource::Param(Any, 'password'), + + # optional header(s) to pass. + Puppet::Resource::Param(Any, 'headers'), + + # extract command user (using this option will configure the archive file permission to 0644 so the user can read the file). + Puppet::Resource::Param(Any, 'user'), + + # extract command group (using this option will configure the archive file permisison to 0644 so the user can read the file). + Puppet::Resource::Param(Any, 'group'), + + # proxy type (none|ftp|http|https) + # + # Valid values are `none`, `ftp`, `http`, `https`. + Puppet::Resource::Param(Enum['none', 'ftp', 'http', 'https'], 'proxy_type'), + + # proxy address to use when accessing source + Puppet::Resource::Param(Any, 'proxy_server'), + + # ignore HTTPS certificate errors + # + # Valid values are `true`, `false`, `yes`, `no`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'allow_insecure'), + + # provider download options (affects curl, wget, gs, and only s3 downloads for ruby provider) + Puppet::Resource::Param(Any, 'download_options'), + + # The specific backend to use for this `archive` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # curl + # : * Required binaries: `curl`. + # * Default for `feature` == `posix`. + # + # ruby + # : * Required binaries: `aws`, `gsutil`. + # * Default for `feature` == `microsoft_windows`. + # + # wget + # : * Required binaries: `wget`. + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['path'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/concat_file.pp b/internal/gentypes/testdata/golden/concat_file.pp new file mode 100644 index 0000000..6c5709e --- /dev/null +++ b/internal/gentypes/testdata/golden/concat_file.pp @@ -0,0 +1,114 @@ +# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# @summary +# Generates a file with content from fragments sharing a common unique tag. +# +# @example +# Concat_fragment <<| tag == 'unique_tag' |>> +# +# concat_file { '/tmp/file': +# tag => 'unique_tag', # Optional. Default to undef +# path => '/tmp/file', # Optional. If given it overrides the resource name +# owner => 'root', # Optional. Default to undef +# group => 'root', # Optional. Default to undef +# mode => '0644' # Optional. Default to undef +# order => 'numeric' # Optional, Default to 'numeric' +# ensure_newline => false # Optional, Defaults to false +# } +Puppet::Resource::ResourceType3.new( + 'concat_file', + [ + # Specifies whether the destination file should exist. Setting to 'absent' tells Puppet to delete the destination file if it exists, and + # negates the effect of any other parameters. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure') + ], + [ + # Required. Specifies a unique tag reference to collect all concat_fragments with the same tag. + Puppet::Resource::Param(Any, 'tag'), + + # Specifies a destination file for the combined fragments. Valid options: a string containing an absolute path. Default value: the + # title of your declared resource. + Puppet::Resource::Param(Any, 'path', true), + + # Specifies the owner of the destination file. Valid options: a string containing a username or integer containing a uid. + Puppet::Resource::Param(Any, 'owner'), + + # Specifies a permissions group for the destination file. Valid options: a string containing a group name or integer containing a + # gid. + Puppet::Resource::Param(Any, 'group'), + + # Specifies the permissions mode of the destination file. Valid options: a string containing a permission mode value in octal notation. + Puppet::Resource::Param(Any, 'mode'), + + # Specifies a method for sorting your fragments by name within the destination file. You can override this setting for individual + # fragments by adjusting the order parameter in their concat::fragment declarations. + # + # Valid values are `alpha`, `numeric`. + Puppet::Resource::Param(Enum['alpha', 'numeric'], 'order'), + + # Specifies whether (and how) to back up the destination file before overwriting it. Your value gets passed on to Puppet's native file + # resource for execution. Valid options: true, false, or a string representing either a target filebucket or a filename extension + # beginning with ".".' + Puppet::Resource::Param(Any, 'backup'), + + # Specifies whether to overwrite the destination file if it already exists. + # + # Valid values are `true`, `false`, `yes`, `no`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'replace'), + + # Specifies a validation command to apply to the destination file. Requires Puppet version 3.5 or newer. Valid options: a string to + # be passed to a file resource. + Puppet::Resource::Param(Any, 'validate_cmd'), + + # Specifies whether to add a line break at the end of each fragment that doesn't already end in one. + # + # Valid values are `true`, `false`, `yes`, `no`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'ensure_newline'), + + # Specify what data type to merge the fragments as. Valid options: 'plain', 'yaml', 'json', 'json-array', 'json-pretty', 'json-array-pretty'. + # + # Valid values are `plain`, `yaml`, `json`, `json-array`, `json-pretty`, `json-array-pretty`. + Puppet::Resource::Param(Enum['plain', 'yaml', 'json', 'json-array', 'json-pretty', 'json-array-pretty'], 'format'), + + # Specifies whether to merge data structures, keeping the values with higher order. + # + # Valid values are `true`, `false`, `yes`, `no`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'force'), + + # See the file type's selinux_ignore_defaults documentention: + # https://docs.puppetlabs.com/references/latest/type.html#file-attribute-selinux_ignore_defaults. + # + # Valid values are `true`, `false`, `yes`, `no`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'selinux_ignore_defaults'), + + # See the file type's selrange documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-selrange + Puppet::Resource::Param(Any, 'selrange'), + + # See the file type's selrole documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-selrole + Puppet::Resource::Param(Any, 'selrole'), + + # See the file type's seltype documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-seltype + Puppet::Resource::Param(Any, 'seltype'), + + # See the file type's seluser documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-seluser + Puppet::Resource::Param(Any, 'seluser'), + + # Specifies whether to set the show_diff parameter for the file resource. Useful for hiding secrets stored in hiera from insecure + # reporting methods. + # + # Valid values are `true`, `false`, `yes`, `no`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'show_diff'), + + # Specifies whether to create an empty file if no fragments are defined. + # + # Valid values are `true`, `false`, `yes`, `no`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'create_empty_file') + ], + { + /(?m-ix:(.*))/ => ['path'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/file_line.pp b/internal/gentypes/testdata/golden/file_line.pp new file mode 100644 index 0000000..1843f83 --- /dev/null +++ b/internal/gentypes/testdata/golden/file_line.pp @@ -0,0 +1,178 @@ +# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# @summary +# Ensures that a given line is contained within a file. +# +# The implementation matches the full line, including whitespace at the +# beginning and end. If the line is not contained in the given file, Puppet +# will append the line to the end of the file to ensure the desired state. +# Multiple resources may be declared to manage multiple lines in the same file. +# +# * Ensure Example +# ``` +# file_line { 'sudo_rule': +# path => '/etc/sudoers', +# line => '%sudo ALL=(ALL) ALL', +# } +# +# file_line { 'sudo_rule_nopw': +# path => '/etc/sudoers', +# line => '%sudonopw ALL=(ALL) NOPASSWD: ALL', +# } +# ``` +# In this example, Puppet will ensure both of the specified lines are +# contained in the file /etc/sudoers. +# +# * Match Example +# +# ``` +# file_line { 'bashrc_proxy': +# ensure => present, +# path => '/etc/bashrc', +# line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', +# match => '^export HTTP_PROXY=', +# } +# ``` +# +# In this code example match will look for a line beginning with export +# followed by HTTP_PROXY and replace it with the value in line. +# +# * Examples With `ensure => absent`: +# +# This type has two behaviors when `ensure => absent` is set. +# +# One possibility is to set `match => ...` and `match_for_absence => true`, +# as in the following example: +# +# ``` +# file_line { 'bashrc_proxy': +# ensure => absent, +# path => '/etc/bashrc', +# match => '^export HTTP_PROXY=', +# match_for_absence => true, +# } +# ``` +# +# In this code example match will look for a line beginning with export +# followed by HTTP_PROXY and delete it. If multiple lines match, an +# error will be raised unless the `multiple => true` parameter is set. +# +# Note that the `line => ...` parameter would be accepted BUT IGNORED in +# the above example. +# +# The second way of using `ensure => absent` is to specify a `line => ...`, +# and no match: +# +# ``` +# file_line { 'bashrc_proxy': +# ensure => absent, +# path => '/etc/bashrc', +# line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', +# } +# ``` +# +# > *Note:* +# When ensuring lines are absent this way, the default behavior +# this time is to always remove all lines matching, and this behavior +# can't be disabled. +# +# * Encoding example: +# +# ``` +# file_line { "XScreenSaver": +# ensure => present, +# path => '/root/XScreenSaver', +# line => "*lock: 10:00:00", +# match => '^*lock:', +# encoding => "iso-8859-1", +# } +# ``` +# +# Files with special characters that are not valid UTF-8 will give the +# error message "invalid byte sequence in UTF-8". In this case, determine +# the correct file encoding and specify the correct encoding using the +# encoding attribute, the value of which needs to be a valid Ruby character +# encoding. +# +# **Autorequires:** If Puppet is managing the file that will contain the line +# being managed, the file_line resource will autorequire that file. +Puppet::Resource::ResourceType3.new( + 'file_line', + [ + # Manage the state of this type. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # The line to be appended to the file or used to replace matches found by the match attribute. + Puppet::Resource::Param(Any, 'line') + ], + [ + # An arbitrary name used as the identity of the resource. + Puppet::Resource::Param(Any, 'name', true), + + # An optional ruby regular expression to run against existing lines in the file. + # If a match is found, we replace that line rather than adding a new line. + # A regex comparison is performed against the line value and if it does not + # match an exception will be raised. + Puppet::Resource::Param(Any, 'match'), + + # An optional value to determine if match should be applied when ensure => absent. + # If set to true and match is set, the line that matches match will be deleted. + # If set to false (the default), match is ignored when ensure => absent. + # When `ensure => present`, match_for_absence is ignored. + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'match_for_absence'), + + # An optional value to determine if match can change multiple lines. + # If set to false, an exception will be raised if more than one line matches + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'multiple'), + + # An optional value used to specify the line after which we will add any new lines. (Existing lines are added in place) + # This is also takes a regex. + Puppet::Resource::Param(Any, 'after'), + + # The file Puppet will ensure contains the line specified by the line parameter. + Puppet::Resource::Param(Any, 'path'), + + # If true, replace line that matches. If false, do not write line if a match is found + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'replace'), + + # Configures the behavior of replacing all lines in a file which match the `match` parameter regular expression, regardless of whether the specified line is already present in the file. + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'replace_all_matches_not_matching_line'), + + # For files that are not UTF-8 encoded, specify encoding such as iso-8859-1 + Puppet::Resource::Param(Any, 'encoding'), + + # If true, append line if match is not found. If false, do not append line if a match is not found + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'append_on_no_match'), + + # The specific backend to use for this `file_line` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # ruby + # : @summary + # This type allows puppet to manage small config files. + # + # The implementation matches the full line, including whitespace at the + # beginning and end. If the line is not contained in the given file, Puppet + # will append the line to the end of the file to ensure the desired state. + # Multiple resources may be declared to manage multiple lines in the same file. + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/firewall.pp b/internal/gentypes/testdata/golden/firewall.pp new file mode 100644 index 0000000..596ddfe --- /dev/null +++ b/internal/gentypes/testdata/golden/firewall.pp @@ -0,0 +1,1408 @@ +# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# This type provides the capability to manage firewall rules within puppet via iptables. +# +# **Autorequires:** +# +# If Puppet is managing the iptables chains specified in the +# `chain` or `jump` parameters, the firewall resource will autorequire +# those firewallchain resources. +# +# If Puppet is managing the iptables, iptables-persistent, or iptables-services packages, +# the firewall resource will autorequire those packages to ensure that any required binaries are +# installed. +# +# #### Providers +# * Required binaries: iptables-save, iptables. +# * Default for kernel == linux. +# * Supported features: address_type, clusterip, connection_limiting, conntrack, dnat, icmp_match, +# interface_match, iprange, ipsec_dir, ipsec_policy, ipset, iptables, isfragment, length, +# log_level, log_prefix, log_uid, log_tcp_sequence, log_tcp_options, log_ip_options, +# mark, mask, mss, netmap, nflog_group, nflog_prefix, +# nflog_range, nflog_threshold, owner, pkttype, queue_bypass, queue_num, rate_limiting, +# recent_limiting, reject_type, snat, socket, state_match, string_matching, tcp_flags, bpf. +# +# #### Features +# * address_type: The ability to match on source or destination address type. +# +# * clusterip: Configure a simple cluster of nodes that share a certain IP and MAC address without an explicit load balancer in front of them. +# +# * condition: Match if a specific condition variable is (un)set (requires xtables-addons) +# +# * connection_limiting: Connection limiting features. +# +# * conntrack: Connection tracking features. +# +# * dnat: Destination NATing. +# +# * hop_limiting: Hop limiting features. +# +# * icmp_match: The ability to match ICMP types. +# +# * interface_match: Interface matching. +# +# * iprange: The ability to match on source or destination IP range. +# +# * ipsec_dir: The ability to match IPsec policy direction. +# +# * ipsec_policy: The ability to match IPsec policy. +# +# * iptables: The provider provides iptables features. +# +# * isfirstfrag: The ability to match the first fragment of a fragmented ipv6 packet. +# +# * isfragment: The ability to match fragments. +# +# * ishasmorefrags: The ability to match a non-last fragment of a fragmented ipv6 packet. +# +# * islastfrag: The ability to match the last fragment of an ipv6 packet. +# +# * length: The ability to match the length of the layer-3 payload. +# +# * log_level: The ability to control the log level. +# +# * log_prefix: The ability to add prefixes to log messages. +# +# * log_uid: The ability to log the userid of the process which generated the packet. +# +# * log_tcp_sequence: The ability to log TCP sequence numbers. +# +# * log_tcp_options: The ability to log TCP packet header. +# +# * log_ip_options: The ability to log IP/IPv6 packet header. +# +# * mark: The ability to match or set the netfilter mark value associated with the packet. +# +# * mask: The ability to match recent rules based on the ipv4 mask. +# +# * nflog_group: The ability to set the group number for NFLOG. +# +# * nflog_prefix: The ability to set a prefix for nflog messages. +# +# * nflog_size: Set the max size of a message to send to nflog. +# +# * nflog_threshold: The ability to set nflog_threshold. +# +# * owner: The ability to match owners. +# +# * pkttype: The ability to match a packet type. +# +# * rate_limiting: Rate limiting features. +# +# * recent_limiting: The netfilter recent module. +# +# * reject_type: The ability to control reject messages. +# +# * set_mss: Set the TCP MSS of a packet. +# +# * snat: Source NATing. +# +# * socket: The ability to match open sockets. +# +# * state_match: The ability to match stateful firewall states. +# +# * string_matching: The ability to match a given string by using some pattern matching strategy. +# +# * tcp_flags: The ability to match on particular TCP flag settings. +# +# * netmap: The ability to map entire subnets via source or destination nat rules. +# +# * hashlimit: The ability to use the hashlimit-module. +# +# * bpf: The ability to use Berkeley Paket Filter rules. +# +# * ipvs: The ability to match IP Virtual Server packets. +# +# * ct_target: The ability to set connection tracking parameters for a packet or its associated connection. +# +# * random_fully: The ability to use --random-fully flag. +Puppet::Resource::ResourceType3.new( + 'firewall', + [ + # Whether this rule should be present or absent on the target system. + # (a Enum[present, absent, 'present', 'absent']) + Puppet::Resource::Param(Any, 'ensure'), + + # The protocol used to set the rule, it's allowed values have been expanded to bring it closer to its `firewallchain` counterpart. + # Defaults to `IPv4` + # + # Noted: this was previously defined as `provider`, however the resource_api does not allow this to be used as an attribute title. + # (a Enum['iptables', 'ip6tables', 'IPv4', 'IPv6']) + Puppet::Resource::Param(Any, 'protocol'), + + # The table the rule will exist in. + # Valid options are: + # + # * nat + # * mangle + # * filter + # * raw + # * rawpost + # + # Defaults to 'filter' + # (a Enum['nat', 'mangle', 'filter', 'raw', 'rawpost', 'broute', 'security']) + Puppet::Resource::Param(Any, 'table'), + + # Name of the chain the rule will be a part of, ensure the chain you choose exists within your set table. + # Can be one of the built-in chains: + # + # * INPUT + # * FORWARD + # * OUTPUT + # * PREROUTING + # * POSTROUTING + # + # Or you can provide a user-based chain. + # Defaults to 'INPUT' + # (a String[1]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'chain'), + + # The source address. For example: + # + # source => '192.168.2.0/24' + # + # You can also negate a mask by putting ! in front. For example: + # + # source => '! 192.168.2.0/24' + # + # The source can also be an IPv6 address if your provider supports it. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'source'), + + # The destination address to match. For example: + # + # destination => '192.168.1.0/24' + # + # You can also negate a mask by putting ! in front. For example: + # + # destination => '! 192.168.2.0/24' + # + # The destination can also be an IPv6 address if your provider supports it. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'destination'), + + # Input interface to filter on. Supports interface alias like eth0:0. + # To negate the match try this: + # + # iniface => '! lo', + # (a Optional[Pattern[/^(?:!\s)?[a-zA-Z0-9\-\._\+\:@]+$/]]) + Puppet::Resource::Param(Any, 'iniface'), + + # Output interface to filter on. Supports interface alias like eth0:0. + # To negate the match try this: + # + # outiface => '! lo', + # (a Optional[Pattern[/^(?:!\s)?[a-zA-Z0-9\-\._\+\:@]+$/]]) + Puppet::Resource::Param(Any, 'outiface'), + + # Match if the packet is entering a bridge from the given interface. + # To negate the match try this: + # + # physdev_in => '! lo', + # (a Optional[Pattern[/^(?:!\s)?[a-zA-Z0-9\-\._\+]+$/]]) + Puppet::Resource::Param(Any, 'physdev_in'), + + # Match if the packet is leaving a bridge via the given interface. + # To negate the match try this: + # + # physdev_out => '! lo', + # (a Optional[Pattern[/^(?:!\s)?[a-zA-Z0-9\-\._\+]+$/]]) + Puppet::Resource::Param(Any, 'physdev_out'), + + # Match if the packet is transversing a bridge. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'physdev_is_bridged'), + + # Matches if the packet has entered through a bridge interface. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'physdev_is_in'), + + # Matches if the packet will leave through a bridge interface. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'physdev_is_out'), + + # The specific protocol to match for this rule. + # (a Optional[Pattern[/^(?:!\s)?(?:ip(?:encap)?|tcp|udp|icmp|esp|ah|vrrp|carp|igmp|ipv4|ospf|gre|cbt|sctp|pim|all)/]]) + Puppet::Resource::Param(Any, 'proto'), + + # Set to true to match tcp fragments (requires proto to be set to tcp) + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'isfragment'), + + # Matches if the packet is the first fragment. + # Specific to IPv6. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'isfirstfrag'), + + # Matches if the packet has it's 'more fragments' bit set. + # Specific to IPv6. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'ishasmorefrags'), + + # Matches if the packet is the last fragment. + # Specific to IPv6. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'islastfrag'), + + # Set the matching mode for statistic matching. + # (a Optional[Enum[nth, random]]) + Puppet::Resource::Param(Any, 'stat_mode'), + + # Match one packet every nth packet. Requires `stat_mode => 'nth'` + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'stat_every'), + + # Set the initial counter value for the nth mode. Must be between 0 and the value of `stat_every`. + # Defaults to 0. Requires `stat_mode => 'nth'` + # (a Optional[Integer]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'stat_packet'), + + # Set the probability from 0 to 1 for a packet to be randomly matched. It works only with `stat_mode => 'random'`. + # (a Optional[Variant[Integer[0,1], Float[0.0,1.0]]]) + Puppet::Resource::Param(Any, 'stat_probability'), + + # The source IP range. For example: + # + # src_range => '192.168.1.1-192.168.1.10' + # + # You can also negate the range by apending a `!`` to the front. For example: + # + # src_range => '! 192.168.1.1-192.168.1.10' + # + # The source IP range must be in 'IP1-IP2' format. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'src_range'), + + # The destination IP range. For example: + # + # dst_range => '192.168.1.1-192.168.1.10' + # + # You can also negate the range by putting ! in front. For example: + # + # dst_range => '! 192.168.1.1-192.168.1.10' + # + # The destination IP range must be in 'IP1-IP2' format. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'dst_range'), + + # Match when the TCP option is present or absent. + # Given as a single TCP option, optionally prefixed with '! ' to match + # on absence instead. Only one TCP option can be matched in a given rule. + # TCP option numbers are an eight-bit field, so valid option numbers range + # from 0-255. + # (a Optional[Variant[Pattern[/^(?:!\s)?(?:[0-1][0-9]{0,2}|2[0-4][0-9]|25[0-5])$/], Integer[0,255]]]) + Puppet::Resource::Param(Any, 'tcp_option'), + + # Match when the TCP flags are as specified. + # Is a string with a list of comma-separated flag names for the mask, + # then a space, then a comma-separated list of flags that should be set. + # The flags are: FIN SYN RST PSH ACK URG ALL NONE + # Note that you specify them in the order that iptables --list-rules + # would list them to avoid having puppet think you changed the flags. + # + # Example: FIN,SYN,RST,ACK SYN matches packets with the SYN bit set and the + # ACK,RST and FIN bits cleared. Such packets are used to request + # TCP connection initiation. + # Can be negated by placing ! in front, i.e. + # ! FIN,SYN,RST,ACK SYN + # (a Optional[Pattern[/^(?:!\s)?((FIN|SYN|RST|PSH|ACK|URG|ALL|NONE),?)+\s((FIN|SYN|RST|PSH|ACK|URG|ALL|NONE),?)+$/]]) + Puppet::Resource::Param(Any, 'tcp_flags'), + + # UID or Username owner matching rule. Accepts a single argument + # only, as iptables does not accept multiple uid in a single + # statement. + # To negate add a space seperated '!' in front of the value. + # (a Optional[Variant[String[1], Integer]]) + Puppet::Resource::Param(Any, 'uid'), + + # GID or Group owner matching rule. Accepts a single argument + # only, as iptables does not accept multiple gid in a single + # statement. + # To negate add a space seperated '!' in front of the value. + # (a Optional[Variant[String[1], Integer]]) + Puppet::Resource::Param(Any, 'gid'), + + # MAC Source + # (a Optional[Pattern[/^(?:!\s)?([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})$/]]) + Puppet::Resource::Param(Any, 'mac_source'), + + # The source port to match for this filter (if the protocol supports + # ports). Will accept a single element or an array. + # + # For some firewall providers you can pass a range of ports in the format: + # + # sport => '1:1024' + # + # This would cover ports 1 to 1024. + # + # You can also negate a port by putting ! in front. For example: + # + # sport => '! 54' + # + # If you wish to negate multiple ports at once, then place a ! at the start of the first array + # variable. For example: + # + # sport => ['! 54','23'] + # + # Note: + # This will negate all passed ports, it is not possible to negate a single one of the array. + # In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + # (a Optional[Variant[Array[Variant[Pattern[/^(?:!\s)?\d+(?:(?:\:|-)\d+)?$/],Integer]],Pattern[/^(?:!\s)?\d+(?:(?:\:|-)\d+)?$/],Integer]]) + Puppet::Resource::Param(Any, 'sport'), + + # The source port to match for this filter (if the protocol supports + # ports). Will accept a single element or an array. + # + # For some firewall providers you can pass a range of ports in the format: + # + # dport => '1:1024' + # + # This would cover ports 1 to 1024. + # + # You can also negate a port by putting ! in front. For example: + # + # dport => '! 54' + # + # If you wish to negate multiple ports at once, then place a ! at the start of the first array + # variable. For example: + # + # dport => ['! 54','23'] + # + # Note: + # This will negate all passed ports, it is not possible to negate a single one of the array. + # In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + # (a Optional[Variant[Array[Variant[Pattern[/^(?:!\s)?\d+(?:(?:\:|-)\d+)?$/],Integer]],Pattern[/^(?:!\s)?\d+(?:(?:\:|-)\d+)?$/],Integer]]) + Puppet::Resource::Param(Any, 'dport'), + + # The source address type. For example: + # + # src_type => 'LOCAL' + # + # Can be one of: + # + # * UNSPEC - an unspecified address + # * UNICAST - a unicast address + # * LOCAL - a local address + # * BROADCAST - a broadcast address + # * ANYCAST - an anycast packet + # * MULTICAST - a multicast address + # * BLACKHOLE - a blackhole address + # * UNREACHABLE - an unreachable address + # * PROHIBIT - a prohibited address + # * THROW - undocumented + # * NAT - undocumented + # * XRESOLVE - undocumented + # + # In addition, it accepts '--limit-iface-in' and '--limit-iface-out' flags, specified as: + # + # src_type => ['LOCAL --limit-iface-in'] + # + # It can also be negated using '!': + # + # src_type => ['! LOCAL'] + # + # Will accept a single element or an array. Each element of the array should be negated seperately. + # (a Optional[Variant[ + # Array[Pattern[/^(?:!\s)?(?:UNSPEC|UNICAST|LOCAL|BROADCAST|ANYCAST|MULTICAST|BLACKHOLE|UNREACHABLE|UNREACHABLE|PROHIBIT|THROW|NAT|XRESOLVE)(?:\s--limit-iface-(?:in|out))?$/]], + # Pattern[/^(?:!\s)?(?:UNSPEC|UNICAST|LOCAL|BROADCAST|ANYCAST|MULTICAST|BLACKHOLE|UNREACHABLE|UNREACHABLE|PROHIBIT|THROW|NAT|XRESOLVE)(?:\s--limit-iface-(?:in|out))?$/]]]) + Puppet::Resource::Param(Any, 'src_type'), + + # The destination address type. For example: + # + # dst_type => ['LOCAL'] + # + # Can be one of: + # + # * UNSPEC - an unspecified address + # * UNICAST - a unicast address + # * LOCAL - a local address + # * BROADCAST - a broadcast address + # * ANYCAST - an anycast packet + # * MULTICAST - a multicast address + # * BLACKHOLE - a blackhole address + # * UNREACHABLE - an unreachable address + # * PROHIBIT - a prohibited address + # * THROW - undocumented + # * NAT - undocumented + # * XRESOLVE - undocumented + # + # In addition, it accepts '--limit-iface-in' and '--limit-iface-out' flags, specified as: + # + # dst_type => ['LOCAL --limit-iface-in'] + # + # Each value can be negated seperately using '!': + # + # dst_type => ['! UNICAST', '! LOCAL'] + # + # Will accept a single element or an array. + # (a Optional[Variant[ + # Array[Pattern[/^(?:!\s)?(?:UNSPEC|UNICAST|LOCAL|BROADCAST|ANYCAST|MULTICAST|BLACKHOLE|UNREACHABLE|UNREACHABLE|PROHIBIT|THROW|NAT|XRESOLVE)(?:\s--limit-iface-(?:in|out))?$/]], + # Pattern[/^(?:!\s)?(?:UNSPEC|UNICAST|LOCAL|BROADCAST|ANYCAST|MULTICAST|BLACKHOLE|UNREACHABLE|UNREACHABLE|PROHIBIT|THROW|NAT|XRESOLVE)(?:\s--limit-iface-(?:in|out))?$/]]]) + Puppet::Resource::Param(Any, 'dst_type'), + + # If true, matches if an open socket can be found by doing a coket lookup + # on the packet. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'socket'), + + # Sets the packet type to match. + # (a Optional[Enum['unicast', 'broadcast', 'multicast']]) + Puppet::Resource::Param(Any, 'pkttype'), + + # Sets the ipsec policy direction + # (a Optional[Enum['in', 'out']]) + Puppet::Resource::Param(Any, 'ipsec_dir'), + + # Sets the ipsec policy type. May take a combination of arguments for any flags that can be passed to `--pol ipsec` such as: `--strict`, `--reqid 100`, `--next`, `--proto esp`, etc. + # (a Optional[Enum['none', 'ipsec']]) + Puppet::Resource::Param(Any, 'ipsec_policy'), + + # Matches a packet based on its state in the firewall stateful inspection + # table. Values can be: + # + # * INVALID + # * ESTABLISHED + # * NEW + # * RELATED + # * UNTRACKED + # * SNAT + # * DNAT + # + # Can be passed either as a single String or as an Array: + # + # state => 'INVALID' + # state => ['INVALID', 'ESTABLISHED'] + # + # Values can be negated by adding a '!'. + # If you wish to negate multiple states at once, then place a ! at the start of the first array + # variable. For example: + # + # state => ['! INVALID', 'ESTABLISHED'] + # + # Note: + # This will negate all passed states, it is not possible to negate a single one of the array. + # In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + # (a Optional[Variant[Pattern[/^(?:!\s)?(?:INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED)$/], Array[Pattern[/^(?:!\s)?(?:INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED)$/]]]]) + Puppet::Resource::Param(Any, 'state'), + + # Matches a packet based on its state in the firewall stateful inspection + # table, using the conntrack module. Values can be: + # + # * INVALID + # * ESTABLISHED + # * NEW + # * RELATED + # * UNTRACKED + # * SNAT + # * DNAT + # + # Can be passed either as a single String or as an Array, if passed as an array values should be passed in order: + # + # ctstate => 'INVALID' + # ctstate => ['INVALID', 'ESTABLISHED'] + # + # Values can be negated by adding a '!'. + # If you wish to negate multiple states at once, then place a ! at the start of the first array + # variable. For example: + # + # ctstate => ['! INVALID', 'ESTABLISHED'] + # + # Note: + # This will negate all passed states, it is not possible to negate a single one of the array. + # In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + # (a Optional[Variant[Pattern[/^(?:!\s)?(?:INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED|SNAT|DNAT)$/], Array[Pattern[/^(?:!\s)?(?:INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED|SNAT|DNAT)$/]]]]) + Puppet::Resource::Param(Any, 'ctstate'), + + # The specific layer-4 protocol number to match for this rule using the + # conntrack module. + # (a Optional[Variant[Pattern[/^(?:!\s)?\d+$/],Integer]]) + Puppet::Resource::Param(Any, 'ctproto'), + + # The original source address using the conntrack module. For example: + # + # ctorigsrc => '192.168.2.0/24' + # + # You can also negate a mask by putting ! in front. For example: + # + # ctorigsrc => '! 192.168.2.0/24' + # + # The ctorigsrc can also be an IPv6 address if your provider supports it. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'ctorigsrc'), + + # The original destination address using the conntrack module. For example: + # + # ctorigdst => '192.168.2.0/24' + # + # You can also negate a mask by putting ! in front. For example: + # + # ctorigdst => '! 192.168.2.0/24' + # + # The ctorigdst can also be an IPv6 address if your provider supports it. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'ctorigdst'), + + # The reply source address using the conntrack module. For example: + # + # ctreplsrc => '192.168.2.0/24' + # + # You can also negate a mask by putting ! in front. For example: + # + # ctreplsrc => '! 192.168.2.0/24' + # + # The ctreplsrc can also be an IPv6 address if your provider supports it. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'ctreplsrc'), + + # The reply destination address using the conntrack module. For example: + # + # ctrepldst => '192.168.2.0/24' + # + # You can also negate a mask by putting ! in front. For example: + # + # ctrepldst => '! 192.168.2.0/24' + # + # The ctrepldst can also be an IPv6 address if your provider supports it. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'ctrepldst'), + + # The original source port to match for this filter using the conntrack module. + # For example: + # + # ctorigsrcport => '80' + # + # You can also specify a port range: For example: + # + # ctorigsrcport => '80:81' + # + # You can also negate a port by putting ! in front. For example: + # + # ctorigsrcport => '! 80' + # (a Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]) + Puppet::Resource::Param(Any, 'ctorigsrcport'), + + # The original destination port to match for this filter using the conntrack module. + # For example: + # + # ctorigdstport => '80' + # + # You can also specify a port range: For example: + # + # ctorigdstport => '80:81' + # + # You can also negate a port by putting ! in front. For example: + # + # ctorigdstport => '! 80' + # (a Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]) + Puppet::Resource::Param(Any, 'ctorigdstport'), + + # The reply source port to match for this filter using the conntrack module. + # For example: + # + # ctreplsrcport => '80' + # + # You can also specify a port range: For example: + # + # ctreplsrcport => '80:81' + # + # You can also negate a port by putting ! in front. For example: + # + # ctreplsrcport => '! 80' + # (a Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]) + Puppet::Resource::Param(Any, 'ctreplsrcport'), + + # The reply destination port to match for this filter using the conntrack module. + # For example: + # + # ctrepldstport => '80' + # + # You can also specify a port range: For example: + # + # ctrepldstport => '80:81' + # + # You can also negate a port by putting ! in front. For example: + # + # ctrepldstport => '! 80' + # (a Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]) + Puppet::Resource::Param(Any, 'ctrepldstport'), + + # Matches a packet based on its status using the conntrack module. Values can be: + # + # * EXPECTED + # * SEEN_REPLY + # * ASSURED + # * CONFIRMED + # * NONE + # + # Can be passed either as a single String or as an Array: + # + # ctstatus => 'EXPECTED' + # ctstatus => ['EXPECTED', 'CONFIRMED'] + # + # Values can be negated by adding a '!'. + # If you wish to negate multiple states at once, then place a ! at the start of the first array + # variable. For example: + # + # ctstatus => ['! EXPECTED', 'CONFIRMED'] + # + # Note: + # This will negate all passed states, it is not possible to negate a single one of the array. + # In order to maintain compatibility it is also possible to negate all values given in the array to achieve the same behaviour. + # (a Optional[Variant[Pattern[/^(?:!\s)?(?:EXPECTED|SEEN_REPLY|ASSURED|CONFIRMED|NONE)$/], Array[Pattern[/^(?:!\s)?(?:EXPECTED|SEEN_REPLY|ASSURED|CONFIRMED|NONE)$/]]]]) + Puppet::Resource::Param(Any, 'ctstatus'), + + # Matches a packet based on lifetime remaining in seconds or range of seconds + # using the conntrack module. For example: + # + # ctexpire => '100' + # ctexpire => '100:150' + # (a Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]) + Puppet::Resource::Param(Any, 'ctexpire'), + + # Matches a packet that is flowing in the specified direction using the + # conntrack module. If this flag is not specified at all, matches packets + # in both directions. Values can be: + # + # * REPLY + # * ORIGINAL + # (a Optional[Enum['REPLY', 'ORIGINAL']]) + Puppet::Resource::Param(Any, 'ctdir'), + + # Hop limiting value for matched packets. + # To negate add a space seperated `!` the the beginning of the value + # This is IPv6 specific. + # (a Optional[Variant[Pattern[/^(?:!\s)?\d+$/],Integer]]) + Puppet::Resource::Param(Any, 'hop_limit'), + + # When matching ICMP packets, this is the type of ICMP packet to match. + # + # A value of "any" is not supported. To achieve this behaviour the + # parameter should simply be omitted or undefined. + # An array of values is also not supported. To match against multiple ICMP + # types, please use separate rules for each ICMP type. + # (a Optional[Variant[String[1],Integer]]) + Puppet::Resource::Param(Any, 'icmp'), + + # Rate limiting value for matched packets. The format is: + # rate/[/second/|/minute|/hour|/day] + # + # Example values are: '50/sec', '40/min', '30/hour', '10/day'." + # (a Optional[Pattern[/^\d+\/(?:sec(?:ond)?|min(?:ute)?|hour|day)$/]]) + Puppet::Resource::Param(Any, 'limit'), + + # Rate limiting burst value (per second) before limit checks apply. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'burst'), + + # Sets the length of layer-3 payload to match. + # + # Example values are: '500', '5:400' + # (a Optional[Pattern[/^([0-9]+)(:)?([0-9]+)?$/]]) + Puppet::Resource::Param(Any, 'length'), + + # Enable the recent module. Takes as an argument one of set, update, + # rcheck or remove. For example: + # + # ``` + # # If anyone's appeared on the 'badguy' blacklist within + # # the last 60 seconds, drop their traffic, and update the timestamp. + # firewall { '100 Drop badguy traffic': + # recent => 'update', + # rseconds => 60, + # rsource => true, + # rname => 'badguy', + # jump => 'DROP', + # chain => 'FORWARD', + # } + # ``` + # + # + # ``` + # # No-one should be sending us traffic on eth0 from the + # # localhost, Blacklist them + # firewall { '101 blacklist strange traffic': + # recent => 'set', + # rsource => true, + # rname => 'badguy', + # destination => '127.0.0.0/8', + # iniface => 'eth0', + # jump => 'DROP', + # chain => 'FORWARD', + # } + # ``` + # (a Optional[Enum['set', 'update', 'rcheck', 'remove', '! set', '! update', '! rcheck', '! remove']]) + Puppet::Resource::Param(Any, 'recent'), + + # Recent module; used in conjunction with one of `recent => 'rcheck'` or + # `recent => 'update'`. When used, this will narrow the match to only + # happen when the address is in the list and was seen within the last given + # number of seconds. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'rseconds'), + + # Recent module; can only be used in conjunction with the `rseconds` + # attribute. When used, this will cause entries older than 'seconds' to be + # purged. Must be boolean true. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'reap'), + + # Recent module; used in conjunction with `recent => 'update'` or `recent + # => 'rcheck'. When used, this will narrow the match to only happen when + # the address is in the list and packets had been received greater than or + # equal to the given value. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'rhitcount'), + + # Recent module; may only be used in conjunction with one of `recent => + # 'rcheck'` or `recent => 'update'`. When used, this will narrow the match + # to only happen when the address is in the list and the TTL of the current + # packet matches that of the packet which hit the `recent => 'set'` rule. + # This may be useful if you have problems with people faking their source + # address in order to DoS you via this module by disallowing others access + # to your site by sending bogus packets to you. Must be boolean true. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'rttl'), + + # Recent module; The name of the list. + # The recent module defaults this to `DEFAULT` when recent is set + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'rname'), + + # Recent module; sets the mask to use when `recent` is enabled. + # The recent module defaults this to `255.255.255.255` when recent is set + # (a Optional[Pattern[/^\d+\.\d+\.\d+\.\d+$/]]) + Puppet::Resource::Param(Any, 'mask'), + + # Recent module; add the source IP address to the list. + # Mutually exclusive with `rdest` + # The recent module defaults this behaviour to true when recent is set. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'rsource'), + + # Recent module; add the destination IP address to the list. + # Mutually exclusive with `rsource` + # Must be boolean true. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'rdest'), + + # Matches against the specified ipset list. + # Requires ipset kernel module. Will accept a single element or an array. + # The value is the name of the denylist, followed by a space, and then + # 'src' and/or 'dst' separated by a comma. + # For example: 'denylist src,dst' + # To negate simply place a space seperated `!` at the beginning of a value. + # Values can de negated independently. + # (a Optional[Variant[Pattern[/^(?:!\s)?[\w\-:_]+\s(?:src|dst)(?:,src|,dst)?$/], Array[Pattern[/^(?:!\s)?[\w\-:_]+\s(?:src|dst)(?:,src|,dst)?$/]]]]) + Puppet::Resource::Param(Any, 'ipset'), + + # String matching feature. Matches the packet against the pattern + # given as an argument. + # To negate, add a space seperated `!` to the beginning of the string. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'string'), + + # String matching feature. Matches the packet against the pattern + # given as an argument. + # To negate, add a space seperated `!` to the beginning of the string. + # (a Optional[Pattern[/^(?:!\s)?\|[a-zA-Z0-9\s]+\|$/]]) + Puppet::Resource::Param(Any, 'string_hex'), + + # String matching feature, pattern matching strategy. + # (a Optional[Enum['bm', 'kmp']]) + Puppet::Resource::Param(Any, 'string_algo'), + + # String matching feature, offset from which we start looking for any matching. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'string_from'), + + # String matching feature, offset up to which we should scan. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'string_to'), + + # This value for the iptables --jump parameter and the action to perform on a match. Common values are: + # + # * ACCEPT - the packet is accepted + # * REJECT - the packet is rejected with a suitable ICMP response + # * DROP - the packet is dropped + # + # But can also be one of the following: + # + # * QUEUE + # * RETURN + # * DNAT + # * SNAT + # * LOG + # * NFLOG + # * NETMAP + # * MASQUERADE + # * REDIRECT + # * MARK + # * CT + # + # And any valid chain name is also allowed. + # + # If you specify no value it will simply match the rule but perform no action. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'jump'), + + # The value for the iptables --goto parameter. Normal values are: + # + # * QUEUE + # * RETURN + # * DNAT + # * SNAT + # * LOG + # * MASQUERADE + # * REDIRECT + # * MARK + # + # But any valid chain name is allowed. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'goto'), + + # Used with the CLUSTERIP jump target. + # Create a new ClusterIP. You always have to set this on the first rule for a given ClusterIP. + # This is IPv4 specific. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'clusterip_new'), + + # Used with the CLUSTERIP jump target. + # Specify the hashing mode. + # This is IPv4 specific. + # (a Optional[Enum['sourceip', 'sourceip-sourceport', 'sourceip-sourceport-destport']]) + Puppet::Resource::Param(Any, 'clusterip_hashmode'), + + # Used with the CLUSTERIP jump target. + # Specify the ClusterIP MAC address. Has to be a link-layer multicast address. + # This is IPv4 specific. + # (a Optional[Pattern[/^([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})$/]]) + Puppet::Resource::Param(Any, 'clusterip_clustermac'), + + # Used with the CLUSTERIP jump target. + # Number of total nodes within this cluster. + # This is IPv4 specific. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'clusterip_total_nodes'), + + # Used with the CLUSTERIP jump target. + # Specify the random seed used for hash initialization. + # This is IPv4 specific. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'clusterip_local_node'), + + # Used with the CLUSTERIP jump target. + # Specify the random seed used for hash initialization. + # This is IPv4 specific. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'clusterip_hash_init'), + + # Used with NFQUEUE jump target. + # What queue number to send packets to + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'queue_num'), + + # Allow packets to bypass :queue_num if userspace process is not listening + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'queue_bypass'), + + # Used with the jump target NFLOG. + # The netlink group (0 - 2^16-1) to which packets are (only applicable + # for nfnetlink_log). Defaults to 0. + # (a Optional[Integer[1, 65535]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'nflog_group'), + + # Used with the jump target NFLOG. + # A prefix string to include in the log message, up to 64 characters long, + # useful for distinguishing messages in the logs. + # (a Optional[String]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'nflog_prefix'), + + # Used with the jump target NFLOG. + # This has never worked, use nflog_size instead. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'nflog_range'), + + # Used with the jump target NFLOG. + # The number of bytes to be copied to userspace (only applicable for nfnetlink_log). + # nfnetlink_log instances may specify their own size, this option overrides it. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'nflog_size'), + + # Used with the jump target NFLOG. + # Number of packets to queue inside the kernel before sending them to userspace + # (only applicable for nfnetlink_log). Higher values result in less overhead + # per packet, but increase delay until the packets reach userspace. Defaults to 1. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'nflog_threshold'), + + # The TEE target will clone a packet and redirect this clone to another + # machine on the local network segment. + # Gateway is the target host's IP. + # (a Optional[Pattern[/^(\d+.\d+.\d+.\d+|\w+:\w+::\w+)$/]]) + Puppet::Resource::Param(Any, 'gateway'), + + # Sets the clamp mss to pmtu flag. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'clamp_mss_to_pmtu'), + + # Sets the TCP MSS value for packets. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'set_mss'), + + # Set DSCP Markings. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'set_dscp'), + + # This sets the DSCP field according to a predefined DiffServ class. + # (a Optional[Enum['af11', 'af12', 'af13', 'af21', 'af22', 'af23', 'af31', 'af32', 'af33', 'af41', 'af42', 'af43', 'cs1', 'cs2', 'cs3', 'cs4', 'cs5', 'cs6', 'cs7', 'ef']]) + Puppet::Resource::Param(Any, 'set_dscp_class'), + + # When using jump => "DNAT" you can specify the new destination address using this paramter. + # Can specify a single new destination IP address or an inclusive range of IP addresses. + # Optionally a port or a port range with a possible follow up baseport can be provided. + # Input structure: [ipaddr[-ipaddr]][:port[-port[/baseport]]] + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'todest'), + + # When using jump => "SNAT" you can specify the new source address using this paramter. + # Can specify a single new destination IP address or an inclusive range of IP addresses. + # Input structure: [ipaddr[-ipaddr]][:port[-port]] + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'tosource'), + + # For REDIRECT/MASQUERADE this is the port that will replace the destination/source port. + # Can specify a single new port or an inclusive range of ports. + # (a Optional[Variant[Integer[0, 65535], Pattern[/^\d+(?:-\d+)?$/]]]) + Puppet::Resource::Param(Any, 'toports'), + + # For NETMAP this will replace the destination IP + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'to'), + + # Compute and fill missing packet checksums. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'checksum_fill'), + + # When using a jump value of "MASQUERADE", "DNAT", "REDIRECT", or "SNAT" this boolean will enable fully randomized port mapping. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'random_fully'), + + # When using a jump value of "MASQUERADE", "DNAT", "REDIRECT", or "SNAT" this boolean will enable randomized port mapping. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'random'), + + # When combined with jump => "LOG" specifies the log prefix to use when logging. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'log_prefix'), + + # When combined with jump => "LOG" specifies the system log level to log to. + # + # Note: log level 4/warn is the default setting and as such it is not returned by iptables-save. + # As a result, explicitly setting `log_level` to this can result in idempotency errors. + # (a Optional[Variant[Integer[0,7],String[1]]]) + Puppet::Resource::Param(Any, 'log_level'), + + # When combined with jump => "LOG" specifies the uid of the process making the connection. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'log_uid'), + + # When combined with jump => "LOG" enables logging of the TCP sequence numbers. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'log_tcp_sequence'), + + # When combined with jump => "LOG" logging of the TCP packet header. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'log_tcp_options'), + + # When combined with jump => "LOG" logging of the TCP IP/IPv6 packet header. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'log_ip_options'), + + # When combined with jump => "REJECT" you can specify a different icmp response to be sent back to the packet sender. + # Valid values differ depending on if the protocol is `IPv4` or `IPv6`. + # IPv4 allows: icmp-net-unreachable, icmp-host-unreachable, icmp-port-unreachable, icmp-proto-unreachable, icmp-net-prohibited, + # icmp-host-prohibited, icmp-admin-prohibited, or tcp-reset. + # IPv6 allows: icmp6-no-route, no-route, icmp6-adm-prohibited, adm-prohibited, icmp6-addr-unreachable, addr-unreach, + # icmp6-port-unreachable, or tcp-reset. + # (a Optional[Enum['icmp-net-unreachable', 'icmp-host-unreachable', 'icmp-port-unreachable', 'icmp-proto-unreachable', + # 'icmp-net-prohibited', 'icmp-host-prohibited', 'icmp-admin-prohibited', 'icmp6-no-route', 'no-route', + # 'icmp6-adm-prohibited', 'adm-prohibited', 'icmp6-addr-unreachable', 'addr-unreach', 'icmp6-port-unreachable', + # 'tcp-reset']]) + Puppet::Resource::Param(Any, 'reject'), + + # Set the Netfilter mark value associated with the packet. Accepts either of mark/mask or mark. + # These will be converted to hex if they are not already. + # (a Optional[Pattern[/^[a-fA-F0-9x]+(?:\/[a-fA-F0-9x]+)?$/]]) + Puppet::Resource::Param(Any, 'set_mark'), + + # Match the Netfilter mark value associated with the packet. Accepts either of mark/mask or mark. + # This value will be converted to hex if it is not already. + # This value can be negated by adding a space seperated `!` to the beginning. + # (a Optional[Pattern[/^(?:!\s)?[a-fA-F0-9x]+(?:\/[a-fA-F0-9x]+)?$/]]) + Puppet::Resource::Param(Any, 'match_mark'), + + # Match a given TCP MSS value or range. + # This value can be negated by adding a space seperated `!` to the beginning. + # (a Optional[Pattern[/^(?:!\s)?\d+(?:\:\d+)?$/]]) + Puppet::Resource::Param(Any, 'mss'), + + # Connection limiting value for matched connections below or equal to n. + # (a Optional[Integer]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'connlimit_upto'), + + # Connection limiting value for matched connections above n. + # (a Optional[Integer]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'connlimit_above'), + + # Connection limiting by subnet mask for matched connections. + # IPv4: 0-32 + # IPv6: 0-128 + # (a Optional[Integer[0,128]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'connlimit_mask'), + + # Match the Netfilter mark value associated with the packet. Accepts either of mark/mask or mark. + # This value will be converted to hex if it is not already. + # This value can be negated by adding a space seperated `!` to the beginning. + # (a Optional[Pattern[/^(?:!\s)?[a-fA-F0-9x]+(?:\/[a-fA-F0-9x]+)?$/]]) + Puppet::Resource::Param(Any, 'connmark'), + + # Only match during the given daytime. The possible time range is 00:00:00 to 23:59:59. + # Leading zeroes are allowed (e.g. "06:03") and correctly interpreted as base-10. + # (a Optional[Pattern[/^([0-9]|[0-1][0-9]|2[0-3])\:[0-5][0-9](?:\:[0-5][0-9])?/]]) + Puppet::Resource::Param(Any, 'time_start'), + + # Only match during the given daytime. The possible time range is 00:00:00 to 23:59:59. + # Leading zeroes are allowed (e.g. "06:03") and correctly interpreted as base-10. + # (a Optional[Pattern[/^([0-9]|[0-1][0-9]|2[0-3])\:[0-5][0-9](?:\:[0-5][0-9])?/]]) + Puppet::Resource::Param(Any, 'time_stop'), + + # Only match on the given days of the month. Possible values are 1 to 31. + # Note that specifying 31 will of course not match on months which do not have a 31st day; + # the same goes for 28-day or 29-day February. + # + # Can be passed either as a single value or an array of values: + # month_days => 5, + # month_days => [5, 9, 23], + # (a Optional[Variant[Integer[0,31], Array[Integer[0,31]]]]) + Puppet::Resource::Param(Any, 'month_days'), + + # Only match on the given weekdays. + # + # Can be passed either as a single value or an array of values: + # week_days => 'Mon', + # week_days => ['Mon', 'Tue', 'Wed'], + # (a Optional[Variant[Enum['Mon','Tue','Wed','Thu','Fri','Sat','Sun'], Array[Enum['Mon','Tue','Wed','Thu','Fri','Sat','Sun']]]]) + Puppet::Resource::Param(Any, 'week_days'), + + # Only match during the given time, which must be in ISO 8601 "T" notation. + # The possible time range is 1970-01-01T00:00:00 to 2038-01-19T04:17:07 + # (a Optional[Pattern[/^[0-9]{4}\-(?:0[0-9]|1[0-2])\-(?:[0-2][0-9]|3[0-1])T(?:[0-1][0-9]|2[0-3])\:[0-5][0-9]\:[0-5][0-9]$/]]) + Puppet::Resource::Param(Any, 'date_start'), + + # Only match during the given time, which must be in ISO 8601 "T" notation. + # The possible time range is 1970-01-01T00:00:00 to 2038-01-19T04:17:07 + # (a Optional[Pattern[/^[0-9]{4}\-(?:0[0-9]|1[0-2])\-(?:[0-2][0-9]|3[0-1])T(?:[0-1][0-9]|2[0-3])\:[0-5][0-9]\:[0-5][0-9]$/]]) + Puppet::Resource::Param(Any, 'date_stop'), + + # When time_stop is smaller than time_start value, match this as a single time period instead distinct intervals. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'time_contiguous'), + + # Use the kernel timezone instead of UTC to determine whether a packet meets the time regulations. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'kernel_timezone'), + + # Enable the u32 module. Takes as an argument one of set, update, + # rcheck or remove. For example: + # firewall { '032 u32 test': + # ensure => present, + # table => 'mangle', + # chain => 'PREROUTING', + # u32 => '0x4&0x1fff=0x0&&0x0&0xf000000=0x5000000', + # jump => 'DROP', + # } + # (a Optional[Pattern[/^0x[0-9a-fA-F]+&0x[0-9a-fA-F]+=0x[0-9a-fA-F]+(?::0x[0-9a-fA-F]+)?(?:&&0x[0-9a-fA-F]+&0x[0-9a-fA-F]+=0x[0-9a-fA-F]+(?::0x[0-9a-fA-F]+)?)*$/]]) + Puppet::Resource::Param(Any, 'u32'), + + # src attribute for the module geoip + # (a Optional[Pattern[/^[A-Z]{2}(,[A-Z]{2})*$/]]) + Puppet::Resource::Param(Any, 'src_cc'), + + # dst attribute for the module geoip + # (a Optional[Pattern[/^[A-Z]{2}(,[A-Z]{2})*$/]]) + Puppet::Resource::Param(Any, 'dst_cc'), + + # Match if the rate is below or equal to amount/quantum. It is specified either as a number, with an optional time quantum suffix (the default is 3/hour), or as amountb/second (number of bytes per second). + # This parameter or `hashlimit_above` and `hashlimit_name` are required when setting any other hashlimit values. + # Allowed forms are '40','40/sec','40/min','40/hour','40/day'. + # (a Optional[Pattern[/^\d+(?:\/(?:sec|min|hour|day))?$/]]) + Puppet::Resource::Param(Any, 'hashlimit_upto'), + + # Match if the rate is above amount/quantum. + # This parameter or `hashlimit_upto` and `hashlimit_name` are required when setting any other hashlimit values. + # Allowed forms are '40','40/sec','40/min','40/hour','40/day'. + # (a Optional[Pattern[/^\d+(?:\/(?:sec|min|hour|day))?$/]]) + Puppet::Resource::Param(Any, 'hashlimit_above'), + + # The name for the /proc/net/ipt_hashlimit/foo entry. + # This parameter and either `hashlimit_upto` or `hashlimit_above` are required when setting any other hashlimit values. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'hashlimit_name'), + + # Maximum initial number of packets to match: this number gets recharged by one every time the limit specified above is not reached, up to this number; the default is 5. + # When byte-based rate matching is requested, this option specifies the amount of bytes that can exceed the given rate. + # This option should be used with caution -- if the entry expires, the burst value is reset too. + # (a Optional[Integer[1]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'hashlimit_burst'), + + # A comma-separated list of objects to take into consideration. + # If no --hashlimit-mode option is given, hashlimit acts like limit, but at the expensive of doing the hash housekeeping. + # Allowed values are: srcip, srcport, dstip, dstport + # (a Optional[Pattern[/^(?:srcip|srcport|dstip|dstport)(?:\,(?:srcip|srcport|dstip|dstport))*$/]]) + Puppet::Resource::Param(Any, 'hashlimit_mode'), + + # When --hashlimit-mode srcip is used, all source addresses encountered will be grouped according to the given prefix length + # and the so-created subnet will be subject to hashlimit. + # Prefix must be between (inclusive) 0 and 32. + # Note that --hashlimit-srcmask 0 is basically doing the same thing as not specifying srcip for --hashlimit-mode, but is technically more expensive. + # (a Optional[Integer[0,32]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'hashlimit_srcmask'), + + # When --hashlimit-mode srcip is used, all destination addresses encountered will be grouped according to the given prefix length + # and the so-created subnet will be subject to hashlimit. + # Prefix must be between (inclusive) 0 and 32. + # Note that --hashlimit-dstmask 0 is basically doing the same thing as not specifying srcip for --hashlimit-mode, but is technically more expensive. + # (a Optional[Integer[0,32]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'hashlimit_dstmask'), + + # The number of buckets of the hash table + # (a Optional[Integer]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'hashlimit_htable_size'), + + # Maximum entries in the hash. + # (a Optional[Integer]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'hashlimit_htable_max'), + + # After how many milliseconds do hash entries expire. + # (a Optional[Integer]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'hashlimit_htable_expire'), + + # How many milliseconds between garbage collection intervals. + # (a Optional[Integer]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'hashlimit_htable_gcinterval'), + + # Match using Linux Socket Filter. Expects a BPF program in decimal format. + # This is the format generated by the nfbpf_compile utility. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'bytecode'), + + # Match using Linux Socket Filter. Expects a BPF program in decimal format. + # This is the format generated by the nfbpf_compile utility. + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'ipvs'), + + # Assign this packet to zone id and only have lookups done in that zone. + # (a Optional[Integer]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'zone'), + + # Invoke the nf_conntrack_xxx helper module for this packet. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'helper'), + + # Matches against the net_cls cgroup ID of the packet. + # + # To negate add a space seperate `!` to the beginning of the string + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'cgroup'), + + # Enable the rpfilter module. + # (a Optional[Variant[Enum['loose', 'validmark', 'accept-local', 'invert'], Array[Enum['loose', 'validmark', 'accept-local', 'invert']]]]) + Puppet::Resource::Param(Any, 'rpfilter'), + + # Match on boolean value (0/1) stored in /proc/net/nf_condition/name. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'condition'), + + # Invoke the disable connection tracking for this packet. + # This parameter can be used with iptables version >= 1.8.3 + # (a Optional[Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'notrack') + ], + [ + # The canonical name of the rule. This name is also used for ordering + # so make sure you prefix the rule with a number: + # + # 000 this runs first + # 999 this runs last + # + # Depending on the provider, the name of the rule can be stored using + # the comment feature of the underlying firewall subsystem. + # (a Pattern[/(^\d+(?:[ \t-]\S+)+$)/]) + Puppet::Resource::Param(Any, 'name', true), + + # A read only attribute containing the full rule, used when deleting and when applying firewallchain purge attributes. + # (a Optional[String[1]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'line') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/firewallchain.pp b/internal/gentypes/testdata/golden/firewallchain.pp new file mode 100644 index 0000000..c6a9a23 --- /dev/null +++ b/internal/gentypes/testdata/golden/firewallchain.pp @@ -0,0 +1,82 @@ +# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# This type provides the capability to manage rule chains for firewalls. +# +# Currently this supports only iptables, ip6tables and ebtables on Linux. And +# provides support for setting the default policy on chains and tables that +# allow it. +# +# #### Providers +# * iptables_chain is the only provider that supports firewallchain. +# +# #### Features +# * iptables_chain: The provider provides iptables chain features. +# * policy: Default policy (inbuilt chains only). +Puppet::Resource::ResourceType3.new( + 'firewallchain', + [ + # Whether this chain should be present or absent on the target system. + # Setting this to absent will first remove all rules associated with this chain and then delete the chain itself. + # Inbuilt chains however will merely remove any added rules and, if it has been changed, return their policy to the default. + # (a Enum[present, absent]) + # + # Valid values are `absent`, `present`. + Puppet::Resource::Param(Enum['absent', 'present'], 'ensure'), + + # This action to take when the end of the chain is reached. + # This can only be set on inbuilt chains (i.e. INPUT, FORWARD, OUTPUT, + # PREROUTING, POSTROUTING) and can be one of: + # + # * accept - the packet is accepted + # * drop - the packet is dropped + # * queue - the packet is passed userspace + # * return - the packet is returned to calling (jump) queue + # or the default of inbuilt chains + # (a Optional[Enum['accept', 'drop', 'queue', 'return']]) + Puppet::Resource::Param(Any, 'policy'), + + # Whether or not to purge unmanaged rules in this chain (a Boolean) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'purge'), + + # Regex to perform on firewall rules to exempt unmanaged rules from purging. + # This is matched against the output of `iptables-save`. + # + # This can be a single regex, or an array of them. + # To support flags, use the ruby inline flag mechanism. + # Meaning a regex such as + # /foo/i + # can be written as + # '(?i)foo' or '(?i:foo)' + # + # Full example: + # ``` + # firewallchain { 'INPUT:filter:IPv4': + # purge => true, + # ignore => [ + # '-j fail2ban-ssh', # ignore the fail2ban jump rule + # '--comment "[^"]*(?i:ignore)[^"]*"', # ignore any rules with "ignore" (case insensitive) in the comment in the rule + # ], + # } + # ``` + # (a Optional[Variant[String[1], Array[String[1]]]]) + Puppet::Resource::Param(Any, 'ignore'), + + # Ignore rules that do not match the puppet title pattern "^d+[[:graph:][:space:]]" when purging unmanaged firewall rules in this chain. + # This can be used to ignore rules that were not put in by puppet. Beware that nothing keeps other systems from configuring firewall rules with a comment that starts with digits, and is indistinguishable from puppet-configured rules. + # (a Boolean) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'ignore_foreign') + ], + [ + # The canonical name of the chain with the required format being `{chain}:{table}:{protocol}`. (a Pattern[/^(?:\S+):(?:nat|mangle|filter|raw|rawpost|broute|security):(?:IP(?:v[46])?|ethernet)$/]) + Puppet::Resource::Param(Any, 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/grafana_plugin.pp b/internal/gentypes/testdata/golden/grafana_plugin.pp new file mode 100644 index 0000000..6875f84 --- /dev/null +++ b/internal/gentypes/testdata/golden/grafana_plugin.pp @@ -0,0 +1,59 @@ +# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# manages grafana plugins +# +# @example Install a grafana plugin +# grafana_plugin { 'grafana-simple-json-datasource': } +# +# @example Install a grafana plugin from different repo +# grafana_plugin { 'grafana-simple-json-datasource': +# ensure => 'present', +# repo => 'https://nexus.company.com/grafana/plugins', +# } +# +# @example Install a grafana plugin from a plugin url +# grafana_plugin { 'grafana-example-custom-plugin': +# ensure => 'present', +# plugin_url => 'https://github.com/example/example-custom-plugin/zipball/v1.0.0' +# } +# +# @example Uninstall a grafana plugin +# grafana_plugin { 'grafana-simple-json-datasource': +# ensure => 'absent', +# } +# +# @example Show resources +# $ puppet resource grafana_plugin +Puppet::Resource::ResourceType3.new( + 'grafana_plugin', + [ + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure') + ], + [ + # The name of the plugin to enable + # + # Values can match `/^\S+$/`. + Puppet::Resource::Param(Pattern[/^\S+$/], 'name', true), + + # The URL of an internal plugin server + Puppet::Resource::Param(Any, 'repo'), + + # Full url to the plugin zip file + Puppet::Resource::Param(Any, 'plugin_url'), + + # The specific backend to use for this `grafana_plugin` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # grafana_cli + # : * Required binaries: `grafana-cli`. + # * Default for `feature` == `posix`. + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/ini_setting.pp b/internal/gentypes/testdata/golden/ini_setting.pp new file mode 100644 index 0000000..fbfaad3 --- /dev/null +++ b/internal/gentypes/testdata/golden/ini_setting.pp @@ -0,0 +1,71 @@ +# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# ini_settings is used to manage a single setting in an INI file +Puppet::Resource::ResourceType3.new( + 'ini_setting', + [ + # Ensurable method handles modeling creation. It creates an ensure property + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # The value of the setting to be defined. + Puppet::Resource::Param(Any, 'value') + ], + [ + # An arbitrary name used as the identity of the resource. + Puppet::Resource::Param(Any, 'name', true), + + # The name of the section in the ini file in which the setting should be defined. + Puppet::Resource::Param(Any, 'section'), + + # The name of the setting to be defined. + Puppet::Resource::Param(Any, 'setting'), + + # Create setting only if the section exists + # + # Valid values are `true`, `false`, `yes`, `no`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'force_new_section_creation'), + + # The ini file Puppet will ensure contains the specified setting. + Puppet::Resource::Param(Any, 'path'), + + # Whether to display differences when the setting changes. + # + # Valid values are `true`, `md5`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'md5', 'false']], 'show_diff'), + + # The separator string to use between each setting name and value. + Puppet::Resource::Param(Any, 'key_val_separator'), + + # The prefix to the section name's header. + Puppet::Resource::Param(Any, 'section_prefix'), + + # The suffix to the section name's header. + Puppet::Resource::Param(Any, 'section_suffix'), + + # The character to indent new settings with. + Puppet::Resource::Param(Any, 'indent_char'), + + # The number of indent_chars to use to indent a new setting. + Puppet::Resource::Param(Any, 'indent_width'), + + # A flag indicating whether or not the ini_setting should be updated only when called as part of a refresh event + # + # Valid values are `true`, `false`, `yes`, `no`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'refreshonly'), + + # The specific backend to use for this `ini_setting` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # ruby + # : + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/minio_client_alias.pp b/internal/gentypes/testdata/golden/minio_client_alias.pp new file mode 100644 index 0000000..2c02392 --- /dev/null +++ b/internal/gentypes/testdata/golden/minio_client_alias.pp @@ -0,0 +1,62 @@ +# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# @summary Manages minio client aliases +# @example +# minio_client_alias { 'localminio': +# ensure => 'present', +# endpoint => 'http://localhost:9000', +# access_key => 'admin', +# secret_key => 'password', +# api_signature => 'S3v4', +# path_lookup_support =>'on', +# } +# +# @example +# minio_client_alias { 'default': +# ensure => 'present', +# endpoint => 'http://localhost:9000', +# access_key => 'admin', +# secret_key => Sensitive('password'), +# } +# +# **Autorequires**: +# * `File[/root/.minioclient]` +Puppet::Resource::ResourceType3.new( + 'minio_client_alias', + [ + # Whether this resource should be present or absent on the target system. (a Enum[present, absent]) + # + # Valid values are `absent`, `present`. + Puppet::Resource::Param(Enum['absent', 'present'], 'ensure'), + + # The API endpoint url (a String[1]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'endpoint'), + + # The API access key (a Optional[String]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'access_key'), + + # The API access secret (a Optional[Variant[Sensitive[String], String]]) + Puppet::Resource::Param(Any, 'secret_key'), + + # The API signature (a Optional[Enum['S3v4', 'S3v2']]) + Puppet::Resource::Param(Any, 'api_signature'), + + # Indicate whether dns or path style url requests are supported by the server. (a Optional[Enum['on', 'off', 'auto']]) + Puppet::Resource::Param(Any, 'path_lookup_support') + ], + [ + # The name of the resource you want to manage. (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/mysql_login_path.pp b/internal/gentypes/testdata/golden/mysql_login_path.pp new file mode 100644 index 0000000..fd5ca0b --- /dev/null +++ b/internal/gentypes/testdata/golden/mysql_login_path.pp @@ -0,0 +1,75 @@ +# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# @summary Manage a MySQL login path. +# @see +# https://dev.mysql.com/doc/refman/8.0/en/mysql-config-editor.html +# @example +# mysql_login_path { 'local_socket': +# owner => 'root', +# host => 'localhost', +# user => 'root', +# password => Sensitive('secure'), +# socket => '/var/run/mysql/mysql.sock', +# ensure => present, +# } +# +# mysql_login_path { 'local_tcp': +# owner => 'root', +# host => '127.0.0.1', +# user => 'root', +# password => Sensitive('more_secure'), +# port => 3306, +# ensure => present, +# } +# +# This type provides Puppet with the capabilities to store authentication credentials in an obfuscated login path file +# named .mylogin.cnf created with the mysql_config_editor utility. Supports only MySQL Community Edition > v5.6.6. +Puppet::Resource::ResourceType3.new( + 'mysql_login_path', + [ + # Whether this resource should be present or absent on the target system. (a Enum[present, absent]) + # + # Valid values are `absent`, `present`. + Puppet::Resource::Param(Enum['absent', 'present'], 'ensure'), + + # Host name to be entered into the login path. (a Optional[String]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'host'), + + # Username to be entered into the login path. (a Optional[String]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'user'), + + # Password to be entered into login path (a Optional[Sensitive[String[1]]]) + Puppet::Resource::Param(Any, 'password'), + + # Socket path to be entered into login path (a Optional[String]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'socket'), + + # Port number to be entered into login path. (a Optional[Integer[0,65535]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'port') + ], + [ + # Name of the login path you want to manage. (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'name', true), + + # The user to whom the logon path should belong. (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'owner', true) + ], + { + /^(?.*[^-])-(?.*)$/ => ['name', 'owner'], + /^(?.*)$/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/network_config.pp b/internal/gentypes/testdata/golden/network_config.pp new file mode 100644 index 0000000..81047f5 --- /dev/null +++ b/internal/gentypes/testdata/golden/network_config.pp @@ -0,0 +1,99 @@ +# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# Manage non-volatile network configuration information +Puppet::Resource::ResourceType3.new( + 'network_config', + [ + # The basic property that the resource should be in. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # The IP address of the network interfaces + Puppet::Resource::Param(Any, 'ipaddress'), + + # The subnet mask to apply to the interface + Puppet::Resource::Param(Any, 'netmask'), + + # The method for determining an IP address for the interface + # + # Valid values are `static` (also called `none`), `manual`, `dhcp`, `loopback`. + Puppet::Resource::Param(Enum['static', 'none', 'manual', 'dhcp', 'loopback'], 'method'), + + # The address family to use for the interface + # + # Valid values are `inet` (also called `inet4`), `inet6`. + Puppet::Resource::Param(Enum['inet', 'inet4', 'inet6'], 'family'), + + # Whether to bring the interface up on boot + Puppet::Resource::Param(Any, 'onboot'), + + # Allow/disallow hotplug support for this interface + # + # + # + # Requires features hotpluggable. + Puppet::Resource::Param(Any, 'hotplug'), + + # Allow/disallow startmode support for this interface + # + # + # + # Requires features startmode. + Puppet::Resource::Param(Any, 'startmode'), + + # The Maximum Transmission Unit size to use for the interface + Puppet::Resource::Param(Any, 'mtu'), + + # The exclusive mode the interface should operate in + # + # Valid values are `raw`, `vlan`. + Puppet::Resource::Param(Enum['raw', 'vlan'], 'mode'), + + # Provider specific options to be passed to the provider + # + # + # + # Requires features provider_options. + Puppet::Resource::Param(Any, 'options') + ], + [ + # The name of the physical or logical network device + Puppet::Resource::Param(Any, 'name', true), + + # Reconfigure the interface after the configuration has been updated + # + # + # + # Requires features reconfigurable. + Puppet::Resource::Param(Any, 'reconfigure'), + + # The specific backend to use for this `network_config` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # interfaces + # : Debian interfaces style provider + # + # * Default for `osfamily` == `debian`. + # * Supported features: `hotpluggable`, `provider_options`. + # + # redhat + # : Redhat network-scripts provider + # + # * Default for `osfamily` == `redhat`. + # * Supported features: `hotpluggable`, `provider_options`. + # + # sles + # : SLES network-scripts provider + # + # * Default for `osfamily` == `suse`. + # * Supported features: `provider_options`, `startmode`. + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/reboot.pp b/internal/gentypes/testdata/golden/reboot.pp new file mode 100644 index 0000000..4e41f60 --- /dev/null +++ b/internal/gentypes/testdata/golden/reboot.pp @@ -0,0 +1,140 @@ +# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# Manages system reboots. The `reboot` type is typically +# used in situations where a resource performs a change, e.g. +# package install, and a reboot is required to complete +# installation. Only if the package is installed should the +# reboot be triggered. +# +# Sample usage: +# +# package { 'Microsoft .NET Framework 4.5': +# ensure => installed, +# source => '\\server\share\dotnetfx45_full_x86_x64.exe', +# install_options => ['/Passive', '/NoRestart'], +# provider => windows, +# } +# reboot { 'after': +# subscribe => Package['Microsoft .NET Framework 4.5'], +# } +# +# A reboot resource can also check if the system is in a +# reboot pending state, and if so, reboot the system. For +# example, if you have a package that cannot be installed +# while a reboot is pending. +# +# Sample usage: +# +# reboot { 'before': +# when => pending, +# } +# package { 'Microsoft .NET Framework 4.5': +# ensure => installed, +# source => '\\server\share\dotnetfx45_full_x86_x64.exe', +# install_options => ['/Passive', '/NoRestart'], +# provider => windows, +# require => Reboot['before'], +# } +# +# A reboot resource can also finish the run and then reboot the system. For +# example, if you have a few packages that all require reboots but will not block +# each other during the run. +# +# Sample usage: +# +# package { 'Microsoft .NET Framework 4.5': +# ensure => installed, +# source => '\\server\share\dotnetfx45_full_x86_x64.exe', +# install_options => ['/Passive', '/NoRestart'], +# provider => windows, +# } +# reboot { 'after_run': +# apply => finished, +# subscribe => Package['Microsoft .NET Framework 4.5'], +# } +# +# On windows we can limit the reasons for a pending reboot. +# +# Sample usage: +# +# reboot { 'renames only': +# when => pending, +# onlyif => 'pending_rename_file_operations', +# } +Puppet::Resource::ResourceType3.new( + 'reboot', + [ + # When to check for, and if needed, perform a reboot. If `pending`, + # then the provider will check if a reboot is pending, and only + # if needed, reboot the system. If `refreshed` then the reboot + # will only be performed in response to a refresh event from + # another resource, e.g. `package`. + # + # Valid values are `refreshed`, `pending`. + Puppet::Resource::Param(Enum['refreshed', 'pending'], 'when') + ], + [ + # The name of the reboot resource. Used for uniqueness. + Puppet::Resource::Param(Any, 'name', true), + + # For pending reboots, only reboot if the reboot is pending + # for one of the supplied reasons. + # + # + # + # Requires features manages_reboot_pending. + Puppet::Resource::Param(Any, 'onlyif'), + + # For pending reboots, ignore the supplied reasons when checking pennding reboot + # + # + # + # Requires features manages_reboot_pending. + Puppet::Resource::Param(Any, 'unless'), + + # When to apply the reboot. If `immediately`, then the provider + # will stop applying additional resources and apply the reboot once + # puppet has finished syncing. If `finished`, it will continue + # applying resources and then perform a reboot at the end of the + # run. The default is `immediately`. + # + # Valid values are `immediately`, `finished`. + Puppet::Resource::Param(Enum['immediately', 'finished'], 'apply'), + + # The message to log when the reboot is performed. + Puppet::Resource::Param(Any, 'message'), + + # The amount of time in seconds to wait between the time the reboot + # is requested and when the reboot is performed. The default timeout + # is 60 seconds. Note that this time starts once puppet has exited the + # current run. + Puppet::Resource::Param(Any, 'timeout'), + + # The specific backend to use for this `reboot` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # linux + # : + # + # posix + # : POSIX provider for the reboot type. + # + # This provider handles rebooting for POSIX systems. It does not support + # HP-UX. + # + # * Required binaries: `shutdown`. + # * Default for `feature` == `posix`. + # + # windows + # : * Required binaries: `shutdown.exe`. + # * Default for `os.name` == `windows`. + # * Supported features: `manages_reboot_pending`. + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/yumrepo.pp b/internal/gentypes/testdata/golden/yumrepo.pp new file mode 100644 index 0000000..301a502 --- /dev/null +++ b/internal/gentypes/testdata/golden/yumrepo.pp @@ -0,0 +1,348 @@ +# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# @summary The client-side description of a yum repository. +# +# Repository configurations are found by parsing `/etc/yum.conf` and the files +# indicated by the `reposdir` option in that file (see `yum.conf(5)` for +# details). +# +# Most parameters are identical to the ones documented +# in the `yum.conf(5)` man page. +# +# Continuation lines that yum supports (for the `baseurl`, for example) +# are not supported. This type does not attempt to read or verify the +# existence of files listed in the `include` attribute." +Puppet::Resource::ResourceType3.new( + 'yumrepo', + [ + # The basic property that the resource should be in. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # A human-readable description of the repository. + # This corresponds to the name parameter in `yum.conf(5)`. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'descr'), + + # The URL that holds the list of mirrors for this repository. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'mirrorlist'), + + # The URL for this repository. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'baseurl'), + + # Whether this repository is enabled. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'enabled'), + + # Whether to check the GPG signature on packages installed + # from this repository. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'gpgcheck'), + + # Whether to check the GPG signature of the packages payload. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'payload_gpgcheck'), + + # Whether to check the GPG signature on repodata. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'repo_gpgcheck'), + + # The URL for the GPG key with which packages from this + # repository are signed. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'gpgkey'), + + # Time (in seconds) after which the mirrorlist locally cached + # will expire. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^[0-9]+$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^[0-9]+$/]], 'mirrorlist_expire'), + + # The URL of a remote file containing additional yum configuration + # settings. Puppet does not check for this file's existence or validity. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'include'), + + # The string of package names or shell globs separated by spaces to exclude. + # Packages that match the package name given or shell globs will never be + # considered in updates or installs for this repo. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'exclude'), + + # The URL for the GPG CA key for this repository. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'gpgcakey'), + + # The string of package names or shell globs separated by spaces to + # include. If this is set, only packages matching one of the package + # names or shell globs will be considered for update or install + # from this repository. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'includepkgs'), + + # Whether yum will allow the use of package groups for this + # repository. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'enablegroups'), + + # Whether packages from this repo can be installed into modules. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'module_hotfixes'), + + # The failover method for this repository; should be either + # `roundrobin` or `priority`. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^roundrobin|priority$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^roundrobin|priority$/]], 'failovermethod'), + + # Whether HTTP/1.1 keepalive should be used with this repository. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'keepalive'), + + # Set the number of times any attempt to retrieve a file should + # retry before returning an error. Setting this to `0` makes yum + # try forever. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^[0-9]+$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^[0-9]+$/]], 'retries'), + + # What to cache from this repository. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(packages|all|none)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(packages|all|none)$/]], 'http_caching'), + + # Number of seconds to wait for a connection before timing + # out. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^\d+$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^\d+$/]], 'timeout'), + + # Number of seconds after which the metadata will expire. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^([0-9]+[dhm]?|never)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^([0-9]+[dhm]?|never)$/]], 'metadata_expire'), + + # Enable or disable protection for this repository. Requires + # that the `protectbase` plugin is installed and enabled. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'protect'), + + # Priority of this repository. Can be any integer value + # (including negative). Requires that the `priorities` plugin + # is installed and enabled. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^-?\d+$/]], 'priority'), + + # Sets the low speed threshold in bytes per second. + # If the server is sending data slower than this for at least + # `timeout` seconds, Yum aborts the connection. The default is + # `1000`. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^\d+$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^\d+$/]], 'minrate'), + + # Enable bandwidth throttling for downloads. This option + # can be expressed as a absolute data rate in bytes/sec or a + # percentage `60%`. An SI prefix (k, M or G) may be appended + # to the data rate values. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^\d+[kMG%]?$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^\d+[kMG%]?$/]], 'throttle'), + + # Use to specify the maximum available network bandwidth + # in bytes/second. Used with the `throttle` option. If `throttle` + # is a percentage and `bandwidth` is `0` then bandwidth throttling + # will be disabled. If `throttle` is expressed as a data rate then + # this option is ignored. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^\d+[kMG]?$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^\d+[kMG]?$/]], 'bandwidth'), + + # Cost of this repository. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^\d+$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^\d+$/]], 'cost'), + + # URL of a proxy server that Yum should use when accessing this repository. + # This attribute can also be set to '_none_' (or '' for EL >= 8 only), + # which will make Yum bypass any global proxy settings when accessing this repository. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'proxy'), + + # Username for this proxy. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'proxy_username'), + + # Password for this proxy. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'proxy_password'), + + # Access the repository via S3. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 's3_enabled'), + + # Path to the directory containing the databases of the + # certificate authorities yum should use to verify SSL certificates. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'sslcacert'), + + # Should yum verify SSL certificates/hosts at all. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'sslverify'), + + # Path to the SSL client certificate yum should use to connect + # to repositories/remote sites. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'sslclientcert'), + + # Path to the SSL client key yum should use to connect + # to repositories/remote sites. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'sslclientkey'), + + # Metalink for mirrors. Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'metalink'), + + # Should yum skip this repository if unable to reach it. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'skip_if_unavailable'), + + # Determines if yum prompts for confirmation of critical actions. + # Valid values are: false/0/no or true/1/yes. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^(true|false|0|1|no|yes)$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^(true|false|0|1|no|yes)$/]], 'assumeyes'), + + # Percentage value that determines when to use deltas for this repository. + # When the delta is larger than this percentage value of the package, the + # delta is not used. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^\d+$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^\d+$/]], 'deltarpm_percentage'), + + # Percentage value that determines when to download deltarpm metadata. + # When the deltarpm metadata is larger than this percentage value of the + # package, deltarpm metadata is not downloaded. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/^\d+$/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/^\d+$/]], 'deltarpm_metadata_percentage'), + + # Username to use for basic authentication to a repo or really any url. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'username'), + + # Password to use with the username for basic authentication. + # Set this to `absent` to remove it from the file completely. + # + # Valid values are `absent`. Values can match `/.*/`. + Puppet::Resource::Param(Variant[Enum['absent'], Pattern[/.*/]], 'password') + ], + [ + # The name of the repository. This corresponds to the + # `repositoryid` parameter in `yum.conf(5)`. + Puppet::Resource::Param(Any, 'name', true), + + # The filepath of the local repository file, can be either relative or absolute. If a valid filepath is not specified, the target is created as a new section in `yum.conf(5)` + Puppet::Resource::Param(Any, 'target'), + + # The specific backend to use for this `yumrepo` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # inifile + # : Manage yum repo configurations by parsing yum INI configuration files. + # + # ### Fetching instances + # + # When fetching repo instances, directory entries in '/etc/yum/repos.d', + # '/etc/yum.repos.d', and the directory optionally specified by the reposdir + # key in '/etc/yum.conf' will be checked. If a given directory does not exist it + # will be ignored. In addition, all sections in '/etc/yum.conf' aside from + # 'main' will be created as sections. + # + # ### Storing instances + # + # When creating a new repository, a new section will be added in the first + # yum repo directory that exists. The custom directory specified by the + # '/etc/yum.conf' reposdir property is checked first, followed by + # '/etc/yum/repos.d', and then '/etc/yum.repos.d'. If none of these exist, the + # section will be created in '/etc/yum.conf'. + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) From 893da512f17220db983fbda5996a938530c35633 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 18:01:13 +1100 Subject: [PATCH 2/8] Give the failing-input fixture a stale output mtime --- internal/gentypes/generate_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/gentypes/generate_test.go b/internal/gentypes/generate_test.go index 1960fe2..f4b0cc9 100644 --- a/internal/gentypes/generate_test.go +++ b/internal/gentypes/generate_test.go @@ -344,6 +344,10 @@ func TestGenerateErrors(t *testing.T) { writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/bad.rb"), "Puppet::Type.newtype(:bad) do\n newparam(dynamic)\nend\n") writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/good.rb"), strings.ReplaceAll(simpleType, "%s", "good")) writeFile(t, filepath.Join(env, OutDir, "bad.pp"), "previous") + old := time.Now().Add(-time.Hour) + if err := os.Chtimes(filepath.Join(env, OutDir, "bad.pp"), old, old); err != nil { + t.Fatal(err) + } err := Generate(env) if err == nil || !strings.Contains(err.Error(), "modules/m/lib/puppet/type/bad.rb") { t.Fatalf("got %v", err) From ac24c66924965d3f7712bd4891bc275cdd9f256b Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 18:03:35 +1100 Subject: [PATCH 3/8] Write .resource_types through an os.Root on the worktree --- internal/gentypes/generate.go | 69 +++++++++++++++++++----------- internal/gentypes/generate_test.go | 13 ++++++ 2 files changed, 58 insertions(+), 24 deletions(-) diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index 836d12f..ebbf61c 100644 --- a/internal/gentypes/generate.go +++ b/internal/gentypes/generate.go @@ -67,27 +67,27 @@ func Generate(env string, roots ...string) error { } } sort.Strings(inputs) - out := filepath.Join(g.env, OutDir) - if fi, err := os.Lstat(out); err == nil && !fi.IsDir() { - return fmt.Errorf("%s exists and is not a directory", out) - } else if errors.Is(err, os.ErrNotExist) { - if err := os.Mkdir(out, 0o755); err != nil { - return err - } - } else if err != nil { + out, err := openOut(g.env) + if err != nil { return err } + defer func() { _ = out.Close() }() keep := map[string]bool{} for _, in := range inputs { keep[strings.TrimSuffix(filepath.Base(in), ".rb")+".pp"] = true } - entries, err := os.ReadDir(out) + dir, err := out.Open(".") + if err != nil { + return err + } + entries, err := dir.ReadDir(-1) + _ = dir.Close() if err != nil { return err } for _, e := range entries { if !keep[e.Name()] && e.Type().IsRegular() { - if err := os.Remove(filepath.Join(out, e.Name())); err != nil { + if err := out.Remove(e.Name()); err != nil { return err } } @@ -101,14 +101,35 @@ func Generate(env string, roots ...string) error { return errors.Join(errs...) } -func generateOne(in, out string, providers map[string][]string) error { +// openOut returns an os.Root on /.resource_types, refusing anything but a real directory there. +func openOut(env string) (*os.Root, error) { + root, err := os.OpenRoot(env) + if err != nil { + return nil, err + } + defer func() { _ = root.Close() }() + fi, err := root.Lstat(OutDir) + switch { + case errors.Is(err, os.ErrNotExist): + if err := root.Mkdir(OutDir, 0o755); err != nil { + return nil, err + } + case err != nil: + return nil, err + case !fi.IsDir(): + return nil, fmt.Errorf("%s exists and is not a directory", filepath.Join(env, OutDir)) + } + return root.OpenRoot(OutDir) +} + +func generateOne(in string, out *os.Root, providers map[string][]string) error { ifi, err := os.Stat(in) if err != nil { return err } name := strings.TrimSuffix(filepath.Base(in), ".rb") - dst := filepath.Join(out, name+".pp") - if ofi, err := os.Lstat(dst); err == nil && ofi.Mode().IsRegular() && ofi.ModTime().Equal(ifi.ModTime()) { + dst := name + ".pp" + if ofi, err := out.Lstat(dst); err == nil && ofi.Mode().IsRegular() && ofi.ModTime().Equal(ifi.ModTime()) { return nil } src, err := os.ReadFile(in) @@ -132,26 +153,26 @@ func generateOne(in, out string, providers map[string][]string) error { if err != nil { return err } - tmp, err := os.CreateTemp(out, "."+name+".*.tmp") + tmp := "." + dst + ".tmp" + if err := out.Remove(tmp); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + f, err := out.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) if err != nil { return err } - defer func() { _ = os.Remove(tmp.Name()) }() - if _, err := tmp.WriteString(body); err != nil { - _ = tmp.Close() + defer func() { _ = out.Remove(tmp) }() + if _, err := f.WriteString(body); err != nil { + _ = f.Close() return err } - if err := tmp.Chmod(0o644); err != nil { - _ = tmp.Close() + if err := f.Close(); err != nil { return err } - if err := tmp.Close(); err != nil { + if err := out.Chtimes(tmp, ifi.ModTime(), ifi.ModTime()); err != nil { return err } - if err := os.Chtimes(tmp.Name(), ifi.ModTime(), ifi.ModTime()); err != nil { - return err - } - return os.Rename(tmp.Name(), dst) + return out.Rename(tmp, dst) } func (g *gen) confine(p string) (string, error) { diff --git a/internal/gentypes/generate_test.go b/internal/gentypes/generate_test.go index f4b0cc9..78f0c91 100644 --- a/internal/gentypes/generate_test.go +++ b/internal/gentypes/generate_test.go @@ -286,6 +286,13 @@ func TestGenerateFiles(t *testing.T) { if err := os.Symlink("/etc/passwd", filepath.Join(out, "link.pp")); err != nil { t.Fatal(err) } + victim := filepath.Join(t.TempDir(), "victim") + writeFile(t, victim, "untouched") + for _, l := range []string{"foo.pp", ".bar.pp.tmp"} { + if err := os.Symlink(victim, filepath.Join(out, l)); err != nil { + t.Fatal(err) + } + } if err := Generate(env, cache); err != nil { t.Fatal(err) @@ -293,6 +300,12 @@ func TestGenerateFiles(t *testing.T) { if exists(filepath.Join(out, "stale.pp")) || !exists(filepath.Join(out, "keepdir")) || !exists(filepath.Join(out, "link.pp")) { t.Fatal("cleanup must remove only stale regular files") } + if readFile(t, victim) != "untouched" { + t.Fatal("writes must never follow symlinks under the output dir") + } + if fi, err := os.Lstat(filepath.Join(out, "foo.pp")); err != nil || !fi.Mode().IsRegular() { + t.Fatal("a symlinked output must be replaced by a regular file") + } foo, err := os.ReadFile(filepath.Join(out, "foo.pp")) if err != nil || !strings.Contains(string(foo), "'provider'") { t.Fatalf("foo.pp via symlinked module with provider: %v\n%s", err, foo) From 84356787978f7a30ee96ec5d52f2ee504751a017 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 18:50:46 +1100 Subject: [PATCH 4/8] 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 --- internal/gentypes/generate.go | 41 +- internal/gentypes/generate_test.go | 223 +++++++- internal/gentypes/lexer.go | 201 ++++--- internal/gentypes/parse.go | 492 ++++++++++++++++-- internal/gentypes/render.go | 98 +++- .../provider/alternative_entry/chkconfig.rb | 2 + .../puppet/provider/alternative_entry/dpkg.rb | 2 + .../puppet/provider/alternatives/chkconfig.rb | 2 + .../lib/puppet/provider/alternatives/dpkg.rb | 2 + .../lib/puppet/provider/archive/curl.rb | 2 + .../lib/puppet/provider/archive/ruby.rb | 2 + .../lib/puppet/provider/archive/wget.rb | 2 + .../lib/puppet/provider/firewall/firewall.rb | 2 + .../provider/firewallchain/firewallchain.rb | 2 + .../provider/grafana_plugin/grafana_cli.rb | 2 + .../lib/puppet/provider/ini_setting/ruby.rb | 2 + .../minio_client_alias/minio_client_alias.rb | 4 + .../provider/mysql_login_path/inifile.rb | 2 + .../mysql_login_path/mysql_login_path.rb | 4 + .../provider/mysql_login_path/sensitive.rb | 2 + .../provider/network_config/interfaces.rb | 2 + .../puppet/provider/network_config/redhat.rb | 2 + .../puppet/provider/network_config/sles.rb | 2 + .../lib/puppet/provider/reboot/linux.rb | 2 + .../lib/puppet/provider/reboot/posix.rb | 2 + .../lib/puppet/provider/reboot/windows.rb | 2 + .../lib/puppet/provider/file_line/ruby.rb | 2 + .../lib/puppet/provider/yumrepo/inifile.rb | 2 + .../lib/puppet/provider/private_ensure/p.rb | 2 + .../probe/lib/puppet/type/implicit_ensure.rb | 10 + .../modules/probe/lib/puppet/type/inert.rb | 61 +++ .../modules/probe/lib/puppet/type/literals.rb | 25 + .../probe/lib/puppet/type/mixin_ensure.rb | 5 + .../probe/lib/puppet/type/private_ensure.rb | 7 + .../probe/lib/puppet/type/rsapi_behavior.rb | 11 + .../modules/probe/lib/puppet_x/probe/inert.rb | 13 + .../modules/probe/lib/puppet_x/probe/trio.rb | 11 + .../testdata/golden/alternative_entry.pp | 8 +- .../gentypes/testdata/golden/alternatives.pp | 10 +- internal/gentypes/testdata/golden/anchor.pp | 2 +- internal/gentypes/testdata/golden/archive.pp | 10 +- .../gentypes/testdata/golden/concat_file.pp | 2 +- .../gentypes/testdata/golden/file_line.pp | 10 +- internal/gentypes/testdata/golden/firewall.pp | 2 +- .../gentypes/testdata/golden/firewallchain.pp | 2 +- .../testdata/golden/grafana_plugin.pp | 5 +- .../testdata/golden/implicit_ensure.pp | 22 + internal/gentypes/testdata/golden/inert.pp | 19 + .../gentypes/testdata/golden/ini_setting.pp | 2 +- internal/gentypes/testdata/golden/literals.pp | Bin 0 -> 2367 bytes .../testdata/golden/minio_client_alias.pp | 2 +- .../gentypes/testdata/golden/mixin_ensure.pp | 19 + .../testdata/golden/mysql_login_path.pp | 2 +- .../testdata/golden/network_config.pp | 17 +- .../testdata/golden/private_ensure.pp | 24 + internal/gentypes/testdata/golden/reboot.pp | 14 +- .../testdata/golden/rsapi_behavior.pp | 33 ++ internal/gentypes/testdata/golden/yumrepo.pp | 20 +- 58 files changed, 1247 insertions(+), 228 deletions(-) create mode 100644 internal/gentypes/testdata/env/modules/probe/lib/puppet/provider/private_ensure/p.rb create mode 100644 internal/gentypes/testdata/env/modules/probe/lib/puppet/type/implicit_ensure.rb create mode 100644 internal/gentypes/testdata/env/modules/probe/lib/puppet/type/inert.rb create mode 100644 internal/gentypes/testdata/env/modules/probe/lib/puppet/type/literals.rb create mode 100644 internal/gentypes/testdata/env/modules/probe/lib/puppet/type/mixin_ensure.rb create mode 100644 internal/gentypes/testdata/env/modules/probe/lib/puppet/type/private_ensure.rb create mode 100644 internal/gentypes/testdata/env/modules/probe/lib/puppet/type/rsapi_behavior.rb create mode 100644 internal/gentypes/testdata/env/modules/probe/lib/puppet_x/probe/inert.rb create mode 100644 internal/gentypes/testdata/env/modules/probe/lib/puppet_x/probe/trio.rb create mode 100644 internal/gentypes/testdata/golden/implicit_ensure.pp create mode 100644 internal/gentypes/testdata/golden/inert.pp create mode 100644 internal/gentypes/testdata/golden/literals.pp create mode 100644 internal/gentypes/testdata/golden/mixin_ensure.pp create mode 100644 internal/gentypes/testdata/golden/private_ensure.pp create mode 100644 internal/gentypes/testdata/golden/rsapi_behavior.pp diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index ed8d70a..5366271 100644 --- a/internal/gentypes/generate.go +++ b/internal/gentypes/generate.go @@ -5,6 +5,7 @@ import ( "bufio" "errors" "fmt" + "io/fs" "os" "path/filepath" "regexp" @@ -16,6 +17,9 @@ import ( const OutDir = ".resource_types" +// Version changes whenever generated output can change, so deploys rebuild typed environments. +const Version = "2" + var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) type gen struct { @@ -86,7 +90,7 @@ func Generate(env string, roots ...string) error { return err } for _, e := range entries { - if !keep[e.Name()] && e.Type().IsRegular() { + if !keep[e.Name()] && (e.Type().IsRegular() || e.Type()&fs.ModeSymlink != 0) { if err := out.Remove(e.Name()); err != nil { return err } @@ -94,7 +98,7 @@ func Generate(env string, roots ...string) error { } var errs []error for _, in := range inputs { - if err := generateOne(in, out, providers); err != nil { + if err := generateOne(in, out, providers, g.mixins(mods)); err != nil { errs = append(errs, fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err)) } } @@ -122,7 +126,7 @@ func openOut(env string) (*os.Root, error) { return root.OpenRoot(OutDir) } -func generateOne(in string, out *os.Root, providers map[string][]string) error { +func generateOne(in string, out *os.Root, providers map[string][]string, resolve Resolver) error { ifi, err := os.Stat(in) if err != nil { return err @@ -136,7 +140,7 @@ func generateOne(in string, out *os.Root, providers map[string][]string) error { if err != nil { return err } - types, err := parseFile(string(src)) + types, err := parseFile(string(src), resolve) if err != nil { return err } @@ -175,6 +179,35 @@ func generateOne(in string, out *os.Root, providers map[string][]string) error { return out.Rename(tmp, dst) } +var camel = regexp.MustCompile(`([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])`) + +// mixins resolves a constant path to every module's lib/.rb, as Ruby's require would find it. +func (g *gen) mixins(mods []string) Resolver { + return func(path string) ([]string, error) { + rel := strings.ToLower(camel.ReplaceAllString(strings.ReplaceAll(path, "::", "/"), "${1}${3}_${2}${4}")) + ".rb" + var srcs []string + for _, m := range mods { + p := filepath.Join(m, "lib", rel) + if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) { + continue + } + real, err := g.confine(p) + if err != nil { + return nil, err + } + b, err := os.ReadFile(real) + if err != nil { + return nil, err + } + srcs = append(srcs, string(b)) + } + if len(srcs) == 0 { + return nil, fmt.Errorf("no module provides lib/%s", rel) + } + return srcs, nil + } +} + func (g *gen) confine(p string) (string, error) { real, err := filepath.EvalSymlinks(p) if err != nil { diff --git a/internal/gentypes/generate_test.go b/internal/gentypes/generate_test.go index 78f0c91..1f3ee2d 100644 --- a/internal/gentypes/generate_test.go +++ b/internal/gentypes/generate_test.go @@ -1,7 +1,9 @@ package gentypes import ( + "errors" "os" + "os/exec" "path/filepath" "regexp" "strings" @@ -18,11 +20,11 @@ func uncommented(s string) string { return blankRun.ReplaceAllString(commentLine.ReplaceAllString(s, ""), "\n") } -// GENTYPES_ENV/GENTYPES_GOLDEN point the golden comparison at a full environment and its real `puppet generate types` output. +// GENTYPES_ENV/GENTYPES_GOLDEN compare a full environment without comments, since provider docs are not ported. func TestGolden(t *testing.T) { - env, golden := "testdata/env", "testdata/golden" + env, golden, view := "testdata/env", "testdata/golden", func(s string) string { _, rest, _ := strings.Cut(s, "\n"); return rest } if e := os.Getenv("GENTYPES_ENV"); e != "" { - env, golden = e, os.Getenv("GENTYPES_GOLDEN") + env, golden, view = e, os.Getenv("GENTYPES_GOLDEN"), uncommented } work := t.TempDir() if err := os.CopyFS(work, os.DirFS(env)); err != nil { @@ -47,7 +49,7 @@ func TestGolden(t *testing.T) { if err != nil { t.Fatal(err) } - if g, w := uncommented(string(gb)), uncommented(string(wb)); g != w { + if g, w := view(string(gb)), view(string(wb)); g != w { t.Fatalf("mismatch:\n--- got\n%s\n--- want\n%s", g, w) } if _, gotDoc, _ := strings.Cut(string(gb), "\n"); !strings.Contains(string(wb), strings.SplitN(gotDoc, "Puppet::Resource::ResourceType3", 2)[0]) { @@ -109,7 +111,7 @@ func TestQuote(t *testing.T) { func typeOf(t *testing.T, body string) []string { t.Helper() - types, err := parseFile("Puppet::Type.newtype(:t) do\n" + body + "\nend\n") + types, err := parseFile("Puppet::Type.newtype(:t) do\n"+body+"\nend\n", nil) if err != nil { t.Fatal(err) } @@ -195,15 +197,17 @@ func TestUnsupported(t *testing.T) { {"Puppet::Type.newtype(:t) do\n newparam(name_var)\nend", "unsupported expression"}, {"Puppet::Type.newtype(:t) do\n newparam(:a) do\n desc \"x #{NOPE}\"\n end\nend", "#{NOPE}"}, {"Puppet::Type.newtype(:t) do\n newparam(:a, parent: Puppet::Parameter::Custom)\nend", "unsupported parent"}, - {"Puppet::Type.newtype(:t) do\n if x\n newparam(:a)\n end\nend", "unsupported use of newparam"}, - {"Puppet::Type.newtype(:t) do\n [:a, :b].each { |n| newparam(n) }\nend", "unsupported use of newparam"}, + {"Puppet::Type.newtype(:t) do\n if x\n newparam(:a)\n end\nend", "unsupported if x in type body"}, + {"Puppet::Type.newtype(:t) do\n if defined? X\n newparam(:a)\n end\nend", "unsupported conditional newparam"}, + {"Puppet::Type.newtype(:t) do\n [:a, :b].each { |n| newparam(n) }\nend", "unsupported [ :a , :b ].each in type body"}, + {"Puppet::Type.newtype(:t) do\n newparam(:a) do\n validate do\n newvalues(:x)\n end\n end\nend", "unsupported use of newvalues"}, {"Puppet::Type.newtype(:t) do\n def self.title_patterns\n [[/(.*)/, [[:a, lambda { |x| x }]]]]\n end\nend", "title_patterns"}, {"Puppet::Type.newtype(:t, parent: Puppet::Type::File) do\nend", "newtype with options"}, {"Puppet::Type.newtype(:t) do\n newparam(:a) do\n desc 'x' + dynamic\n end\nend", "unsupported expression"}, {"Puppet::Type.newtype(:t) do\n @isomorphic = false\nend", "@isomorphic"}, {"Puppet::Type.newtype(:t) do\n newparam(:a)\n newparam(:b, namevar: true)\n newparam(:c, namevar: true)\nend", "two or more key attributes"}, } { - types, err := parseFile(c.src) + types, err := parseFile(c.src, nil) if err == nil { _, err = render(types[0], nil, time.Now()) } @@ -234,7 +238,7 @@ Puppet::Type.newtype(:t) do end end ` - types, err := parseFile(src) + types, err := parseFile(src, nil) if err != nil { t.Fatal(err) } @@ -273,7 +277,7 @@ func TestGenerateFiles(t *testing.T) { cache := t.TempDir() mod := filepath.Join(cache, "mods", "foo") writeFile(t, filepath.Join(mod, "lib/puppet/type/foo.rb"), strings.ReplaceAll(simpleType, "%s", "foo")) - writeFile(t, filepath.Join(mod, "lib/puppet/provider/foo/posix.rb"), "") + writeFile(t, filepath.Join(mod, "lib/puppet/provider/foo/posix.rb"), "Puppet::Type.type(:foo).provide(:posix) do\nend\n") writeFile(t, filepath.Join(env, "modules/bar/lib/puppet/type/bar.rb"), strings.ReplaceAll(simpleType, "%s", "bar")) writeFile(t, filepath.Join(env, "site/bar/lib/puppet/type/shadowed.rb"), "not ruby (") writeFile(t, filepath.Join(env, "environment.conf"), "# comment\nmodulepath = modules:site:$basemodulepath\n") @@ -297,8 +301,11 @@ func TestGenerateFiles(t *testing.T) { if err := Generate(env, cache); err != nil { t.Fatal(err) } - if exists(filepath.Join(out, "stale.pp")) || !exists(filepath.Join(out, "keepdir")) || !exists(filepath.Join(out, "link.pp")) { - t.Fatal("cleanup must remove only stale regular files") + if exists(filepath.Join(out, "stale.pp")) || exists(filepath.Join(out, "link.pp")) || !exists(filepath.Join(out, "keepdir")) { + t.Fatal("cleanup must unlink stale files and symlinks and keep directories") + } + if !exists("/etc/passwd") { + t.Fatal("unlinking a stale symlink must not touch its target") } if readFile(t, victim) != "untouched" { t.Fatal("writes must never follow symlinks under the output dir") @@ -406,3 +413,195 @@ func TestGenerateErrors(t *testing.T) { } }) } + +func parseWithin(t *testing.T, src string, resolve Resolver) ([]*rtype, error) { + t.Helper() + type res struct { + ts []*rtype + err error + } + ch := make(chan res, 1) + go func() { ts, err := parseFile(src, resolve); ch <- res{ts, err} }() + select { + case r := <-ch: + return r.ts, r.err + case <-time.After(3 * time.Second): + t.Fatalf("parseFile(%.40q) did not return", src) + } + return nil, nil +} + +func TestStrayCloserIsAnError(t *testing.T) { + for src, want := range map[string]string{ + ")\n": `unmatched ")"`, + "]\n": `unmatched "]"`, + "}\n": `unmatched "}"`, + "end\n": `unmatched "end"`, + "module A\n foo )\nend\n": `unmatched ")"`, + "Puppet::Type.newtype(:t) do\n }\nend\n": "line 2: unsupported } in type body", + "Puppet::Type.newtype(:t) do\n newparam(:a) do\n )\n end\nend\n": "line 3: unsupported ) in attribute a", + } { + if _, err := parseWithin(t, src, nil); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: got %v, want %q", src, err, want) + } + } +} + +func TestStepBudget(t *testing.T) { + var err error + func() { + defer guard(&err) + p := &parser{toks: []token{{kind: tEOF}}} + for { + p.cur() + } + }() + if !errors.Is(err, errBudget) { + t.Fatalf("got %v", err) + } +} + +func TestDeepNestingIsAnError(t *testing.T) { + if os.Getenv("GENTYPES_DEEP_CHILD") == "1" { + _, err := parseFile("Puppet::Type.newtype(:t) do\n newparam(:a) do\n newvalues("+strings.Repeat("[", 4<<20)+"\n", nil) + if err == nil || !strings.Contains(err.Error(), "nesting deeper than") { + os.Exit(3) + } + return + } + for _, src := range []string{ + "Puppet::Type.newtype(:u) do\n newparam(:a) do\n newvalues(" + strings.Repeat("[", 300) + strings.Repeat("]", 300) + ")\n end\nend\n", + strings.Repeat("module A\n", 300) + strings.Repeat("end\n", 300), + "Puppet::Type.newtype(:t) do\n newparam(:a) do\n" + strings.Repeat("if defined? X\n", 300) + strings.Repeat("end\n", 300) + "end\nend\n", + `x = "` + strings.Repeat(`#{"`, 300) + strings.Repeat(`"}`, 300) + `"` + "\n", + } { + if _, err := parseWithin(t, "Puppet::Type.newtype(:t) do\nend\n"+src, nil); err == nil || !strings.Contains(err.Error(), "deeper than") { + t.Errorf("%.40q: got %v", src, err) + } + } + cmd := exec.Command(os.Args[0], "-test.run=^TestDeepNestingIsAnError$") + cmd.Env = append(os.Environ(), "GENTYPES_DEEP_CHILD=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("4MiB of '[' must be a parse error: %v\n%.300s", err, out) + } +} + +func TestImplicitEnsurable(t *testing.T) { + const head = "Puppet::Type.newtype(:t) do\n newproperty(:a)\n newparam(:name, namevar: true)\n" + for body, want := range map[string]string{ + " def exists?; end\n def create; end\n def destroy\n true\n end\n": "ensure Enum['present', 'absent']\na Any\nname Any", + " def exists?; end\n def create; end\n private\n def destroy; end\n": "a Any\nname Any", + " def exists?; end\n def create; end\n": "a Any\nname Any", + " ensurable do\n newvalue(:x)\n end\n def exists?; end\n def create; end\n def destroy; end\n": "ensure Enum['x']\na Any\nname Any", + } { + types, err := parseWithin(t, head+body+"end\n", nil) + if err != nil { + t.Fatal(err) + } + var got []string + for _, a := range append(types[0].props, types[0].params...) { + typ, _ := a.puppetType() + got = append(got, a.name+" "+typ) + } + if g := strings.Join(got, "\n"); g != want { + t.Errorf("%s:\n got %s\nwant %s", body, g, want) + } + } + out, err := render(mustParse(t, head+" def exists?; end\n def create; end\n def destroy; end\nend\n"), nil, time.Unix(0, 0)) + if err != nil || !strings.Contains(out, " # The basic property that the resource should be in.\n # \n # Valid values are `present`, `absent`.\n Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'),\n") { + t.Fatalf("implicit ensure must render like real puppet: %v\n%s", err, out) + } + if _, err := parseWithin(t, head+" if defined? X\n def create; end\n end\nend\n", nil); err == nil || !strings.Contains(err.Error(), "conditional def create") { + t.Fatalf("got %v", err) + } +} + +func mustParse(t *testing.T, src string) *rtype { + t.Helper() + types, err := parseWithin(t, src, nil) + if err != nil { + t.Fatal(err) + } + return types[0] +} + +func TestResourceAPIBehaviorSpelling(t *testing.T) { + ty := mustParse(t, "Puppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behavior: :namevar }, p: { type: 'String', behavior: :parameter } })\n") + if len(ty.params) != 2 || !ty.params[0].namevar || ty.params[1].namevar || len(ty.props) != 0 { + t.Fatalf("behavior: is an alias of behaviour: %+v %+v", ty.params, ty.props) + } + for src, want := range map[string]string{ + "Puppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behavior: :namevar, behaviour: :namevar } })\n": "both behavior and behaviour", + "Puppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behaviour: 'namevar' } })\n": "behaviour must be a symbol", + } { + if _, err := parseWithin(t, src, nil); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%s: got %v, want %q", src, err, want) + } + } +} + +func TestTypeBodyRejectsUnknownStatements(t *testing.T) { + for stmt, want := range map[string]string{ + "include PuppetX::Foo::Params": "line 3: include PuppetX::Foo::Params: mixin source is not available", + "extend PuppetX::Foo": "line 3: unsupported extend PuppetX::Foo in type body", + "PuppetX::Foo.add_params(self)": "line 3: unsupported PuppetX::Foo.add_params in type body", + "instance_eval(&PuppetX::Foo::PARAMS)": "line 3: unsupported instance_eval in type body", + "self.class_eval { newparam(:x) }": "unsupported self.class_eval in type body", + "attr_accessor :create": "unsupported attr_accessor :create in type body", + "private :create": "unsupported private :create in type body", + "x ||= 1": "unsupported x ||= 1 in type body", + "@parameters = []": "unsupported @parameters in type body", + "@@count = 1": "unsupported @@count in type body", + "FOO = compute": "unsupported non-literal constant FOO", + "x = compute": "unsupported expression \"compute\"", + "Puppet.warning(compute)": "unsupported expression \"compute\"", + "def self.doc; 'x'; end": "unsupported def self.doc in type body", + "class << self\n def title_patterns; []; end\n end": "unsupported def title_patterns in class << self", + "class << self\n attr_reader :doc\n end": "attr_reader doc shadows a Puppet::Type class method", + "validate(compute) do\n end": "validate: unsupported expression", + "newparam(:b) do\n defaultto Facter.value(:x)\n end": `unsupported "." after "defaultto"`, + "newparam(:b) do\n def self.doc; end\n end": "unsupported def self.doc in attribute b", + "newparam(:b) do\n include Foo\n end": "unsupported include Foo in attribute b", + "newparam(:b) do\n @doc2 = 'x'\n end": "unsupported @doc2 in attribute b", + "newparam(:b) do\n newvalues(:a) if x\n end": `unsupported "if" after "newvalues"`, + "newparam(:b) do\n if defined? X\n desc 'x'\n end\n end": "unsupported conditional desc", + } { + _, err := parseWithin(t, "Puppet::Type.newtype(:t) do\n newparam(:name, namevar: true)\n "+stmt+"\nend\n", nil) + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: got %v, want %q", stmt, err, want) + } + } +} + +func TestMixinMethods(t *testing.T) { + const path = "PuppetX::M::Mix" + for src, want := range map[string]string{ + "module PuppetX\n module M\n module Mix\n X = 1\n def self.try; end\n def create; end\n private\n def destroy; end\n end\n end\nend\n": "create", + "require 'x'\nmodule Other\n def destroy; end\nend\nmodule PuppetX::M\n module Mix\n def exists?; end\n end\nend\n": "exists?", + "module PuppetX::M::Mix\n def self.included(base); base.newparam(:x); end\nend\n": "def self.included hook", + "module PuppetX::M::Mix\n include Other\nend\n": "unsupported include Other in mixin", + "module PuppetX::M::Mix\n extend ActiveSupport::Concern\nend\n": "unsupported extend", + "module PuppetX::M\nend\n": "not defined", + } { + got, err := mixinMethods(src, path) + if g := strings.Join(got, " "); err != nil && !strings.Contains(err.Error(), want) || err == nil && g != want { + t.Errorf("%q: got %q %v, want %q", src, g, err, want) + } + } +} + +func TestLiteralNormalisation(t *testing.T) { + out, err := render(mustParse(t, "Puppet::Type.newtype(:t) do\n newparam(:name, namevar: true)\n newparam(:a) do\n newvalues(0x1f, 1_000, \"\\101\", /é/)\n end\nend\n"), nil, time.Unix(0, 0)) + if err != nil || !strings.Contains(out, "Variant[Enum['31', '1000', 'A'], Pattern[/(?-mix:é)/]]") || !strings.Contains(out, "Values can match `/é/`.") { + t.Fatalf("got %v:\n%s", err, out) + } + for _, v := range []string{"?a", "1r", "2i", "1e400", "0x", "1__0", "08", `"\M-a"`, `"\xff"`, `"\377"`, "`id`", "%W[a#{1}]", `%w[a\ b]`, "%x(id)", `/\M-a/`, `/\xff/`, `/\200/`, `/(?i)é/`, `/a/n`} { + types, err := parseWithin(t, "Puppet::Type.newtype(:t) do\n newparam(:name, namevar: true)\n newparam(:a) do\n newvalues("+v+")\n end\nend\n", nil) + if err == nil { + _, err = render(types[0], nil, time.Unix(0, 0)) + } + if err == nil { + t.Errorf("%s: literal Ruby renders differently must be rejected", v) + } + } +} diff --git a/internal/gentypes/lexer.go b/internal/gentypes/lexer.go index adde2df..2fcb026 100644 --- a/internal/gentypes/lexer.go +++ b/internal/gentypes/lexer.go @@ -4,8 +4,11 @@ import ( "fmt" "strconv" "strings" + "unicode/utf8" ) +const maxDepth = 256 + type kind int const ( @@ -56,6 +59,9 @@ type heredoc struct { } func lex(src string) ([]token, error) { + if !utf8.ValidString(src) { + return nil, fmt.Errorf("source is not valid UTF-8") + } l := &lexer{src: src, line: 1} if err := l.run(); err != nil { return nil, fmt.Errorf("line %d: %w", l.line, err) @@ -186,7 +192,9 @@ func (l *lexer) next(space bool) error { switch { case c >= '0' && c <= '9': s := l.pos - for l.pos < len(l.src) && (isIdentChar(l.src[l.pos]) || l.src[l.pos] == '.' && l.peek(1) >= '0' && l.peek(1) <= '9') { + hex := c == '0' && (l.peek(1) == 'x' || l.peek(1) == 'X') + for l.pos < len(l.src) && (isIdentChar(l.src[l.pos]) || l.src[l.pos] == '.' && l.peek(1) >= '0' && l.peek(1) <= '9' || + !hex && (l.src[l.pos] == '+' || l.src[l.pos] == '-') && (l.src[l.pos-1] == 'e' || l.src[l.pos-1] == 'E') && l.peek(1) >= '0' && l.peek(1) <= '9') { l.pos++ } l.emit(token{kind: tNum, text: l.src[s:l.pos]}) @@ -233,7 +241,7 @@ func (l *lexer) next(space bool) error { l.emit(token{kind: tOp, text: "::"}) case c == ':' && (l.peek(1) == '"' || l.peek(1) == '\''): l.pos++ - parts, err := l.quoted(l.src[l.pos], l.src[l.pos], l.src[l.pos] == '"') + parts, err := l.quoted(l.src[l.pos], l.src[l.pos], l.src[l.pos] == '"', 0) if err != nil { return err } @@ -249,11 +257,11 @@ func (l *lexer) next(space bool) error { } l.emit(token{kind: tSym, text: l.src[s:l.pos]}) case c == '"' || c == '\'' || c == '`': - parts, err := l.quoted(c, c, c != '\'') + parts, err := l.quoted(c, c, c != '\'', 0) if err != nil { return err } - l.emit(token{kind: tStr, parts: parts}) + l.emit(token{kind: tStr, parts: parts, flags: string(c)}) case c == '/' && l.literalStart(space, 1): return l.regex('/', '/') case c == '%' && l.literalStart(space, 1) && l.percentLiteral(): @@ -310,39 +318,43 @@ func (l *lexer) percent() error { case 'r': return l.regex(open, cl) case 'w', 'W', 'i', 'I': - parts, err := l.quoted(open, cl, false) + body, err := l.scan(open, cl, typ == 'W' || typ == 'I', 0) if err != nil { return err } - var body string - for _, p := range parts { - body += p.text + if strings.ContainsRune(body, '\\') || (typ == 'W' || typ == 'I') && strings.Contains(body, "#") { + return fmt.Errorf("unsupported escape or interpolation in %%%c literal", typ) } l.emit(token{kind: tWords, words: strings.Fields(body)}) case 's': - parts, err := l.quoted(open, cl, false) + parts, err := l.quoted(open, cl, false, 0) if err != nil { return err } l.emit(token{kind: tSym, parts: parts}) case 'q': - parts, err := l.quoted(open, cl, false) + parts, err := l.quoted(open, cl, false, 0) + if err != nil { + return err + } + l.emit(token{kind: tStr, parts: parts}) + case 'Q': + parts, err := l.quoted(open, cl, true, 0) if err != nil { return err } l.emit(token{kind: tStr, parts: parts}) default: - parts, err := l.quoted(open, cl, true) - if err != nil { - return err - } - l.emit(token{kind: tStr, parts: parts}) + return fmt.Errorf("unsupported %%%c literal", typ) } return nil } // scan reads a delimited body starting at the opening delimiter, returning raw text with nesting and #{} honoured. -func (l *lexer) scan(open, cl byte, interp bool) (string, error) { +func (l *lexer) scan(open, cl byte, interp bool, nest int) (string, error) { + if nest > maxDepth { + return "", fmt.Errorf("interpolation nested deeper than %d", maxDepth) + } l.pos++ s := l.pos depth := 0 @@ -354,7 +366,7 @@ func (l *lexer) scan(open, cl byte, interp bool) (string, error) { continue case interp && c == '#' && l.peek(1) == '{': l.pos++ - if _, err := l.scan('{', '}', true); err != nil { + if _, err := l.scan('{', '}', true, nest+1); err != nil { return "", err } continue @@ -373,8 +385,8 @@ func (l *lexer) scan(open, cl byte, interp bool) (string, error) { return "", fmt.Errorf("unterminated literal") } -func (l *lexer) quoted(open, cl byte, dq bool) ([]part, error) { - body, err := l.scan(open, cl, dq) +func (l *lexer) quoted(open, cl byte, dq bool, depth int) ([]part, error) { + body, err := l.scan(open, cl, dq, depth) if err != nil { return nil, err } @@ -431,78 +443,119 @@ func splitInterp(body string) ([]part, error) { b.WriteByte(c) continue } - i++ - switch e := body[i]; e { - case 'n': - b.WriteByte('\n') - case 't': - b.WriteByte('\t') - case 's': - b.WriteByte(' ') - case 'r': - b.WriteByte('\r') - case '0': - b.WriteByte(0) - case 'e': - b.WriteByte(0x1b) - case 'a': - b.WriteByte(7) - case 'b': - b.WriteByte(8) - case 'f': - b.WriteByte('\f') - case 'v': - b.WriteByte('\v') - case '\n': - case 'u': - hex := "" - if i+1 < len(body) && body[i+1] == '{' { - end := strings.IndexByte(body[i:], '}') - if end < 0 { - return nil, fmt.Errorf("bad \\u escape") - } - hex, i = body[i+2:i+end], i+end - } else if i+4 < len(body) { - hex, i = body[i+1:i+5], i+4 - } - r, err := strconv.ParseUint(hex, 16, 32) - if err != nil { - return nil, fmt.Errorf("bad \\u escape") - } - b.WriteString(string(rune(r))) - case 'x': - if i+2 >= len(body) { - return nil, fmt.Errorf("bad \\x escape") - } - r, err := strconv.ParseUint(body[i+1:i+3], 16, 8) - if err != nil { - return nil, fmt.Errorf("bad \\x escape") - } - b.WriteByte(byte(r)) - i += 2 - default: - b.WriteByte(e) + n, err := unescape(&b, body[i+1:]) + if err != nil { + return nil, err } + i += n } if b.Len() > 0 || len(parts) == 0 { parts = append(parts, part{text: b.String()}) } + for _, p := range parts { + if !p.code && !utf8.ValidString(p.text) { + return nil, fmt.Errorf("string escape yields invalid UTF-8") + } + } return parts, nil } +func hexVal(s string, max int) (uint64, int) { + n := 0 + for n < len(s) && n < max && strings.IndexByte("0123456789abcdefABCDEF", s[n]) >= 0 { + n++ + } + v, _ := strconv.ParseUint(s[:n], 16, 32) + return v, n +} + +// unescape writes the Ruby double-quoted escape at the start of s (after the backslash), returning its length. +func unescape(b *strings.Builder, s string) (int, error) { + if i := strings.IndexByte("ntsrfvaeb", s[0]); i >= 0 { + b.WriteByte("\n\t \r\f\v\a\x1b\b"[i]) + return 1, nil + } + switch e := s[0]; { + case e == '\n': + return 1, nil + case e >= '0' && e <= '7': + n, v := 0, 0 + for n < len(s) && n < 3 && s[n] >= '0' && s[n] <= '7' { + v = v*8 + int(s[n]-'0') + n++ + } + b.WriteByte(byte(v)) + return n, nil + case e == 'x': + v, n := hexVal(s[1:], 2) + if n == 0 { + return 0, fmt.Errorf("invalid \\x escape") + } + b.WriteByte(byte(v)) + return n + 1, nil + case e == 'u': + if len(s) > 1 && s[1] == '{' { + end := strings.IndexByte(s, '}') + if end < 0 || strings.TrimSpace(s[2:end]) == "" { + return 0, fmt.Errorf("invalid \\u escape") + } + for _, h := range strings.Fields(s[2:end]) { + v, n := hexVal(h, 6) + if n != len(h) || !utf8.ValidRune(rune(v)) { + return 0, fmt.Errorf("invalid \\u escape") + } + b.WriteRune(rune(v)) + } + return end + 1, nil + } + v, n := hexVal(s[1:], 4) + if n != 4 || !utf8.ValidRune(rune(v)) { + return 0, fmt.Errorf("invalid \\u escape") + } + b.WriteRune(rune(v)) + return 5, nil + case e == 'c' || e == 'C' && len(s) > 1 && s[1] == '-': + n := 1 + if e == 'C' { + n = 2 + } + if n >= len(s) || s[n] == '\\' || s[n] >= 0x80 { + return 0, fmt.Errorf("unsupported control escape") + } + if s[n] == '?' { + b.WriteByte(127) + } else { + b.WriteByte(s[n] & 0x9f) + } + return n + 1, nil + case e == 'M' || e == 'C': + return 0, fmt.Errorf("unsupported \\%c escape", e) + } + _, n := utf8.DecodeRuneInString(s) + b.WriteString(s[:n]) + return n, nil +} + func (l *lexer) regex(open, cl byte) error { - body, err := l.scan(open, cl, true) + raw, err := l.scan(open, cl, true, 0) if err != nil { return err } - if open == '/' { - body = strings.ReplaceAll(body, `\/`, "/") + var body strings.Builder + for i := 0; i < len(raw); i++ { + if raw[i] == '\\' && i+1 < len(raw) { + if raw[i+1] != cl || strings.IndexByte("$*+.?^|)]}>", cl) >= 0 { + body.WriteByte('\\') + } + i++ + } + body.WriteByte(raw[i]) } s := l.pos for l.pos < len(l.src) && strings.IndexByte("mixounse", l.src[l.pos]) >= 0 { l.pos++ } - l.emit(token{kind: tRegex, text: body, flags: l.src[s:l.pos]}) + l.emit(token{kind: tRegex, text: body.String(), flags: l.src[s:l.pos]}) return nil } diff --git a/internal/gentypes/parse.go b/internal/gentypes/parse.go index e9adf70..d92662e 100644 --- a/internal/gentypes/parse.go +++ b/internal/gentypes/parse.go @@ -1,9 +1,13 @@ package gentypes import ( + "errors" "fmt" + "math" + "math/big" "regexp" "slices" + "strconv" "strings" ) @@ -25,6 +29,7 @@ type attr struct { res []*value ensure bool defaults bool + raw bool } type pattern struct { @@ -40,6 +45,8 @@ type rtype struct { patterns []pattern custom bool rsapi bool + methods map[string]bool + private bool } type vkind int @@ -55,6 +62,7 @@ const ( vArray vHash vConst + vBlock ) type rval struct { @@ -74,12 +82,30 @@ func (v rval) get(key string) (rval, bool) { return rval{}, false } +// Resolver returns the sources that may define a mixin module, by Ruby's constant-to-path convention. +type Resolver func(path string) ([]string, error) + type parser struct { - toks []token - i int - consts map[string]rval - used map[int]bool - types []*rtype + toks []token + i int + consts map[string]rval + used map[int]bool + types []*rtype + depth int + steps int + cond int + resolve Resolver +} + +var errBudget = errors.New("parse step budget exceeded") + +func guard(err *error) { + if r := recover(); r != nil { + if r != errBudget { + panic(r) + } + *err = errBudget + } } var watched = map[string]bool{ @@ -88,19 +114,20 @@ var watched = map[string]bool{ "defaultvalues": true, "providify": true, } -func parseFile(src string) ([]*rtype, error) { +func parseFile(src string, resolve Resolver) (types []*rtype, err error) { + defer guard(&err) toks, err := lex(src) if err != nil { return nil, err } - p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}} + p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}, resolve: resolve} if err := p.body("", p.topStmt); err != nil { return nil, p.wrap(err) } for i, t := range p.toks { if t.kind == tIdent && t.text == "def" && (i == 0 || p.toks[i-1].text != ".") { p.i = i - p.skipStatement() + _ = p.skipStatement() for j := i; j < p.i; j++ { p.used[j] = true } @@ -129,10 +156,15 @@ func (p *parser) wrap(err error) error { if strings.HasPrefix(err.Error(), "line ") { return err } - return fmt.Errorf("line %d: %w", p.cur().line, err) + return fmt.Errorf("line %d: %w", p.toks[p.i].line, err) } -func (p *parser) cur() token { return p.toks[p.i] } +func (p *parser) cur() token { + if p.steps++; p.steps > 256*len(p.toks)+4096 { + panic(errBudget) + } + return p.toks[p.i] +} func (p *parser) at(off int) token { if p.i+off < len(p.toks) { @@ -149,7 +181,7 @@ func (p *parser) is(k kind, text string) bool { func (p *parser) op(text string) bool { return p.is(tOp, text) } func (p *parser) take() token { - t := p.toks[p.i] + t := p.cur() if t.kind != tEOF { p.i++ } @@ -170,6 +202,13 @@ func (p *parser) skipNL() { } } +func (p *parser) enter() error { + if p.depth++; p.depth > maxDepth { + return fmt.Errorf("nesting deeper than %d", maxDepth) + } + return nil +} + func describe(t token) string { switch t.kind { case tEOF: @@ -184,6 +223,33 @@ func describe(t token) string { return fmt.Sprintf("%q", t.text) } +// construct names the statement at the cursor for error messages, e.g. "include PuppetX::Foo". +func (p *parser) construct() string { + var b strings.Builder + for j := 0; j < 8; j++ { + t := p.at(j) + if t.kind == tNL || t.kind == tEOF || t.kind == tOp && strings.Contains(" ( { ; = ", " "+t.text+" ") || t.kind == tIdent && t.text == "do" { + break + } + joined := t.kind == tOp && (t.text == "::" || t.text == ".") || j > 0 && p.at(j-1).kind == tOp && (p.at(j-1).text == "::" || p.at(j-1).text == ".") + if j > 0 && !joined { + b.WriteByte(' ') + } + switch { + case t.text == "": + b.WriteString(describe(t)) + case t.kind == tSym: + b.WriteString(":" + t.text) + default: + b.WriteString(t.text) + } + } + if b.Len() == 0 { + return describe(p.cur()) + } + return b.String() +} + func (p *parser) closes(closeTok string) bool { switch closeTok { case "end": @@ -196,6 +262,10 @@ func (p *parser) closes(closeTok string) bool { // body runs stmt for every statement until closeTok ("end", "}" or "" for EOF), skipping statements it declines. func (p *parser) body(closeTok string, stmt func() (bool, error)) error { + defer func() { p.depth-- }() + if err := p.enter(); err != nil { + return err + } for { p.skipNL() if p.closes(closeTok) { @@ -211,7 +281,9 @@ func (p *parser) body(closeTok string, stmt func() (bool, error)) error { return err } if !ok { - p.skipStatement() + if err := p.skipStatement(); err != nil { + return err + } continue } if t := p.cur(); t.kind != tNL && !p.op(";") && !p.closes(closeTok) { @@ -239,9 +311,14 @@ func continues(prev token) bool { return prev.kind == tOp && !strings.Contains(")]}|", prev.text) } -// skipStatement consumes one statement of arbitrary Ruby, tracking bracket and keyword nesting. -func (p *parser) skipStatement() { - depth, loop := 0, false +func (p *parser) skipStatement() error { return p.skip(false) } + +// skipBlock consumes exactly one do...end or {...} block starting at its opener. +func (p *parser) skipBlock() error { return p.skip(true) } + +// skip consumes one statement (or one block) of arbitrary Ruby, tracking bracket and keyword nesting. +func (p *parser) skip(block bool) error { + depth, loop, start := 0, false, p.i for { t := p.cur() var prev *token @@ -251,7 +328,18 @@ func (p *parser) skipStatement() { afterDot := prev != nil && prev.kind == tOp && (prev.text == "." || prev.text == "&." || prev.text == "::") switch { case t.kind == tEOF: - return + return nil + case t.kind == tOp && strings.Contains(")]}", t.text) || t.kind == tIdent && !afterDot && t.text == "end": + if depth == 0 { + if p.i == start { + return fmt.Errorf("unmatched %q", t.text) + } + return nil + } + if depth--; block && depth == 0 { + p.i++ + return nil + } case t.kind == tNL || t.kind == tOp && t.text == ";": loop = false if depth == 0 { @@ -259,22 +347,12 @@ func (p *parser) skipStatement() { if t.kind == tNL && (prev != nil && continues(*prev) || next.kind == tOp && (next.text == "." || next.text == "&.")) { break } - return + return nil } case t.kind == tOp && strings.Contains("([{", t.text): depth++ - case t.kind == tOp && strings.Contains(")]}", t.text): - if depth == 0 { - return - } - depth-- case t.kind == tIdent && !afterDot: switch t.text { - case "end": - if depth == 0 { - return - } - depth-- case "do": if loop { loop = false @@ -310,6 +388,14 @@ func (p *parser) constAssign() (bool, error) { return true, nil } +func (p *parser) strictConstAssign() error { + name := p.cur().text + if ok, _ := p.constAssign(); !ok { + return fmt.Errorf("unsupported non-literal constant %s", name) + } + return nil +} + func (p *parser) topStmt() (bool, error) { t := p.cur() switch { @@ -360,7 +446,7 @@ func symName(v rval) (string, error) { } func (v rval) kindName() string { - return [...]string{"string", "symbol", "regex", "number", "true", "false", "nil", "array", "hash", "constant " + v.s}[v.k] + return [...]string{"string", "symbol", "regex", "number", "true", "false", "nil", "array", "hash", "constant " + v.s, "block argument"}[v.k] } func (p *parser) newtype() error { @@ -375,7 +461,7 @@ func (p *parser) newtype() error { if err != nil { return err } - t := &rtype{name: name} + t := &rtype{name: name, methods: map[string]bool{}} p.types = append(p.types, t) closeTok, err := p.blockOpen() if err != nil { @@ -384,7 +470,18 @@ func (p *parser) newtype() error { if closeTok == "" { return fmt.Errorf("newtype without a block") } - return p.body(closeTok, func() (bool, error) { return p.typeStmt(t) }) + if err := p.body(closeTok, func() (bool, error) { return p.typeStmt(t) }); err != nil { + return err + } + if t.methods["exists?"] && t.methods["create"] && t.methods["destroy"] && !slices.ContainsFunc(t.props, func(a *attr) bool { return a.name == "ensure" }) { + if t.hasParam("ensure") { + return fmt.Errorf("implicit ensurable conflicts with parameter ensure") + } + a := &attr{name: "ensure", ensure: true} + a.defaultValues() + t.addProp(a) + } + return nil } func (p *parser) blockOpen() (string, error) { @@ -440,7 +537,109 @@ func (p *parser) docStmt(doc *string) (bool, error) { return false, nil } +func set(words string) map[string]bool { + m := map[string]bool{} + for _, w := range strings.Fields(words) { + m[w] = true + } + return m +} + +// Inert DSL calls, verified in openvox type.rb, parameter.rb and util/provider_features.rb. +var ( + typeBlocks = set("validate autorequire autobefore autonotify autosubscribe feature") + attrBlocks = set("validate munge unmunge defaultto isrequired sensitive attr_accessor attr_reader attr_writer") + logLevels = set("debug info notice warning err alert emerg crit") + reserved = set("and begin break case class def defined? do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield") + // class-level ivars read by openvox type.rb, metatype/manager.rb, util/{docs,classgen,provider_features}.rb + typeIvars = set("aliases apply_to attrclasses attrtypes autobefores autonotifies autorequires autosubscribes declared_features defaultprovider defaults doc feature_module features isomorphic key_attribute_parameters key_attributes_cache managed manager_lock metaparamhash metaparams methods name name_var_cache noop objects original_parameters paramdoc parameters paramhash parent path properties provider provider_hashes providerloader purging ref resource stampwarnings subclasses tags title typeloader types validattrs validproperties value virtual") + // Puppet::Type.singleton_class methods defined by Puppet or Enumerable (openvox 9.3.0) + typeClassMethods = set("N_ Nn_ _ alert allattrs allclear apply_to apply_to_all apply_to_device apply_to_host attrclass attrtype autobefore autonotify autorequire autosubscribe benchmark build_exception_trace can_apply_to chain chunk chunk_while clear_deprecation_warnings clear_environment clear_misses clear_warnings collect collect_concat compact count create_erb crit cycle debug debug_once default_env defaultprovider deprecation_warning desc detect deterministic_rand deterministic_rand_int doc dochook doctable drop drop_while each_cons each_entry each_slice each_with_index each_with_object eachautobefore eachautonotify eachautorequire eachautosubscribe eachmetaparam eachtype emerg ensurable entries err exit_on_fail feature feature_module featuredocs features filter filter_map find find_all find_index first flat_map format_backtrace format_exception genclass genconst_string genmodule genthing get_deprecation_offender get_env get_environment grep grep_v group_by handle_param_options handleclassconst hash2resource info initclass initvars inject instances issue_deprecation_warning key_attribute_parameters key_attributes lazy loadall log_and_raise log_deprecations_to_file log_exception log_metadata log_source map markdown_definitionlist markdown_header max max_by merge_environment metaparamclass metaparamdoc metaparams min min_by minmax minmax_by n_ name name2const needs_ensure_retrieved newmetaparam newparam newproperty newtype nodoc notice notice_once np_ ns_ p_ pad paramclass paramdoc parameters parameters_to_include partition path_to_uri properties propertybyname provide provider provider_feature provider_hash provider_hash_by_type providerloader providers providers_by_source providify puppet_deprecation_warning reduce reject relationship_params replace_file reverse_each rfc2396_escape rmclass rmtype s_ safe_posix_fork scrub select self_refresh send_log set_env skip_external_facts slice_after slice_before slice_when sort sort_by storeclass suitableprovider sum symbolizehash take take_while tally thinmark title_patterns to_a to_h to_s to_set type typeloader uniq unprovide uri_encode uri_query_encode uri_to_path uri_unescape validate validproperties warn_once warning warnonce which withenv yaml_tag zip") +) + +func isLocal(t token) bool { + return t.kind == tIdent && !reserved[t.text] && t.text[0] >= 'a' && t.text[0] <= 'z' && !strings.ContainsAny(t.text, "?!") +} + +func (p *parser) assigns() bool { return p.at(1).kind == tOp && p.at(1).text == "=" } + +// inert consumes a statement that cannot change generated output; t is set in a type body, a in an attribute body. +func (p *parser) inert(t *rtype, a *attr) (bool, error) { + c := p.cur() + switch { + case isLocal(c) && p.assigns(): + p.i += 2 + if (p.is(tIdent, "proc") || p.is(tIdent, "lambda")) && (p.at(1).kind == tIdent && p.at(1).text == "do" || p.at(1).kind == tOp && p.at(1).text == "{") { + p.take() + return true, p.skipBlock() + } + _, err := p.expr() + return true, err + case c.kind == tIdent && (t != nil && typeBlocks[c.text] || a != nil && attrBlocks[c.text]): + p.take() + if _, err := p.args(); err != nil { + return true, fmt.Errorf("%s: %w", c.text, err) + } + if p.is(tIdent, "do") || p.op("{") { + return true, p.skipBlock() + } + return true, nil + case c.kind == tIdent && c.text == "def": + if p.at(1).kind == tIdent && p.at(1).text == "self" { + return false, nil + } + if name := p.at(1).text; t != nil { + if p.cond > 0 && (name == "exists?" || name == "create" || name == "destroy") { + return true, fmt.Errorf("unsupported conditional def %s", name) + } + t.methods[name] = !t.private + } + return true, p.skipStatement() + case c.kind == tIdent && (c.text == "if" || c.text == "unless") && p.at(1).kind == tIdent && p.at(1).text == "defined?": + p.i += 2 + paren := p.op("(") + if paren { + p.take() + } + if p.cur().kind != tConst { + return true, fmt.Errorf("unsupported %s condition", c.text) + } + for p.take(); p.op("::") && p.at(1).kind == tConst; p.take() { + p.take() + } + if paren { + if err := p.expect(")"); err != nil { + return true, err + } + } + if p.is(tIdent, "then") { + p.take() + } + p.cond++ + defer func() { p.cond-- }() + if t != nil { + return true, p.body("end", func() (bool, error) { return p.typeStmt(t) }) + } + return true, p.body("end", func() (bool, error) { return p.attrStmt(a) }) + case t != nil && c.kind == tIVar && !strings.HasPrefix(c.text, "@@") && !typeIvars[c.text[1:]] && p.assigns(): + p.i += 2 + _, err := p.expr() + return true, err + case c.kind == tConst && c.text == "Puppet" && p.at(1).text == "." && logLevels[p.at(2).text]: + p.i += 3 + _, err := p.args() + return true, err + } + return false, nil +} + func (p *parser) typeStmt(t *rtype) (bool, error) { + if ok, err := p.inert(t, nil); ok || err != nil { + return true, err + } + if p.cond > 0 { + return true, fmt.Errorf("unsupported conditional %s", p.construct()) + } if ok, err := p.docStmt(&t.doc); ok || err != nil { return ok, err } @@ -469,10 +668,128 @@ func (p *parser) typeStmt(t *rtype) (bool, error) { p.used[p.i+3] = true p.i += 4 return true, p.titlePatterns(t) - case c.kind == tConst && p.at(1).kind == tOp && p.at(1).text == "=": - return p.constAssign() + case c.kind == tConst && p.assigns(): + return true, p.strictConstAssign() + case c.kind == tIdent && (c.text == "private" || c.text == "protected" || c.text == "public") && (p.at(1).kind == tNL || p.at(1).text == ";"): + p.take() + t.private = c.text != "public" + return true, nil + case c.kind == tIdent && c.text == "include" && p.at(1).kind == tConst: + return true, p.include(t) + case c.kind == tIdent && c.text == "class" && p.at(1).text == "<<" && p.at(2).text == "self": + p.i += 3 + return true, p.body("end", p.singletonStmt) } - return false, nil + return true, fmt.Errorf("unsupported %s in type body", p.construct()) +} + +// singletonStmt allows only class-level accessors that do not shadow a Puppet::Type class method. +func (p *parser) singletonStmt() (bool, error) { + c := p.cur() + if c.kind != tIdent || c.text != "attr_reader" && c.text != "attr_writer" && c.text != "attr_accessor" { + return true, fmt.Errorf("unsupported %s in class << self", p.construct()) + } + p.take() + args, err := p.args() + if err != nil { + return true, err + } + for _, a := range args { + if a.k != vSym || typeClassMethods[a.s] { + return true, fmt.Errorf("%s %s shadows a Puppet::Type class method", c.text, a.s) + } + } + return true, nil +} + +func (p *parser) include(t *rtype) error { + p.take() + path := p.take().text + for p.op("::") && p.at(1).kind == tConst { + p.take() + path += "::" + p.take().text + } + if p.resolve == nil { + return fmt.Errorf("include %s: mixin source is not available", path) + } + srcs, err := p.resolve(path) + if err != nil { + return fmt.Errorf("include %s: %w", path, err) + } + for _, src := range srcs { + names, err := mixinMethods(src, path) + if err != nil { + return fmt.Errorf("include %s: %w", path, err) + } + for _, n := range names { + t.methods[n] = true + } + } + return nil +} + +// mixinMethods returns the public instance methods module path defines in src, failing on anything include could act on. +func mixinMethods(src, path string) (methods []string, err error) { + defer guard(&err) + toks, err := lex(src) + if err != nil { + return nil, err + } + p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}} + want := strings.Split(path, "::") + found, private := false, false + target := func() (bool, error) { + c := p.cur() + switch { + case c.kind == tIdent && c.text == "def" && p.at(1).kind == tIdent && p.at(1).text == "self" && p.at(2).text == ".": + if n := p.at(3).text; n == "included" || n == "append_features" { + return true, fmt.Errorf("def self.%s hook", n) + } + return true, p.skipStatement() + case c.kind == tIdent && c.text == "def": + if !private { + methods = append(methods, p.at(1).text) + } + return true, p.skipStatement() + case c.kind == tIdent && (c.text == "private" || c.text == "protected" || c.text == "public") && (p.at(1).kind == tNL || p.at(1).text == ";"): + p.take() + private = c.text != "public" + return true, nil + case c.kind == tConst && p.assigns(): + return true, p.strictConstAssign() + } + return true, fmt.Errorf("unsupported %s in mixin", p.construct()) + } + var scope func(prefix []string) func() (bool, error) + scope = func(prefix []string) func() (bool, error) { + return func() (bool, error) { + if !p.is(tIdent, "module") { + return false, nil + } + p.take() + name := slices.Clone(prefix) + for p.cur().kind == tConst || p.op("::") { + if t := p.take(); t.kind == tConst { + name = append(name, t.text) + } + } + switch { + case slices.Equal(name, want): + found = true + return true, p.body("end", target) + case len(name) < len(want) && slices.Equal(name, want[:len(name)]): + return true, p.body("end", scope(name)) + } + return true, p.body("end", func() (bool, error) { return false, nil }) + } + } + if err := p.body("", scope(nil)); err != nil { + return nil, p.wrap(err) + } + if !found { + return nil, fmt.Errorf("module is not defined in its source") + } + return methods, nil } func (t *rtype) addProp(a *attr) { @@ -572,7 +889,7 @@ func valueName(v rval) (string, *regex, error) { switch v.k { case vStr: if v.s == "" { - return "\x00", nil, nil + return "\xff", nil, nil } return v.s, nil, nil case vSym, vNum, vNil: @@ -611,15 +928,21 @@ func (a *attr) addValue(name string, re *regex) { } func (p *parser) attrStmt(a *attr) (bool, error) { + if ok, err := p.inert(nil, a); ok || err != nil { + return true, err + } + if p.cond > 0 { + return true, fmt.Errorf("unsupported conditional %s", p.construct()) + } if ok, err := p.docStmt(&a.doc); ok || err != nil { return ok, err } c := p.cur() - if c.kind == tConst && p.at(1).kind == tOp && p.at(1).text == "=" { - return p.constAssign() + if c.kind == tConst && p.assigns() { + return true, p.strictConstAssign() } if c.kind != tIdent || !watched[c.text] { - return false, nil + return true, fmt.Errorf("unsupported %s in attribute %s", p.construct(), a.name) } p.used[p.i] = true p.take() @@ -652,7 +975,7 @@ func (p *parser) attrStmt(a *attr) (bool, error) { a.addValue(name, re) } if p.is(tIdent, "do") || p.op("{") { - p.skipStatement() + return true, p.skipBlock() } return true, nil case "aliasvalue": @@ -768,6 +1091,9 @@ func (p *parser) args() ([]rval, error) { return nil, fmt.Errorf("splat of %s", v.kindName()) } out = append(out, v.arr...) + case p.op("&") && (p.at(1).kind == tSym || isLocal(p.at(1))): + p.i += 2 + out = append(out, rval{k: vBlock}) default: v, err := p.expr() if err != nil { @@ -812,6 +1138,10 @@ func (p *parser) args() ([]rval, error) { } func (p *parser) expr() (rval, error) { + defer func() { p.depth-- }() + if err := p.enter(); err != nil { + return rval{}, err + } v, err := p.primary() if err != nil { return v, err @@ -854,7 +1184,7 @@ func (p *parser) interp(parts []part) (string, error) { if err != nil { return "", fmt.Errorf("unsupported interpolation #{%s}", pt.text) } - sub := &parser{toks: toks, consts: p.consts, used: map[int]bool{}} + sub := &parser{toks: toks, consts: p.consts, used: map[int]bool{}, depth: p.depth} c, err := sub.expr() sub.skipNL() if err != nil || c.k != vStr || sub.cur().kind != tEOF { @@ -865,10 +1195,72 @@ func (p *parser) interp(parts []part) (string, error) { return b.String(), nil } +var ( + intRe = regexp.MustCompile(`^(?:0[xX]([0-9a-fA-F]+(?:_[0-9a-fA-F]+)*)|0[bB]([01]+(?:_[01]+)*)|0[oO]?_?([0-7]+(?:_[0-7]+)*)|0[dD]([0-9]+(?:_[0-9]+)*)|([1-9][0-9]*(?:_[0-9]+)*|0))$`) + floatRe = regexp.MustCompile(`^(?:[1-9][0-9]*(?:_[0-9]+)*|0)(?:\.[0-9]+(?:_[0-9]+)*)?(?:[eE][+-]?[0-9]+(?:_[0-9]+)*)?$`) +) + +// rubyNum renders a numeric literal as Ruby's Integer#to_s or Float#to_s would. +func rubyNum(neg bool, text string) (string, error) { + if m := intRe.FindStringSubmatch(text); m != nil { + for i, base := range []int{16, 2, 8, 10, 10} { + if m[i+1] != "" { + n, _ := new(big.Int).SetString(strings.ReplaceAll(m[i+1], "_", ""), base) + if neg { + n.Neg(n) + } + return n.String(), nil + } + } + } + if floatRe.MatchString(text) { + f, err := strconv.ParseFloat(strings.ReplaceAll(text, "_", ""), 64) + if err != nil || math.IsInf(f, 0) { + return "", fmt.Errorf("unsupported float literal %s", text) + } + if neg { + f = -f + } + return rubyFloat(f), nil + } + return "", fmt.Errorf("unsupported numeric literal %s", text) +} + +func rubyFloat(f float64) string { + mant, exp, _ := strings.Cut(strconv.FormatFloat(f, 'e', -1, 64), "e") + e, _ := strconv.Atoi(exp) + sign := "" + if strings.HasPrefix(mant, "-") { + sign, mant = "-", mant[1:] + } + digits := strings.Replace(mant, ".", "", 1) + if e < -4 || e >= 15 { + frac := digits[1:] + if frac == "" { + frac = "0" + } + return fmt.Sprintf("%s%s.%se%+03d", sign, digits[:1], frac, e) + } + if e < 0 { + return sign + "0." + strings.Repeat("0", -e-1) + digits + } + for len(digits) < e+1 { + digits += "0" + } + frac := digits[e+1:] + if frac == "" { + frac = "0" + } + return sign + digits[:e+1] + "." + frac +} + func (p *parser) primary() (rval, error) { t := p.cur() switch t.kind { case tStr: + if t.flags == "`" { + return rval{}, fmt.Errorf("unsupported command string") + } p.take() s, err := p.interp(t.parts) return rval{k: vStr, s: s}, err @@ -894,7 +1286,8 @@ func (p *parser) primary() (rval, error) { return v, nil case tNum: p.take() - return rval{k: vNum, s: t.text}, nil + s, err := rubyNum(false, t.text) + return rval{k: vNum, s: s}, err case tIdent: switch t.text { case "true": @@ -937,7 +1330,8 @@ func (p *parser) primary() (rval, error) { case "-": if p.at(1).kind == tNum && !p.at(1).space { p.take() - return rval{k: vNum, s: "-" + p.take().text}, nil + s, err := rubyNum(true, p.take().text) + return rval{k: vNum, s: s}, err } case "[": p.take() @@ -1046,6 +1440,16 @@ func resourceAPIType(def rval) (*rtype, error) { if !ok || attrs.k != vHash { return nil, fmt.Errorf("register_type: attributes must be a literal hash") } + for _, opts := range attrs.arr { + for j, k := range opts.keys { + if k.k == vSym && k.s == "behavior" { + if _, both := opts.get("behaviour"); both { + return nil, fmt.Errorf("register_type: attribute has both behavior and behaviour") + } + opts.keys[j].s = "behaviour" + } + } + } var namevars []string insyncable := false for _, opts := range attrs.arr { @@ -1070,7 +1474,11 @@ func resourceAPIType(def rval) (*rtype, error) { if !ok { return nil, fmt.Errorf("attribute %s: type must be a string", an) } - behaviour, hasB := str(opts.get("behaviour")) + bv, hasB := opts.get("behaviour") + if hasB && bv.k != vSym { + return nil, fmt.Errorf("attribute %s: behaviour must be a symbol", an) + } + behaviour := bv.s a := &attr{name: an, namevar: behaviour == "namevar"} if d, ok := str(opts.get("desc")); ok { a.doc = d + " (a " + typ + ")" diff --git a/internal/gentypes/render.go b/internal/gentypes/render.go index 9447ee2..499d50e 100644 --- a/internal/gentypes/render.go +++ b/internal/gentypes/render.go @@ -3,8 +3,10 @@ package gentypes import ( "fmt" "slices" + "strconv" "strings" "time" + "unicode/utf8" ) const rubySpace = " \t\r\n\f\v\x00" @@ -97,20 +99,21 @@ func doubleQuote(s string) string { return b.String() } -func escapeSlash(src string) 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 src[i] { - case '\\': - b.WriteByte('\\') - if i+1 < len(src) { - i++ - b.WriteByte(src[i]) - } - case '/': + 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(src[i]) + b.WriteByte(c) } } return b.String() @@ -127,28 +130,84 @@ func (r regex) opts() (on, off string) { 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 "/" + escapeSlash(r.src) + "/" + on + return "/" + exprStr(r.src) + "/" + on } -// puppet renders the %p form: inspect without options, else /(?on-off:src)/. +// 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 == "" { + if on == "" && !fixed { 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) + 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 + ":" + escapeSlash(r.src) + ")/", nil + return "/(?" + on + off + ":" + exprStr(r.src) + ")/", nil } func (a *attr) puppetType() (string, error) { @@ -186,9 +245,12 @@ func (a *attr) puppetType() (string, error) { return "Variant[" + strings.Join(parts, ", ") + "]", nil } -func (v *value) display() string { return strings.TrimPrefix(v.name, "\x00") } +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." @@ -220,10 +282,10 @@ func (a *attr) fullDoc() string { 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 { + for _, p := range slices.Sorted(slices.Values(providers)) { doc += p + "\n: \n\n" } - return &attr{name: "provider", doc: doc} + return &attr{name: "provider", doc: doc, raw: true} } func writeDoc(b *strings.Builder, doc, prefix string) { diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/chkconfig.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/chkconfig.rb index e69de29..b30e464 100644 --- a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/chkconfig.rb +++ b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/chkconfig.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:alternative_entry).provide(:chkconfig) do +end diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/dpkg.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/dpkg.rb index e69de29..be37305 100644 --- a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/dpkg.rb +++ b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternative_entry/dpkg.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:alternative_entry).provide(:dpkg) do +end diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/chkconfig.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/chkconfig.rb index e69de29..bad2956 100644 --- a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/chkconfig.rb +++ b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/chkconfig.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:alternatives).provide(:chkconfig) do +end diff --git a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/dpkg.rb b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/dpkg.rb index e69de29..49691c3 100644 --- a/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/dpkg.rb +++ b/internal/gentypes/testdata/env/external_modules/alternatives/lib/puppet/provider/alternatives/dpkg.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:alternatives).provide(:dpkg) do +end diff --git a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/curl.rb b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/curl.rb index e69de29..312d52c 100644 --- a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/curl.rb +++ b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/curl.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:archive).provide(:curl) do +end diff --git a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/ruby.rb b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/ruby.rb index e69de29..d30c599 100644 --- a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/ruby.rb +++ b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/ruby.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:archive).provide(:ruby) do +end diff --git a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/wget.rb b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/wget.rb index e69de29..64ca4e3 100644 --- a/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/wget.rb +++ b/internal/gentypes/testdata/env/external_modules/archive/lib/puppet/provider/archive/wget.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:archive).provide(:wget) do +end diff --git a/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewall/firewall.rb b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewall/firewall.rb index e69de29..a7e2f3a 100644 --- a/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewall/firewall.rb +++ b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewall/firewall.rb @@ -0,0 +1,2 @@ +class Puppet::Provider::Firewall::Firewall +end diff --git a/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewallchain/firewallchain.rb b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewallchain/firewallchain.rb index e69de29..3b3c638 100644 --- a/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewallchain/firewallchain.rb +++ b/internal/gentypes/testdata/env/external_modules/firewall/lib/puppet/provider/firewallchain/firewallchain.rb @@ -0,0 +1,2 @@ +class Puppet::Provider::Firewallchain::Firewallchain +end diff --git a/internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/provider/grafana_plugin/grafana_cli.rb b/internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/provider/grafana_plugin/grafana_cli.rb index e69de29..31654e1 100644 --- a/internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/provider/grafana_plugin/grafana_cli.rb +++ b/internal/gentypes/testdata/env/external_modules/grafana/lib/puppet/provider/grafana_plugin/grafana_cli.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:grafana_plugin).provide(:grafana_cli) do +end diff --git a/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb index e69de29..40e0c15 100644 --- a/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb +++ b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:ini_setting).provide(:ruby) do +end diff --git a/internal/gentypes/testdata/env/external_modules/minio/lib/puppet/provider/minio_client_alias/minio_client_alias.rb b/internal/gentypes/testdata/env/external_modules/minio/lib/puppet/provider/minio_client_alias/minio_client_alias.rb index e69de29..a0435e6 100644 --- a/internal/gentypes/testdata/env/external_modules/minio/lib/puppet/provider/minio_client_alias/minio_client_alias.rb +++ b/internal/gentypes/testdata/env/external_modules/minio/lib/puppet/provider/minio_client_alias/minio_client_alias.rb @@ -0,0 +1,4 @@ +require 'puppet/resource_api/simple_provider' + +class Puppet::Provider::MinioClientAlias::MinioClientAlias < Puppet::ResourceApi::SimpleProvider +end diff --git a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/inifile.rb b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/inifile.rb index e69de29..a2366f4 100644 --- a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/inifile.rb +++ b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/inifile.rb @@ -0,0 +1,2 @@ +class Puppet::Provider::MysqlLoginPath::IniFile < Puppet::Provider +end diff --git a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/mysql_login_path.rb b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/mysql_login_path.rb index e69de29..48cac2c 100644 --- a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/mysql_login_path.rb +++ b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/mysql_login_path.rb @@ -0,0 +1,4 @@ +require 'puppet/resource_api/simple_provider' + +class Puppet::Provider::MysqlLoginPath::MysqlLoginPath < Puppet::ResourceApi::SimpleProvider +end diff --git a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/sensitive.rb b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/sensitive.rb index e69de29..05e05be 100644 --- a/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/sensitive.rb +++ b/internal/gentypes/testdata/env/external_modules/mysql/lib/puppet/provider/mysql_login_path/sensitive.rb @@ -0,0 +1,2 @@ +class Puppet::Provider::MysqlLoginPath::Sensitive < Puppet::Pops::Types::PSensitiveType::Sensitive +end diff --git a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/interfaces.rb b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/interfaces.rb index e69de29..e738cff 100644 --- a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/interfaces.rb +++ b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/interfaces.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:network_config).provide(:interfaces) do +end diff --git a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/redhat.rb b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/redhat.rb index e69de29..3f9ba2c 100644 --- a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/redhat.rb +++ b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/redhat.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:network_config).provide(:redhat) do +end diff --git a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/sles.rb b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/sles.rb index e69de29..8717cef 100644 --- a/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/sles.rb +++ b/internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/sles.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:network_config).provide(:sles) do +end diff --git a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/linux.rb b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/linux.rb index e69de29..5f9b8ec 100644 --- a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/linux.rb +++ b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/linux.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:reboot).provide(:linux) do +end diff --git a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/posix.rb b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/posix.rb index e69de29..524ab90 100644 --- a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/posix.rb +++ b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/posix.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:reboot).provide(:posix) do +end diff --git a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/windows.rb b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/windows.rb index e69de29..3e9e3f0 100644 --- a/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/windows.rb +++ b/internal/gentypes/testdata/env/external_modules/reboot/lib/puppet/provider/reboot/windows.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:reboot).provide(:windows) do +end diff --git a/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/provider/file_line/ruby.rb b/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/provider/file_line/ruby.rb index e69de29..56d6c06 100644 --- a/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/provider/file_line/ruby.rb +++ b/internal/gentypes/testdata/env/external_modules/stdlib/lib/puppet/provider/file_line/ruby.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:file_line).provide(:ruby) do +end diff --git a/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb b/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb index e69de29..e293313 100644 --- a/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb +++ b/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:yumrepo).provide(:inifile) do +end diff --git a/internal/gentypes/testdata/env/modules/probe/lib/puppet/provider/private_ensure/p.rb b/internal/gentypes/testdata/env/modules/probe/lib/puppet/provider/private_ensure/p.rb new file mode 100644 index 0000000..fe615ed --- /dev/null +++ b/internal/gentypes/testdata/env/modules/probe/lib/puppet/provider/private_ensure/p.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:private_ensure).provide(:p) do +end diff --git a/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/implicit_ensure.rb b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/implicit_ensure.rb new file mode 100644 index 0000000..93de365 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/implicit_ensure.rb @@ -0,0 +1,10 @@ +Puppet::Type.newtype(:implicit_ensure) do + @doc = 'implicit' + newproperty(:a) + newparam(:name, namevar: true) + def exists?; end + def create + true + end + def destroy; end +end diff --git a/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/inert.rb b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/inert.rb new file mode 100644 index 0000000..fb2e026 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/inert.rb @@ -0,0 +1,61 @@ +require_relative '../../puppet_x/probe/inert' +Puppet::Type.newtype(:inert) do + desc 'everything inert' + Puppet.warning('loading inert') + Puppet.debug 'x' + include PuppetX::Probe::Inert + feature :f1, 'Feature doc', methods: [:m1] + feature :f2, + "multi + line" + @state = false + @hdr = <<~EOS + header + EOS + helper = proc do |v| + v + end + other = lambda { |v| v } + LIST = %w[a b].freeze + class << self + attr_accessor :state + end + validate do + raise 'x' unless self[:name] + end + autorequire(:file) { ['/a'] } + autobefore(:file) do + [] + end + autonotify(:service) { [] } + autosubscribe(:package) { [] } + newparam(:name, namevar: true) do + desc 'n' + possible = [:a, :b] + rx = %r{^x$} + validate do |v| + raise ArgumentError unless possible.include?(v) + end + munge(&helper) + unmunge { |v| v } + isrequired + attr_accessor :latest + def insync?(is) + is == should + end + if defined? IPAddr + validate do |v| + IPAddr.new(v) + end + end + end + newproperty(:p) do + sensitive true + defaultto :x + newvalues(:x, :y) + defaultto { :y } + end + def refresh; end + private + def exists?; end +end diff --git a/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/literals.rb b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/literals.rb new file mode 100644 index 0000000..0546785 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/literals.rb @@ -0,0 +1,25 @@ +Puppet::Type.newtype(:literals) do + @doc = "Type doc with escapes: \101\x42\u0043 \u{44 45} tab\there \e end" + newparam(:name, namevar: true) + newparam(:ints) do + desc 'Single \n quoted \\ and \' only' + newvalues(0x1f, 0X1F, 1_000, 0o17, 0O17, 017, 0_17, 0b101, 0B11, 0d12, 0D19, -0x10, 0, 00, -0, 12345678901234567890) + end + newparam(:floats) do + newvalues(1e3, 1E3, 1.5, 1.5e-5, 1e15, 1e14, 999999999999999.0, 0.0001, 0.00001, 1_0.5, 1e+3, 100.0, -0.0, -2.5, 123456789.123456789, 5e-324) + end + newparam(:dq) do + desc "Double \"quoted\"\s\a\b doc" + newvalues("\101", "\x41", "\x4", "\u00e9", "\u{41 42 43}", "\e", "\cA", "\C-b", "\c?", "\1", "\18", "\12", "\1234", "\q", "\8", "a\ +b", "\#{x}", "\0", "tab\t", "nl\n", "\s", "\$x") + end + newparam(:sq) do + newvalues('a\nb', 'a\\b', 'a\'b', %q(a\)b\(c), %q{x\}y}, :"x\101", :'y\101', %s(z\101)) + end + newparam(:re) do + newvalues(/é/, /\u00e9/, /\u{e9}/, /[\u{41}]/, /\u0041/, /\p{L}/, /\P{Alpha}/, /\x41/, /a b/x, /(?i)x/, /\//m, /a\/b/, %r{a/b}, %r{a\/b}, %r!a\!b!, %r|a\|b|, %r{a\}b}, %r(a\)b), %r,a\,b,, /\h\R\X/, /[[:alpha:]]/, /é/i, /a#b/, /\\/, /\e/, /x/o) + end + newparam(:re2) do + newvalues(/a b/, /c/) + end +end diff --git a/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/mixin_ensure.rb b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/mixin_ensure.rb new file mode 100644 index 0000000..9e8aebd --- /dev/null +++ b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/mixin_ensure.rb @@ -0,0 +1,5 @@ +require_relative '../../puppet_x/probe/trio' +Puppet::Type.newtype(:mixin_ensure) do + newparam(:name, namevar: true) + include PuppetX::Probe::Trio +end diff --git a/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/private_ensure.rb b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/private_ensure.rb new file mode 100644 index 0000000..8e77510 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/private_ensure.rb @@ -0,0 +1,7 @@ +Puppet::Type.newtype(:private_ensure) do + newparam(:name, namevar: true) + def exists?; end + def create; end + private + def destroy; end +end diff --git a/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/rsapi_behavior.rb b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/rsapi_behavior.rb new file mode 100644 index 0000000..74d5c34 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/probe/lib/puppet/type/rsapi_behavior.rb @@ -0,0 +1,11 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'rsapi_behavior', + docs: 'rsapi', + attributes: { + name: { type: 'String', desc: 'n', behavior: :namevar }, + ro: { type: 'String', desc: 'r', behavior: :read_only }, + p: { type: 'Boolean', desc: 'p', behavior: :parameter }, + ensure: { type: 'Enum[present, absent]', desc: 'e' }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/probe/lib/puppet_x/probe/inert.rb b/internal/gentypes/testdata/env/modules/probe/lib/puppet_x/probe/inert.rb new file mode 100644 index 0000000..a662d91 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/probe/lib/puppet_x/probe/inert.rb @@ -0,0 +1,13 @@ +module PuppetX + module Probe + module Inert + def self.try + yield + end + + private + + def create; end + end + end +end diff --git a/internal/gentypes/testdata/env/modules/probe/lib/puppet_x/probe/trio.rb b/internal/gentypes/testdata/env/modules/probe/lib/puppet_x/probe/trio.rb new file mode 100644 index 0000000..fd52255 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/probe/lib/puppet_x/probe/trio.rb @@ -0,0 +1,11 @@ +module PuppetX + module Probe + module Trio + MAX = 3 + def self.helper; end + def exists?; end + def create; end + def destroy; end + end + end +end diff --git a/internal/gentypes/testdata/golden/alternative_entry.pp b/internal/gentypes/testdata/golden/alternative_entry.pp index 0cc560b..bc2f793 100644 --- a/internal/gentypes/testdata/golden/alternative_entry.pp +++ b/internal/gentypes/testdata/golden/alternative_entry.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:23 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. Puppet::Resource::ResourceType3.new( @@ -30,12 +30,10 @@ Puppet::Resource::ResourceType3.new( # discover the appropriate provider for your platform.Available providers are: # # chkconfig - # : * Required binaries: `/usr/sbin/alternatives`. - # * Default for `os.family` == `redhat`. + # : # # dpkg - # : * Required binaries: `update-alternatives`. - # * Default for `{"os.name"=>[:debian, :ubuntu], "os.family"=>:suse}` == ``. + # : Puppet::Resource::Param(Any, 'provider') ], { diff --git a/internal/gentypes/testdata/golden/alternatives.pp b/internal/gentypes/testdata/golden/alternatives.pp index 3fa748d..61dbf63 100644 --- a/internal/gentypes/testdata/golden/alternatives.pp +++ b/internal/gentypes/testdata/golden/alternatives.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:23 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. Puppet::Resource::ResourceType3.new( @@ -23,14 +23,10 @@ Puppet::Resource::ResourceType3.new( # discover the appropriate provider for your platform.Available providers are: # # chkconfig - # : * Required binaries: `alternatives`. - # * Default for `os.family` == `redhat`. - # * Supported features: `mode`. + # : # # dpkg - # : * Required binaries: `update-alternatives`. - # * Default for `{"os.name"=>[:debian, :ubuntu], "os.family"=>:suse}` == ``. - # * Supported features: `mode`. + # : Puppet::Resource::Param(Any, 'provider') ], { diff --git a/internal/gentypes/testdata/golden/anchor.pp b/internal/gentypes/testdata/golden/anchor.pp index 1c78094..8a07357 100644 --- a/internal/gentypes/testdata/golden/anchor.pp +++ b/internal/gentypes/testdata/golden/anchor.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # @summary diff --git a/internal/gentypes/testdata/golden/archive.pp b/internal/gentypes/testdata/golden/archive.pp index 67771af..dd9ca3b 100644 --- a/internal/gentypes/testdata/golden/archive.pp +++ b/internal/gentypes/testdata/golden/archive.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:23 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # Manage archive file download, extraction, and cleanup. @@ -125,15 +125,13 @@ Puppet::Resource::ResourceType3.new( # discover the appropriate provider for your platform.Available providers are: # # curl - # : * Required binaries: `curl`. - # * Default for `feature` == `posix`. + # : # # ruby - # : * Required binaries: `aws`, `gsutil`. - # * Default for `feature` == `microsoft_windows`. + # : # # wget - # : * Required binaries: `wget`. + # : Puppet::Resource::Param(Any, 'provider') ], { diff --git a/internal/gentypes/testdata/golden/concat_file.pp b/internal/gentypes/testdata/golden/concat_file.pp index 6c5709e..d0fefab 100644 --- a/internal/gentypes/testdata/golden/concat_file.pp +++ b/internal/gentypes/testdata/golden/concat_file.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # @summary diff --git a/internal/gentypes/testdata/golden/file_line.pp b/internal/gentypes/testdata/golden/file_line.pp index 1843f83..1efd2a1 100644 --- a/internal/gentypes/testdata/golden/file_line.pp +++ b/internal/gentypes/testdata/golden/file_line.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # @summary @@ -162,13 +162,7 @@ Puppet::Resource::ResourceType3.new( # discover the appropriate provider for your platform.Available providers are: # # ruby - # : @summary - # This type allows puppet to manage small config files. - # - # The implementation matches the full line, including whitespace at the - # beginning and end. If the line is not contained in the given file, Puppet - # will append the line to the end of the file to ensure the desired state. - # Multiple resources may be declared to manage multiple lines in the same file. + # : Puppet::Resource::Param(Any, 'provider') ], { diff --git a/internal/gentypes/testdata/golden/firewall.pp b/internal/gentypes/testdata/golden/firewall.pp index 596ddfe..3fd7713 100644 --- a/internal/gentypes/testdata/golden/firewall.pp +++ b/internal/gentypes/testdata/golden/firewall.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # This type provides the capability to manage firewall rules within puppet via iptables. diff --git a/internal/gentypes/testdata/golden/firewallchain.pp b/internal/gentypes/testdata/golden/firewallchain.pp index c6a9a23..9af3af1 100644 --- a/internal/gentypes/testdata/golden/firewallchain.pp +++ b/internal/gentypes/testdata/golden/firewallchain.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # This type provides the capability to manage rule chains for firewalls. diff --git a/internal/gentypes/testdata/golden/grafana_plugin.pp b/internal/gentypes/testdata/golden/grafana_plugin.pp index 6875f84..4b0ab8f 100644 --- a/internal/gentypes/testdata/golden/grafana_plugin.pp +++ b/internal/gentypes/testdata/golden/grafana_plugin.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # manages grafana plugins @@ -48,8 +48,7 @@ Puppet::Resource::ResourceType3.new( # discover the appropriate provider for your platform.Available providers are: # # grafana_cli - # : * Required binaries: `grafana-cli`. - # * Default for `feature` == `posix`. + # : Puppet::Resource::Param(Any, 'provider') ], { diff --git a/internal/gentypes/testdata/golden/implicit_ensure.pp b/internal/gentypes/testdata/golden/implicit_ensure.pp new file mode 100644 index 0000000..23b5a6e --- /dev/null +++ b/internal/gentypes/testdata/golden/implicit_ensure.pp @@ -0,0 +1,22 @@ +# This file was automatically generated on 2026-11-08 18:46:53 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# implicit +Puppet::Resource::ResourceType3.new( + 'implicit_ensure', + [ + # The basic property that the resource should be in. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + Puppet::Resource::Param(Any, 'a') + ], + [ + Puppet::Resource::Param(Any, 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/inert.pp b/internal/gentypes/testdata/golden/inert.pp new file mode 100644 index 0000000..93686e1 --- /dev/null +++ b/internal/gentypes/testdata/golden/inert.pp @@ -0,0 +1,19 @@ +# This file was automatically generated on 2026-11-08 18:46:53 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# everything inert +Puppet::Resource::ResourceType3.new( + 'inert', + [ + # Valid values are `x`, `y`. + Puppet::Resource::Param(Enum['x', 'y'], 'p') + ], + [ + # n + Puppet::Resource::Param(Any, 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/ini_setting.pp b/internal/gentypes/testdata/golden/ini_setting.pp index fbfaad3..0ea9a57 100644 --- a/internal/gentypes/testdata/golden/ini_setting.pp +++ b/internal/gentypes/testdata/golden/ini_setting.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # ini_settings is used to manage a single setting in an INI file diff --git a/internal/gentypes/testdata/golden/literals.pp b/internal/gentypes/testdata/golden/literals.pp new file mode 100644 index 0000000000000000000000000000000000000000..e04984234d86679436ac1cb46ffd2cdd178b3fdf GIT binary patch literal 2367 zcma)8+iu%N5N(PAY4i(unOFfRHsVbeR}#<$a+0?^7;#b*&8=qe%nBR3pIWev)&!mPu=zZrWg_GEr6=@^zu?Hbnw7 z;UY>uBUd7Y>tadF2%x?!WGLPkAEW+~aWsd2WLzjD7AwE(2AAzhB5^*Ag8svj&0U`B zupE+ff>Tl)xfemF+v}hHJ{bCYbm?*#|JCBVv`8jaH^2rhDus2QB#SPOJ1mDJabZ&0 z?}6p4Db7Y|o>_aY?h`;Oxw`E=ay0{PUpc;kzItVNLAQfP#}1DlZN$93&-@0iUuW`7 za-6Hz)xa?Zr(;~Ird-1z^WCRh-A?aOZ0hcqGnZKmbWhsCJuy6Ji0dNbaZ5v&iPk+; z;mD2-H_53bGEgV1u@iQ<*9lpxPI#lP;-x&=s<+ExhR6CuAL*13DL6e%`MUUh)37(QOg3WEYBmENzy8NWm_#h6*^0Iu? z){K#Y6H#n?yA$N%?v@zA7mKk5XJn@NpaLCs{8~Be2JDbh^hJ-NuSpC@$Qenh7d0jE zISJM*a*9f0!Er!tFH7El`SlO)i4-Z5Aca>1dQne)snM=R zc7@soh=uqd{?_>>laZu?MpIKbwi)R)o0YpT)hMm8xF7Gwxy zwV@hm{*EogB3o(_(VrZVo`Xo@@hGrjlZ}GNWbYD}9U-H}m-u9R;$StxV>1(p)> ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/mysql_login_path.pp b/internal/gentypes/testdata/golden/mysql_login_path.pp index fd5ca0b..fa93bd0 100644 --- a/internal/gentypes/testdata/golden/mysql_login_path.pp +++ b/internal/gentypes/testdata/golden/mysql_login_path.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:24 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # @summary Manage a MySQL login path. diff --git a/internal/gentypes/testdata/golden/network_config.pp b/internal/gentypes/testdata/golden/network_config.pp index 81047f5..af343ae 100644 --- a/internal/gentypes/testdata/golden/network_config.pp +++ b/internal/gentypes/testdata/golden/network_config.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # Manage non-volatile network configuration information @@ -74,22 +74,13 @@ Puppet::Resource::ResourceType3.new( # discover the appropriate provider for your platform.Available providers are: # # interfaces - # : Debian interfaces style provider - # - # * Default for `osfamily` == `debian`. - # * Supported features: `hotpluggable`, `provider_options`. + # : # # redhat - # : Redhat network-scripts provider - # - # * Default for `osfamily` == `redhat`. - # * Supported features: `hotpluggable`, `provider_options`. + # : # # sles - # : SLES network-scripts provider - # - # * Default for `osfamily` == `suse`. - # * Supported features: `provider_options`, `startmode`. + # : Puppet::Resource::Param(Any, 'provider') ], { diff --git a/internal/gentypes/testdata/golden/private_ensure.pp b/internal/gentypes/testdata/golden/private_ensure.pp new file mode 100644 index 0000000..0b39e80 --- /dev/null +++ b/internal/gentypes/testdata/golden/private_ensure.pp @@ -0,0 +1,24 @@ +# This file was automatically generated on 2026-11-08 18:46:53 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'private_ensure', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true), + + # The specific backend to use for this `private_ensure` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # p + # : + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/reboot.pp b/internal/gentypes/testdata/golden/reboot.pp index 4e41f60..c14c7a0 100644 --- a/internal/gentypes/testdata/golden/reboot.pp +++ b/internal/gentypes/testdata/golden/reboot.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # Manages system reboots. The `reboot` type is typically @@ -119,18 +119,10 @@ Puppet::Resource::ResourceType3.new( # : # # posix - # : POSIX provider for the reboot type. - # - # This provider handles rebooting for POSIX systems. It does not support - # HP-UX. - # - # * Required binaries: `shutdown`. - # * Default for `feature` == `posix`. + # : # # windows - # : * Required binaries: `shutdown.exe`. - # * Default for `os.name` == `windows`. - # * Supported features: `manages_reboot_pending`. + # : Puppet::Resource::Param(Any, 'provider') ], { diff --git a/internal/gentypes/testdata/golden/rsapi_behavior.pp b/internal/gentypes/testdata/golden/rsapi_behavior.pp new file mode 100644 index 0000000..b055181 --- /dev/null +++ b/internal/gentypes/testdata/golden/rsapi_behavior.pp @@ -0,0 +1,33 @@ +# This file was automatically generated on 2026-11-08 18:46:53 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# rsapi +Puppet::Resource::ResourceType3.new( + 'rsapi_behavior', + [ + # e (a Enum[present, absent]) + # + # Valid values are `absent`, `present`. + Puppet::Resource::Param(Enum['absent', 'present'], 'ensure') + ], + [ + # n (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'name', true), + + # r (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'ro'), + + # p (a Boolean) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'p') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/yumrepo.pp b/internal/gentypes/testdata/golden/yumrepo.pp index 301a502..a677551 100644 --- a/internal/gentypes/testdata/golden/yumrepo.pp +++ b/internal/gentypes/testdata/golden/yumrepo.pp @@ -1,4 +1,4 @@ -# This file was automatically generated on 2026-11-08 17:31:25 +1100. +# This file was automatically generated on 2026-11-08 18:46:53 +1100. # Use the 'puppet generate types' command to regenerate this file. # @summary The client-side description of a yum repository. @@ -322,23 +322,7 @@ Puppet::Resource::ResourceType3.new( # discover the appropriate provider for your platform.Available providers are: # # inifile - # : Manage yum repo configurations by parsing yum INI configuration files. - # - # ### Fetching instances - # - # When fetching repo instances, directory entries in '/etc/yum/repos.d', - # '/etc/yum.repos.d', and the directory optionally specified by the reposdir - # key in '/etc/yum.conf' will be checked. If a given directory does not exist it - # will be ignored. In addition, all sections in '/etc/yum.conf' aside from - # 'main' will be created as sections. - # - # ### Storing instances - # - # When creating a new repository, a new section will be added in the first - # yum repo directory that exists. The custom directory specified by the - # '/etc/yum.conf' reposdir property is checked first, followed by - # '/etc/yum/repos.d', and then '/etc/yum.repos.d'. If none of these exist, the - # section will be created in '/etc/yum.conf'. + # : Puppet::Resource::Param(Any, 'provider') ], { From 0edce80e2ceee352a632280f2d6ccaad431cd8b7 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 18:50:46 +1100 Subject: [PATCH 5/8] Key typed worktrees on generate_types and the generator version --- internal/deploy/deploy.go | 13 +++++++++++-- internal/deploy/deploy_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 472a577..49696de 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -262,10 +262,19 @@ func (d *Deployer) owned(s *Source, link string) string { return "" } +// worktreePrefix keys worktrees on everything besides modules that changes their content. +func (d *Deployer) worktreePrefix(sha string) string { + if d.cfg.W10k.GenerateTypes { + return sha + "-types" + gentypes.Version + "-" + } + return sha + "-" +} + func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, modules bool) error { link := filepath.Join(s.Basedir, name) cur := d.owned(s, link) - if cur != "" && !modules && strings.HasPrefix(filepath.Base(cur), sha+"-") && d.complete(cur) { + prefix := d.worktreePrefix(sha) + if base := filepath.Base(cur); cur != "" && !modules && strings.HasPrefix(base, prefix) && len(base) == len(prefix)+12 && d.complete(cur) { return nil } pf, checksum, err := d.puppetfile(ctx, d.srcMirror(s), sha) @@ -280,7 +289,7 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m for _, m := range mods { _, _ = fmt.Fprintf(h, "%s %s\n", m.path, m.key) } - target := filepath.Join(d.srcWorktrees(s), sha+"-"+hex.EncodeToString(h.Sum(nil))[:12]) + target := filepath.Join(d.srcWorktrees(s), prefix+hex.EncodeToString(h.Sum(nil))[:12]) if cur == target && d.complete(cur) { return nil } diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 8c9efc7..5666b6b 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -639,6 +639,34 @@ func TestGenerateTypesBeforeSwap(t *testing.T) { } } +func TestGenerateTypesToggleRedeploys(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{ + "environment.conf": "modulepath = site:$basemodulepath\n", + "site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name)\nend\n", + }) + f.mustDeploy(false) + plain := f.env("main") + if exists(filepath.Join(plain, ".resource_types")) { + t.Fatal("types generated while generate_types is off") + } + f.cfg.W10k.GenerateTypes = true + f.mustDeploy(false) + typed := f.env("main") + if typed == plain || !exists(filepath.Join(typed, ".resource_types", "local.pp")) { + t.Fatalf("enabling generate_types must deploy a new worktree with types: %s", typed) + } + f.mustDeploy(false) + if f.env("main") != typed { + t.Fatal("an unchanged typed env must not be redeployed") + } + f.cfg.W10k.GenerateTypes = false + f.mustDeploy(false) + if f.env("main") != plain { + t.Fatalf("disabling generate_types must return to the untyped worktree, got %s", f.env("main")) + } +} + func readFileT(t *testing.T, p string) string { t.Helper() b, err := os.ReadFile(p) From 71425b58c8d481483a1b2815d868dfcfa9a5d6f9 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 18:54:44 +1100 Subject: [PATCH 6/8] Cap tokens per Ruby file --- internal/gentypes/generate_test.go | 4 ++-- internal/gentypes/lexer.go | 8 +++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/internal/gentypes/generate_test.go b/internal/gentypes/generate_test.go index 1f3ee2d..f74934e 100644 --- a/internal/gentypes/generate_test.go +++ b/internal/gentypes/generate_test.go @@ -464,7 +464,7 @@ func TestStepBudget(t *testing.T) { func TestDeepNestingIsAnError(t *testing.T) { if os.Getenv("GENTYPES_DEEP_CHILD") == "1" { _, err := parseFile("Puppet::Type.newtype(:t) do\n newparam(:a) do\n newvalues("+strings.Repeat("[", 4<<20)+"\n", nil) - if err == nil || !strings.Contains(err.Error(), "nesting deeper than") { + if err == nil || !strings.Contains(err.Error(), "more than 262144 tokens") { os.Exit(3) } return @@ -482,7 +482,7 @@ func TestDeepNestingIsAnError(t *testing.T) { cmd := exec.Command(os.Args[0], "-test.run=^TestDeepNestingIsAnError$") cmd.Env = append(os.Environ(), "GENTYPES_DEEP_CHILD=1") if out, err := cmd.CombinedOutput(); err != nil { - t.Fatalf("4MiB of '[' must be a parse error: %v\n%.300s", err, out) + t.Fatalf("4MiB of '[' must hit the token cap: %v\n%.300s", err, out) } } diff --git a/internal/gentypes/lexer.go b/internal/gentypes/lexer.go index 2fcb026..311b373 100644 --- a/internal/gentypes/lexer.go +++ b/internal/gentypes/lexer.go @@ -7,7 +7,10 @@ import ( "unicode/utf8" ) -const maxDepth = 256 +const ( + maxDepth = 256 + maxTokens = 1 << 18 +) type kind int @@ -173,6 +176,9 @@ func (l *lexer) run() error { continue } start := len(l.toks) + if start > maxTokens { + return fmt.Errorf("more than %d tokens", maxTokens) + } if err := l.next(space); err != nil { return err } From d570c98fea48632cb58cce5fb9e2def6290b2905 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 19:01:34 +1100 Subject: [PATCH 7/8] Skip unparseable types instead of failing the environment Parse failures are logged per file and counted per env; I/O, confinement and parser-limit errors still fail the deploy. --- internal/deploy/deploy.go | 45 ++++++++++++++++++------- internal/deploy/deploy_test.go | 22 +++++++++++-- internal/gentypes/generate.go | 53 +++++++++++++++++++++--------- internal/gentypes/generate_test.go | 40 ++++++++++++++-------- internal/gentypes/lexer.go | 4 +-- internal/gentypes/parse.go | 7 ++-- 6 files changed, 125 insertions(+), 46 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 49696de..8cc92fa 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -8,10 +8,13 @@ import ( "errors" "fmt" "log" + "maps" "os" "path/filepath" "regexp" + "slices" "sort" + "strconv" "strings" "sync" "syscall" @@ -41,6 +44,7 @@ type Deployer struct { sem chan struct{} mu sync.Mutex flights map[string]*flight + skips map[string]int } type flight struct { @@ -75,7 +79,7 @@ func New(cfg *Config, jobs int, grace time.Duration) *Deployer { if cfg.W10k.GitTimeout != nil { gt = *cfg.W10k.GitTimeout } - return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}} + return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}, skips: map[string]int{}} } func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { @@ -160,6 +164,9 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro for _, e := range only { want[e] = true } + d.mu.Lock() + clear(d.skips) + d.mu.Unlock() var errs []error for _, s := range d.Sources() { if err := d.deploySource(ctx, s, want, modules); err != nil { @@ -172,6 +179,11 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro if err := d.GC(ctx); err != nil { errs = append(errs, err) } + d.mu.Lock() + for _, e := range slices.Sorted(maps.Keys(d.skips)) { + log.Printf("environment %s: %d types skipped", e, d.skips[e]) + } + d.mu.Unlock() return errors.Join(errs...) } @@ -293,7 +305,7 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m if cur == target && d.complete(cur) { return nil } - if _, err := d.once("env:"+target, func() (string, error) { + skipped, err := d.once("env:"+target, func() (string, error) { if d.complete(target) { return "", nil } @@ -301,13 +313,19 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m if err := d.checkout(ctx, s, sha, target, mods); err != nil { return "", err } - return "", d.prepare(s, name, sha, checksum, target, mods, started) - }); err != nil { + return d.prepare(s, name, sha, checksum, target, mods, started) + }) + if err != nil { return err } if err := Swap(target, link); err != nil { return err } + if n, _ := strconv.Atoi(skipped); n > 0 { + d.mu.Lock() + d.skips[name] = n + d.mu.Unlock() + } log.Printf("environment %s -> %s", name, filepath.Base(target)) return nil } @@ -463,10 +481,15 @@ func linkModule(root *os.Root, rel, dir string) error { } // prepare runs last before a worktree can be swapped in; its out-of-tree done file marks the worktree complete. -func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods []resolved, started time.Time) error { +func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods []resolved, started time.Time) (string, error) { + var skipped []error if d.cfg.W10k.GenerateTypes { - if err := gentypes.Generate(target, d.path("modules"), d.path("forge")); err != nil { - return fmt.Errorf("generate types: %w", err) + var err error + if skipped, err = gentypes.Generate(target, d.path("modules"), d.path("forge")); err != nil { + return "", fmt.Errorf("generate types: %w", err) + } + for _, e := range skipped { + log.Printf("error: environment %s: generate types: skipped %v", name, e) } } r := deployResult{ @@ -485,17 +508,17 @@ func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods [ } b, err := json.MarshalIndent(r, "", " ") if err != nil { - return err + return "", err } b = append(b, '\n') if err := writeMarker(target, b); err != nil { - return err + return "", err } done := d.doneFile(target) if err := os.MkdirAll(filepath.Dir(done), 0o755); err != nil { - return err + return "", err } - return writeAtomic(done, b) + return strconv.Itoa(len(skipped)), writeAtomic(done, b) } // writeMarker replaces whatever the branch committed at the marker paths without following it. diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 5666b6b..248f841 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -1,9 +1,11 @@ package deploy import ( + "bytes" "context" "encoding/json" "fmt" + "log" "net" "net/http" "net/http/httptest" @@ -618,8 +620,24 @@ func TestGenerateTypesBeforeSwap(t *testing.T) { } commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(dynamic)\nend\n"}) - if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "generate types") || !strings.Contains(err.Error(), "site/local/lib/puppet/type/local.rb") { - t.Fatalf("broken type must fail the deploy naming the file: %v", err) + var logs bytes.Buffer + log.SetOutput(&logs) + defer log.SetOutput(os.Stderr) + f.mustDeploy(false) + skipped := f.env("main") + if skipped == live || !exists(filepath.Join(skipped, ".resource_types", "typed.pp")) || exists(filepath.Join(skipped, ".resource_types", "local.pp")) { + t.Fatal("an unparseable type is skipped while the env still deploys its other types") + } + for _, want := range []string{"environment main: generate types: skipped site/local/lib/puppet/type/local.rb: line 2:", "environment main: 1 types skipped"} { + if !strings.Contains(logs.String(), want) { + t.Fatalf("log lacks %q:\n%s", want, logs.String()) + } + } + live = skipped + + commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name)\nend\n" + strings.Repeat("module A\n", 300) + strings.Repeat("end\n", 300)}) + if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "deeper than") || !strings.Contains(err.Error(), "site/local/lib/puppet/type/local.rb") { + t.Fatalf("a parser limit must fail the deploy naming the file: %v", err) } if f.env("main") != live { t.Fatal("failed generation must leave the live env untouched") diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index 5366271..e0e8b4b 100644 --- a/internal/gentypes/generate.go +++ b/internal/gentypes/generate.go @@ -22,13 +22,29 @@ const Version = "2" var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) +var errConfine = errors.New("resolves outside the environment and module cache") + +// skipErr marks an input skipped the way `puppet generate types` skips a type that fails to load. +type skipErr struct{ error } + +func (u skipErr) Unwrap() error { return u.error } + +func unparsed(err error) error { + var pe *fs.PathError + if errors.Is(err, errLimit) || errors.Is(err, errConfine) || errors.As(err, &pe) { + return err + } + return skipErr{err} +} + type gen struct { env string roots []string } // Generate writes /.resource_types; every file it reads must resolve inside env or one of roots. -func Generate(env string, roots ...string) error { +// Inputs that fail to parse are returned as skipped and keep any previous output. +func Generate(env string, roots ...string) (skipped []error, err error) { g := &gen{} for i, r := range append([]string{env}, roots...) { real, err := filepath.EvalSymlinks(r) @@ -36,31 +52,31 @@ func Generate(env string, roots ...string) error { continue } if err != nil { - return err + return nil, err } g.roots = append(g.roots, real) } g.env = g.roots[0] mods, err := g.modules() if err != nil { - return err + return nil, err } var inputs []string providers := map[string][]string{} for _, m := range mods { files, err := g.glob(filepath.Join(m, "lib", "puppet", "type")) if err != nil { - return err + return nil, err } inputs = append(inputs, files...) dirs, err := g.list(filepath.Join(m, "lib", "puppet", "provider")) if err != nil { - return err + return nil, err } for _, d := range dirs { files, err := g.glob(d) if err != nil { - return err + return nil, err } for _, f := range files { typ, name := filepath.Base(d), strings.TrimSuffix(filepath.Base(f), ".rb") @@ -73,7 +89,7 @@ func Generate(env string, roots ...string) error { sort.Strings(inputs) out, err := openOut(g.env) if err != nil { - return err + return nil, err } defer func() { _ = out.Close() }() keep := map[string]bool{} @@ -82,27 +98,32 @@ func Generate(env string, roots ...string) error { } dir, err := out.Open(".") if err != nil { - return err + return nil, err } entries, err := dir.ReadDir(-1) _ = dir.Close() if err != nil { - return err + return nil, err } for _, e := range entries { if !keep[e.Name()] && (e.Type().IsRegular() || e.Type()&fs.ModeSymlink != 0) { if err := out.Remove(e.Name()); err != nil { - return err + return nil, err } } } var errs []error for _, in := range inputs { if err := generateOne(in, out, providers, g.mixins(mods)); err != nil { - errs = append(errs, fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err)) + err = fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err) + if errors.As(err, new(skipErr)) { + skipped = append(skipped, err) + } else { + errs = append(errs, err) + } } } - return errors.Join(errs...) + return skipped, errors.Join(errs...) } // openOut returns an os.Root on /.resource_types, refusing anything but a real directory there. @@ -142,7 +163,7 @@ func generateOne(in string, out *os.Root, providers map[string][]string, resolve } types, err := parseFile(string(src), resolve) if err != nil { - return err + return unparsed(err) } var t *rtype for _, c := range types { @@ -151,11 +172,11 @@ func generateOne(in string, out *os.Root, providers map[string][]string, resolve } } if t == nil { - return fmt.Errorf("custom type %q was not defined", name) + return skipErr{fmt.Errorf("custom type %q was not defined", name)} } body, err := render(t, providers[name], time.Now()) if err != nil { - return err + return unparsed(err) } tmp := "." + dst + ".tmp" if err := out.RemoveAll(tmp); err != nil { @@ -218,7 +239,7 @@ func (g *gen) confine(p string) (string, error) { return real, nil } } - return "", fmt.Errorf("%s resolves outside the environment and module cache", p) + return "", fmt.Errorf("%s %w", p, errConfine) } // list returns the confined subdirectories of dir, or nothing when dir is absent. diff --git a/internal/gentypes/generate_test.go b/internal/gentypes/generate_test.go index f74934e..77b36b3 100644 --- a/internal/gentypes/generate_test.go +++ b/internal/gentypes/generate_test.go @@ -33,7 +33,7 @@ func TestGolden(t *testing.T) { if err := os.RemoveAll(filepath.Join(work, OutDir)); err != nil { t.Fatal(err) } - if err := Generate(work); err != nil { + if _, err := Generate(work); err != nil { t.Fatal(err) } want, _ := filepath.Glob(filepath.Join(golden, "*.pp")) @@ -298,7 +298,7 @@ func TestGenerateFiles(t *testing.T) { } } - if err := Generate(env, cache); err != nil { + if _, err := Generate(env, cache); err != nil { t.Fatal(err) } if exists(filepath.Join(out, "stale.pp")) || exists(filepath.Join(out, "link.pp")) || !exists(filepath.Join(out, "keepdir")) { @@ -327,7 +327,7 @@ func TestGenerateFiles(t *testing.T) { if err := os.Chtimes(bar, in.ModTime(), in.ModTime()); err != nil { t.Fatal(err) } - if err := Generate(env, cache); err != nil { + if _, err := Generate(env, cache); err != nil { t.Fatal(err) } if readFile(t, bar) != "edited" { @@ -336,7 +336,7 @@ func TestGenerateFiles(t *testing.T) { if err := os.Chtimes(bar, in.ModTime(), in.ModTime().Add(-time.Hour)); err != nil { t.Fatal(err) } - if err := Generate(env, cache); err != nil { + if _, err := Generate(env, cache); err != nil { t.Fatal(err) } if readFile(t, bar) == "edited" { @@ -359,7 +359,7 @@ func readFile(t *testing.T, p string) string { } func TestGenerateErrors(t *testing.T) { - t.Run("bad input names the file and keeps going", func(t *testing.T) { + t.Run("unparseable input is skipped naming the file and line", func(t *testing.T) { env := t.TempDir() writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/bad.rb"), "Puppet::Type.newtype(:bad) do\n newparam(dynamic)\nend\n") writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/good.rb"), strings.ReplaceAll(simpleType, "%s", "good")) @@ -368,9 +368,9 @@ func TestGenerateErrors(t *testing.T) { if err := os.Chtimes(filepath.Join(env, OutDir, "bad.pp"), old, old); err != nil { t.Fatal(err) } - err := Generate(env) - if err == nil || !strings.Contains(err.Error(), "modules/m/lib/puppet/type/bad.rb") { - t.Fatalf("got %v", err) + skipped, err := Generate(env) + if err != nil || len(skipped) != 1 || !strings.Contains(skipped[0].Error(), "modules/m/lib/puppet/type/bad.rb: line 2:") { + t.Fatalf("got %v, skipped %v", err, skipped) } if !exists(filepath.Join(env, OutDir, "good.pp")) || readFile(t, filepath.Join(env, OutDir, "bad.pp")) != "previous" { t.Fatal("good inputs still generate; a failing input's old output is kept") @@ -379,8 +379,22 @@ func TestGenerateErrors(t *testing.T) { t.Run("wrong type name", func(t *testing.T) { env := t.TempDir() writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/a.rb"), strings.ReplaceAll(simpleType, "%s", "b")) - if err := Generate(env); err == nil || !strings.Contains(err.Error(), `"a" was not defined`) { - t.Fatalf("got %v", err) + if skipped, err := Generate(env); err != nil || len(skipped) != 1 || !strings.Contains(skipped[0].Error(), `"a" was not defined`) { + t.Fatalf("got %v, skipped %v", err, skipped) + } + }) + t.Run("parser limit fails the env", func(t *testing.T) { + env := t.TempDir() + writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/deep.rb"), "Puppet::Type.newtype(:deep) do\nend\n"+strings.Repeat("module A\n", 300)+strings.Repeat("end\n", 300)) + if skipped, err := Generate(env); !errors.Is(err, errLimit) || len(skipped) != 0 { + t.Fatalf("got %v, skipped %v", err, skipped) + } + }) + t.Run("missing mixin is skipped", func(t *testing.T) { + env := t.TempDir() + writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/mix.rb"), "Puppet::Type.newtype(:mix) do\n include PuppetX::Nope\nend\n") + if skipped, err := Generate(env); err != nil || len(skipped) != 1 { + t.Fatalf("got %v, skipped %v", err, skipped) } }) t.Run("output dir symlink", func(t *testing.T) { @@ -388,7 +402,7 @@ func TestGenerateErrors(t *testing.T) { if err := os.Symlink(t.TempDir(), filepath.Join(env, OutDir)); err != nil { t.Fatal(err) } - if err := Generate(env); err == nil || !strings.Contains(err.Error(), "not a directory") { + if _, err := Generate(env); err == nil || !strings.Contains(err.Error(), "not a directory") { t.Fatalf("got %v", err) } }) @@ -401,14 +415,14 @@ func TestGenerateErrors(t *testing.T) { if err := os.Symlink(filepath.Join(outside, "evil.rb"), filepath.Join(env, "modules/m/lib/puppet/type/evil.rb")); err != nil { t.Fatal(err) } - if err := Generate(env); err == nil || !strings.Contains(err.Error(), "outside") { + if _, err := Generate(env); err == nil || !strings.Contains(err.Error(), "outside") { t.Fatalf("got %v", err) } }) t.Run("modulepath outside roots", func(t *testing.T) { env := t.TempDir() writeFile(t, filepath.Join(env, "environment.conf"), "modulepath = "+t.TempDir()+"\n") - if err := Generate(env); err == nil || !strings.Contains(err.Error(), "outside") { + if _, err := Generate(env); err == nil || !strings.Contains(err.Error(), "outside") { t.Fatalf("got %v", err) } }) diff --git a/internal/gentypes/lexer.go b/internal/gentypes/lexer.go index 311b373..687371b 100644 --- a/internal/gentypes/lexer.go +++ b/internal/gentypes/lexer.go @@ -177,7 +177,7 @@ func (l *lexer) run() error { } start := len(l.toks) if start > maxTokens { - return fmt.Errorf("more than %d tokens", maxTokens) + return fmt.Errorf("more than %d tokens: %w", maxTokens, errLimit) } if err := l.next(space); err != nil { return err @@ -359,7 +359,7 @@ func (l *lexer) percent() error { // scan reads a delimited body starting at the opening delimiter, returning raw text with nesting and #{} honoured. func (l *lexer) scan(open, cl byte, interp bool, nest int) (string, error) { if nest > maxDepth { - return "", fmt.Errorf("interpolation nested deeper than %d", maxDepth) + return "", fmt.Errorf("interpolation nested deeper than %d: %w", maxDepth, errLimit) } l.pos++ s := l.pos diff --git a/internal/gentypes/parse.go b/internal/gentypes/parse.go index d92662e..3c67093 100644 --- a/internal/gentypes/parse.go +++ b/internal/gentypes/parse.go @@ -97,7 +97,10 @@ type parser struct { resolve Resolver } -var errBudget = errors.New("parse step budget exceeded") +var ( + errLimit = errors.New("parser limit exceeded") + errBudget = fmt.Errorf("step budget: %w", errLimit) +) func guard(err *error) { if r := recover(); r != nil { @@ -204,7 +207,7 @@ func (p *parser) skipNL() { func (p *parser) enter() error { if p.depth++; p.depth > maxDepth { - return fmt.Errorf("nesting deeper than %d", maxDepth) + return fmt.Errorf("nesting deeper than %d: %w", maxDepth, errLimit) } return nil } From b31b4f617587a063554ca817c7766911bfaaa1a1 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:45:18 +1100 Subject: [PATCH 8/8] Skip types w10k cannot prove match puppet - bound-check a trailing $ in the lexer and turn a per-file panic into an env error - allowlist top-level statements: requires, literal constants, module Puppet, begin/rescue requires - require the require that defines Puppet::ResourceApi, Boolean and File parents and included mixins - name providers by their provide call; skip types whose provider files are not one recognised provide - read symbol option keys only, as newparam, newproperty and register_type do - parse Resource API types with a TypeParser-compatible grammar - skip duplicate properties and parameters - add a parseFile fuzz target and real-puppet golden fixtures for each case --- internal/deploy/deploy_test.go | 4 +- internal/gentypes/fuzz_test.go | 37 ++ internal/gentypes/generate.go | 72 ++- internal/gentypes/generate_test.go | 193 ++++++-- internal/gentypes/lexer.go | 2 +- internal/gentypes/parse.go | 413 +++++++++++++++--- internal/gentypes/ptype.go | 334 ++++++++++++++ .../lib/puppet/provider/r_prov_class/posix.rb | 2 + .../lib/puppet/provider/r_prov_empty/posix.rb | 0 .../lib/puppet/provider/r_prov_name/posix.rb | 3 + .../lib/puppet/provider/r_prov_parent/a.rb | 2 + .../lib/puppet/provider/r_prov_parent/b.rb | 3 + .../provider/r_prov_parent_missing/a.rb | 2 + .../modules/review/lib/puppet/type/r_bare.rb | 3 + .../modules/review/lib/puppet/type/r_begin.rb | 10 + .../review/lib/puppet/type/r_const_call.rb | 4 + .../review/lib/puppet/type/r_dollar.rb | 4 + .../review/lib/puppet/type/r_dup_ensure.rb | 5 + .../review/lib/puppet/type/r_dup_param.rb | 5 + .../review/lib/puppet/type/r_dup_prop.rb | 5 + .../review/lib/puppet/type/r_feature_const.rb | 4 + .../review/lib/puppet/type/r_helper.rb | 9 + .../review/lib/puppet/type/r_include_noreq.rb | 4 + .../review/lib/puppet/type/r_include_req.rb | 6 + .../lib/puppet/type/r_inline_provide.rb | 4 + .../review/lib/puppet/type/r_mod_compact.rb | 5 + .../review/lib/puppet/type/r_mod_foo.rb | 5 + .../review/lib/puppet/type/r_mod_puppet.rb | 5 + .../review/lib/puppet/type/r_param_prop.rb | 5 + .../review/lib/puppet/type/r_prov_class.rb | 3 + .../review/lib/puppet/type/r_prov_empty.rb | 3 + .../review/lib/puppet/type/r_prov_name.rb | 3 + .../review/lib/puppet/type/r_prov_parent.rb | 3 + .../lib/puppet/type/r_prov_parent_missing.rb | 3 + .../lib/puppet/type/r_require_missing.rb | 4 + .../review/lib/puppet/type/r_rs_bad_lower.rb | 8 + .../review/lib/puppet/type/r_rs_bad_range.rb | 8 + .../review/lib/puppet/type/r_rs_bad_regex.rb | 8 + .../lib/puppet/type/r_rs_bad_uncertain.rb | 8 + .../review/lib/puppet/type/r_rs_bad_undef.rb | 8 + .../review/lib/puppet/type/r_rs_bad_words.rb | 8 + .../lib/puppet/type/r_rs_str_feature.rb | 8 + .../review/lib/puppet/type/r_rs_str_key.rb | 7 + .../lib/puppet/type/r_rs_sym_feature.rb | 8 + .../review/lib/puppet/type/r_rs_types.rb | 18 + .../modules/review/lib/puppet/type/r_send.rb | 4 + .../review/lib/puppet/type/r_str_keys.rb | 6 + .../modules/review/lib/puppet_x/review/mix.rb | 10 + internal/gentypes/testdata/golden/r_begin.pp | 17 + .../gentypes/testdata/golden/r_const_call.pp | 16 + internal/gentypes/testdata/golden/r_helper.pp | 18 + .../gentypes/testdata/golden/r_include_req.pp | 21 + .../testdata/golden/r_inline_provide.pp | 24 + .../gentypes/testdata/golden/r_mod_puppet.pp | 16 + .../gentypes/testdata/golden/r_param_prop.pp | 18 + .../gentypes/testdata/golden/r_prov_class.pp | 16 + .../gentypes/testdata/golden/r_prov_empty.pp | 16 + .../gentypes/testdata/golden/r_prov_name.pp | 24 + .../gentypes/testdata/golden/r_prov_parent.pp | 27 ++ .../testdata/golden/r_rs_bad_uncertain.pp | 20 + .../testdata/golden/r_rs_bad_undef.pp | 20 + .../testdata/golden/r_rs_str_feature.pp | 20 + .../testdata/golden/r_rs_sym_feature.pp | 19 + .../gentypes/testdata/golden/r_rs_types.pp | 64 +++ internal/gentypes/testdata/golden/r_send.pp | 18 + .../gentypes/testdata/golden/r_str_keys.pp | 18 + 66 files changed, 1573 insertions(+), 97 deletions(-) create mode 100644 internal/gentypes/fuzz_test.go create mode 100644 internal/gentypes/ptype.go create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_class/posix.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_empty/posix.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_name/posix.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent/a.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent/b.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent_missing/a.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_bare.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_begin.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_const_call.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dollar.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_ensure.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_param.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_prop.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_feature_const.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_helper.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_include_noreq.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_include_req.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_inline_provide.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_compact.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_foo.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_puppet.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_param_prop.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_class.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_empty.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_name.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_parent.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_parent_missing.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_require_missing.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_lower.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_range.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_regex.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_uncertain.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_undef.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_words.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_str_feature.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_str_key.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_sym_feature.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_types.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_send.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_str_keys.rb create mode 100644 internal/gentypes/testdata/env/modules/review/lib/puppet_x/review/mix.rb create mode 100644 internal/gentypes/testdata/golden/r_begin.pp create mode 100644 internal/gentypes/testdata/golden/r_const_call.pp create mode 100644 internal/gentypes/testdata/golden/r_helper.pp create mode 100644 internal/gentypes/testdata/golden/r_include_req.pp create mode 100644 internal/gentypes/testdata/golden/r_inline_provide.pp create mode 100644 internal/gentypes/testdata/golden/r_mod_puppet.pp create mode 100644 internal/gentypes/testdata/golden/r_param_prop.pp create mode 100644 internal/gentypes/testdata/golden/r_prov_class.pp create mode 100644 internal/gentypes/testdata/golden/r_prov_empty.pp create mode 100644 internal/gentypes/testdata/golden/r_prov_name.pp create mode 100644 internal/gentypes/testdata/golden/r_prov_parent.pp create mode 100644 internal/gentypes/testdata/golden/r_rs_bad_uncertain.pp create mode 100644 internal/gentypes/testdata/golden/r_rs_bad_undef.pp create mode 100644 internal/gentypes/testdata/golden/r_rs_str_feature.pp create mode 100644 internal/gentypes/testdata/golden/r_rs_sym_feature.pp create mode 100644 internal/gentypes/testdata/golden/r_rs_types.pp create mode 100644 internal/gentypes/testdata/golden/r_send.pp create mode 100644 internal/gentypes/testdata/golden/r_str_keys.pp diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 5b0e89e..946027c 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -626,7 +626,7 @@ func TestGenerateTypesBeforeSwap(t *testing.T) { newRepo(t, typed) commit(t, typed, map[string]string{ "lib/puppet/type/typed.rb": "Puppet::Type.newtype(:typed) do\n newparam(:name, namevar: true)\nend\n", - "lib/puppet/provider/typed/posix.rb": "", + "lib/puppet/provider/typed/posix.rb": "Puppet::Type.type(:typed).provide(:posix) do\nend\n", }) commit(t, f.control, map[string]string{ "Puppetfile": fmt.Sprintf("moduledir 'external_modules'\nmod 'typed', :git => '%s'\n", f.url(typed)), @@ -656,7 +656,7 @@ func TestGenerateTypesBeforeSwap(t *testing.T) { } live = skipped - commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name)\nend\n" + strings.Repeat("module A\n", 300) + strings.Repeat("end\n", 300)}) + commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name) do\n newvalues(" + strings.Repeat("[", 300) + strings.Repeat("]", 300) + ")\n end\nend\n"}) if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "deeper than") || !strings.Contains(err.Error(), "site/local/lib/puppet/type/local.rb") { t.Fatalf("a parser limit must fail the deploy naming the file: %v", err) } diff --git a/internal/gentypes/fuzz_test.go b/internal/gentypes/fuzz_test.go new file mode 100644 index 0000000..2c88127 --- /dev/null +++ b/internal/gentypes/fuzz_test.go @@ -0,0 +1,37 @@ +package gentypes + +import ( + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func FuzzParseFile(f *testing.F) { + err := filepath.WalkDir("testdata/env", func(p string, d fs.DirEntry, err error) error { + if err == nil && strings.HasSuffix(p, ".rb") { + b, rerr := os.ReadFile(p) + f.Add(string(b)) + return rerr + } + return err + }) + if err != nil { + f.Fatal(err) + } + mix := "module PuppetX\n module M\n def exists?; end\n end\nend\n" + f.Fuzz(func(t *testing.T, src string) { + types, err := parseFile(src, func(string, bool) ([]string, error) { return []string{mix, src}, nil }) + if err == nil { + for _, ty := range types { + _, _ = render(ty, []string{"a"}, time.Unix(0, 0)) + } + } + _, _, _ = providerOf(src, "t") + _, _ = mixinMethods(src, "PuppetX::M") + _, _ = inertLib(src) + _, _ = parsePType(src) + }) +} diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index e0e8b4b..be6e97f 100644 --- a/internal/gentypes/generate.go +++ b/internal/gentypes/generate.go @@ -18,7 +18,7 @@ import ( const OutDir = ".resource_types" // Version changes whenever generated output can change, so deploys rebuild typed environments. -const Version = "2" +const Version = "3" var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) @@ -79,9 +79,9 @@ func Generate(env string, roots ...string) (skipped []error, err error) { return nil, err } for _, f := range files { - typ, name := filepath.Base(d), strings.TrimSuffix(filepath.Base(f), ".rb") - if !slices.Contains(providers[typ], name) { - providers[typ] = append(providers[typ], name) + typ := filepath.Base(d) + if !slices.ContainsFunc(providers[typ], func(o string) bool { return filepath.Base(o) == filepath.Base(f) }) { + providers[typ] = append(providers[typ], f) } } } @@ -114,7 +114,7 @@ func Generate(env string, roots ...string) (skipped []error, err error) { } var errs []error for _, in := range inputs { - if err := generateOne(in, out, providers, g.mixins(mods)); err != nil { + if err := generateOne(in, out, providers[strings.TrimSuffix(filepath.Base(in), ".rb")], g.libs(mods, in)); err != nil { err = fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err) if errors.As(err, new(skipErr)) { skipped = append(skipped, err) @@ -147,7 +147,13 @@ func openOut(env string) (*os.Root, error) { return root.OpenRoot(OutDir) } -func generateOne(in string, out *os.Root, providers map[string][]string, resolve Resolver) error { +// generateOne writes the type defined by in; providers are the first-found provider files the autoloader loads for it. +func generateOne(in string, out *os.Root, providers []string, resolve Resolver) (err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("panic: %v", r) + } + }() ifi, err := os.Stat(in) if err != nil { return err @@ -174,7 +180,11 @@ func generateOne(in string, out *os.Root, providers map[string][]string, resolve if t == nil { return skipErr{fmt.Errorf("custom type %q was not defined", name)} } - body, err := render(t, providers[name], time.Now()) + names, err := providerNames(t, providers) + if err != nil { + return err + } + body, err := render(t, names, time.Now()) if err != nil { return unparsed(err) } @@ -200,14 +210,49 @@ func generateOne(in string, out *os.Root, providers map[string][]string, resolve return out.Rename(tmp, dst) } -var camel = regexp.MustCompile(`([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])`) +// providerNames returns the providers puppet registers for t, or a skip when a provider file is not a recognised provide call. +func providerNames(t *rtype, files []string) ([]string, error) { + var names, parents []string + for _, f := range files { + src, err := os.ReadFile(f) + if err != nil { + return nil, err + } + name, parent, err := providerOf(string(src), t.name) + switch { + case err != nil: + case t.rsapi && name != "": + err = fmt.Errorf("provide on a Resource API type") + case !t.rsapi && name == "": + err = fmt.Errorf("no Puppet::Type.type(:%s).provide call", t.name) + } + if err != nil { + return nil, unparsed(fmt.Errorf("provider %s: %w", filepath.Base(f), err)) + } + if !slices.Contains(names, name) && name != "" { + names = append(names, name) + } + if parent != "" { + parents = append(parents, parent) + } + } + for _, p := range parents { + if !slices.Contains(names, p) { + return nil, skipErr{fmt.Errorf("parent provider %s is not defined", p)} + } + } + return names, nil +} -// mixins resolves a constant path to every module's lib/.rb, as Ruby's require would find it. -func (g *gen) mixins(mods []string) Resolver { - return func(path string) ([]string, error) { - rel := strings.ToLower(camel.ReplaceAllString(strings.ReplaceAll(path, "::", "/"), "${1}${3}_${2}${4}")) + ".rb" +// libs resolves a lib-relative path in every module as Ruby's require would search, or only in the module of in when local. +func (g *gen) libs(mods []string, in string) Resolver { + own := filepath.Dir(filepath.Dir(filepath.Dir(filepath.Dir(in)))) + return func(rel string, local bool) ([]string, error) { var srcs []string for _, m := range mods { + if local && m != own { + continue + } p := filepath.Join(m, "lib", rel) if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) { continue @@ -222,9 +267,6 @@ func (g *gen) mixins(mods []string) Resolver { } srcs = append(srcs, string(b)) } - if len(srcs) == 0 { - return nil, fmt.Errorf("no module provides lib/%s", rel) - } return srcs, nil } } diff --git a/internal/gentypes/generate_test.go b/internal/gentypes/generate_test.go index 77b36b3..49489d9 100644 --- a/internal/gentypes/generate_test.go +++ b/internal/gentypes/generate_test.go @@ -20,11 +20,14 @@ func uncommented(s string) string { return blankRun.ReplaceAllString(commentLine.ReplaceAllString(s, ""), "\n") } +// realOnly are golden files real puppet generates that w10k skips because it cannot prove the output matches. +var realOnly = set("r_const_call r_helper r_inline_provide r_prov_class r_prov_empty r_rs_bad_uncertain r_rs_bad_undef r_send") + // GENTYPES_ENV/GENTYPES_GOLDEN compare a full environment without comments, since provider docs are not ported. func TestGolden(t *testing.T) { - env, golden, view := "testdata/env", "testdata/golden", func(s string) string { _, rest, _ := strings.Cut(s, "\n"); return rest } + env, golden, view, allowSkip := "testdata/env", "testdata/golden", func(s string) string { _, rest, _ := strings.Cut(s, "\n"); return rest }, realOnly if e := os.Getenv("GENTYPES_ENV"); e != "" { - env, golden, view = e, os.Getenv("GENTYPES_GOLDEN"), uncommented + env, golden, view, allowSkip = e, os.Getenv("GENTYPES_GOLDEN"), uncommented, nil } work := t.TempDir() if err := os.CopyFS(work, os.DirFS(env)); err != nil { @@ -40,12 +43,24 @@ func TestGolden(t *testing.T) { if len(want) == 0 { t.Fatal("no golden files") } + got, _ := filepath.Glob(filepath.Join(work, OutDir, "*.pp")) + for _, g := range got { + if !exists(filepath.Join(golden, filepath.Base(g))) { + t.Errorf("%s generated, real puppet does not generate it", filepath.Base(g)) + } + } match := 0 for _, w := range want { name := filepath.Base(w) t.Run(strings.TrimSuffix(name, ".pp"), func(t *testing.T) { wb, _ := os.ReadFile(w) gb, err := os.ReadFile(filepath.Join(work, OutDir, name)) + if allowSkip[strings.TrimSuffix(name, ".pp")] { + if err == nil { + t.Fatal("expected a skip") + } + return + } if err != nil { t.Fatal(err) } @@ -58,7 +73,55 @@ func TestGolden(t *testing.T) { match++ }) } - t.Logf("%d/%d golden files match", match, len(want)) + t.Logf("%d/%d golden files match", match, len(want)-len(allowSkip)) +} + +// TestReviewSkips pins why each testdata/env/modules/review type that real puppet 9.3.0 fails to load, or that +// w10k cannot prove, is skipped. +func TestReviewSkips(t *testing.T) { + work := t.TempDir() + if err := os.CopyFS(work, os.DirFS("testdata/env")); err != nil { + t.Fatal(err) + } + skipped, err := Generate(work) + if err != nil { + t.Fatal(err) + } + got := map[string]string{} + for _, s := range skipped { + file, why, _ := strings.Cut(s.Error(), ": ") + got[strings.TrimSuffix(filepath.Base(file), ".rb")] = why + } + for name, want := range map[string]string{ + "r_dollar": "line 4: unsupported top-level $", + "r_prov_empty": "provider posix.rb: no Puppet::Type.type(:r_prov_empty).provide call", + "r_prov_class": "provider posix.rb: no Puppet::Type.type(:r_prov_class).provide call", + "r_prov_parent_missing": "parent provider nope is not defined", + "r_send": "line 4: unsupported top-level Puppet::Type.type", + "r_inline_provide": "line 4: unsupported top-level Puppet::Type.type", + "r_helper": "line 1: unsupported top-level module RHelper", + "r_const_call": "unsupported non-literal constant X", + "r_require_missing": `require "puppet_x/review/nope": no module provides it`, + "r_rs_str_key": "register_type: unsupported string key", + "r_rs_bad_lower": `type "string": unsupported type`, + "r_rs_bad_range": "unsupported Integer[5,1]", + "r_rs_bad_regex": "unsupported regex /(/", + "r_rs_bad_undef": "unsupported Undef", + "r_rs_bad_uncertain": "cannot tell whether String and String[0] are the same type", + "r_rs_bad_words": "unsupported word if", + "r_dup_prop": "duplicate property a", + "r_dup_param": "duplicate parameter a", + "r_dup_ensure": "duplicate property ensure", + "r_bare": "unsupported top-level Type.newtype", + "r_mod_foo": "unsupported top-level module RFoo", + "r_mod_compact": "unsupported top-level module Puppet::RCompact", + "r_include_noreq": "include PuppetX::Review::Mix: no require defines it", + "r_feature_const": "uninitialized constant RNope", + } { + if !strings.Contains(got[name], want) { + t.Errorf("%s: got %q, want %q", name, got[name], want) + } + } } func TestScrub(t *testing.T) { @@ -111,7 +174,7 @@ func TestQuote(t *testing.T) { func typeOf(t *testing.T, body string) []string { t.Helper() - types, err := parseFile("Puppet::Type.newtype(:t) do\n"+body+"\nend\n", nil) + types, err := parseFile("require 'puppet/parameter/boolean'\nPuppet::Type.newtype(:t) do\n"+body+"\nend\n", nil) if err != nil { t.Fatal(err) } @@ -146,25 +209,50 @@ func TestPuppetTypeMapping(t *testing.T) { } } +// Expected values are ValueCreator.create_values on Puppet::Pops::Types::TypeParser.singleton.parse(typ) in openvox 9.3.0. func TestResourceAPIMapping(t *testing.T) { + const str, num, boolean = "Pattern[//]", `Pattern[/^-?\d+$/]`, "Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']]" for typ, want := range map[string]string{ - "String": "Pattern[//]", - "Optional[String[1]]": "Pattern[//]", - "Integer[0,65535]": `Pattern[/^-?\d+$/]`, - "Boolean": "Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']]", - "Enum[present, absent]": "Enum['absent', 'present']", - "Optional[Enum[a, b]]": "Any", - "Array[String]": "Any", - "Sensitive[String]": "Any", - "Optional[Numeric]": "Pattern[/" + strings.ReplaceAll(numericRe, "/", `\/`) + "/]", - "Variant[String, Undef]": "Any", + "String": str, + " Optional[String[1]] ": str, + "Integer[0,65535]": num, + "Boolean": boolean, + "Enum[present, absent]": "Enum['absent', 'present']", + "Optional[Enum[a, b]]": "Any", + "Array[String]": "Any", + "Sensitive[String]": "Any", + "Optional[Numeric]": "Pattern[/" + strings.ReplaceAll(numericRe, "/", `\/`) + "/]", + "Variant[String]": str, + "Optional[Variant[Integer]]": num, + "Variant[Optional[Float]]": "Pattern[/" + strings.ReplaceAll(numericRe, "/", `\/`) + "/]", + "Variant[Integer[ 1 , 2 ], Integer[1,2]]": num, + "Optional[Optional[String]]": "Any", + "Optional['x']": str, + "Variant[Variant[Boolean], Boolean]": boolean, + "Variant[String, Integer]": "Any", + "Optional": "Any", + "Variant": "Any", + "Hash[String, Integer, 1, 2]": "Any", + "Integer[-5, default]": num, } { a := &attr{} - rsapiValues(a, typ) + if err := rsapiValues(a, typ); err != nil { + t.Errorf("%s: %v", typ, err) + continue + } if got, _ := a.puppetType(); got != want { t.Errorf("%s = %s, want %s", typ, got, want) } } + for _, typ := range []string{ + "string", "Stdlib::Port", "Optional[]", "Variant[]", "Integer[5,1]", "Integer[1.5]", "Numeric[1]", "Array[String, 3, 1]", "Hash[String]", + "Float[2, 1.5]", "Pattern[/(/]", "Pattern['(']", "Pattern[/(?Px)/]", "Enum[if]", "Variant[String, Undef]", + "Variant[Integer, Integer[default,default]]", "Integer[0x10]", "String[1,2,3]", "Optional[String, Integer]", "Integer[", + } { + if err := rsapiValues(&attr{}, typ); err == nil { + t.Errorf("%s: TypeParser rejects it or its values are not provable, want an error", typ) + } + } } func TestHeredocs(t *testing.T) { @@ -196,13 +284,13 @@ func TestUnsupported(t *testing.T) { for _, c := range []struct{ src, want string }{ {"Puppet::Type.newtype(:t) do\n newparam(name_var)\nend", "unsupported expression"}, {"Puppet::Type.newtype(:t) do\n newparam(:a) do\n desc \"x #{NOPE}\"\n end\nend", "#{NOPE}"}, - {"Puppet::Type.newtype(:t) do\n newparam(:a, parent: Puppet::Parameter::Custom)\nend", "unsupported parent"}, + {"Puppet::Type.newtype(:t) do\n newparam(:a, parent: Puppet::Parameter::Custom)\nend", "uninitialized constant Puppet::Parameter::Custom"}, {"Puppet::Type.newtype(:t) do\n if x\n newparam(:a)\n end\nend", "unsupported if x in type body"}, {"Puppet::Type.newtype(:t) do\n if defined? X\n newparam(:a)\n end\nend", "unsupported conditional newparam"}, {"Puppet::Type.newtype(:t) do\n [:a, :b].each { |n| newparam(n) }\nend", "unsupported [ :a , :b ].each in type body"}, {"Puppet::Type.newtype(:t) do\n newparam(:a) do\n validate do\n newvalues(:x)\n end\n end\nend", "unsupported use of newvalues"}, {"Puppet::Type.newtype(:t) do\n def self.title_patterns\n [[/(.*)/, [[:a, lambda { |x| x }]]]]\n end\nend", "title_patterns"}, - {"Puppet::Type.newtype(:t, parent: Puppet::Type::File) do\nend", "newtype with options"}, + {"Puppet::Type.newtype(:t, self_refresh: true) do\nend", "newtype with options"}, {"Puppet::Type.newtype(:t) do\n newparam(:a) do\n desc 'x' + dynamic\n end\nend", "unsupported expression"}, {"Puppet::Type.newtype(:t) do\n @isomorphic = false\nend", "@isomorphic"}, {"Puppet::Type.newtype(:t) do\n newparam(:a)\n newparam(:b, namevar: true)\n newparam(:c, namevar: true)\nend", "two or more key attributes"}, @@ -385,7 +473,7 @@ func TestGenerateErrors(t *testing.T) { }) t.Run("parser limit fails the env", func(t *testing.T) { env := t.TempDir() - writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/deep.rb"), "Puppet::Type.newtype(:deep) do\nend\n"+strings.Repeat("module A\n", 300)+strings.Repeat("end\n", 300)) + writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/deep.rb"), "Puppet::Type.newtype(:deep) do\n newparam(:a) do\n newvalues("+strings.Repeat("[", 300)+strings.Repeat("]", 300)+")\n end\nend\n") if skipped, err := Generate(env); !errors.Is(err, errLimit) || len(skipped) != 0 { t.Fatalf("got %v, skipped %v", err, skipped) } @@ -447,11 +535,8 @@ func parseWithin(t *testing.T, src string, resolve Resolver) ([]*rtype, error) { func TestStrayCloserIsAnError(t *testing.T) { for src, want := range map[string]string{ - ")\n": `unmatched ")"`, - "]\n": `unmatched "]"`, - "}\n": `unmatched "}"`, - "end\n": `unmatched "end"`, - "module A\n foo )\nend\n": `unmatched ")"`, + ")\n": "unsupported top-level )", + "end\n": "unsupported top-level end", "Puppet::Type.newtype(:t) do\n }\nend\n": "line 2: unsupported } in type body", "Puppet::Type.newtype(:t) do\n newparam(:a) do\n )\n end\nend\n": "line 3: unsupported ) in attribute a", } { @@ -459,6 +544,11 @@ func TestStrayCloserIsAnError(t *testing.T) { t.Errorf("%q: got %v, want %q", src, err, want) } } + for src, want := range map[string]string{")\n": `unmatched ")"`, "]\n": `unmatched "]"`, "}\n": `unmatched "}"`, "end\n": `unmatched "end"`, "class A\n foo )\nend\n": "unmatched"} { + if _, _, err := providerOf(src, "t"); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("provider %q: got %v, want %q", src, err, want) + } + } } func TestStepBudget(t *testing.T) { @@ -485,7 +575,6 @@ func TestDeepNestingIsAnError(t *testing.T) { } for _, src := range []string{ "Puppet::Type.newtype(:u) do\n newparam(:a) do\n newvalues(" + strings.Repeat("[", 300) + strings.Repeat("]", 300) + ")\n end\nend\n", - strings.Repeat("module A\n", 300) + strings.Repeat("end\n", 300), "Puppet::Type.newtype(:t) do\n newparam(:a) do\n" + strings.Repeat("if defined? X\n", 300) + strings.Repeat("end\n", 300) + "end\nend\n", `x = "` + strings.Repeat(`#{"`, 300) + strings.Repeat(`"}`, 300) + `"` + "\n", } { @@ -493,6 +582,9 @@ func TestDeepNestingIsAnError(t *testing.T) { t.Errorf("%.40q: got %v", src, err) } } + if _, err := inertLib("module PuppetX\n" + strings.Repeat("module A\n", 300) + strings.Repeat("end\n", 301)); err == nil || !strings.Contains(err.Error(), "deeper than") { + t.Errorf("nested required modules: got %v", err) + } cmd := exec.Command(os.Args[0], "-test.run=^TestDeepNestingIsAnError$") cmd.Env = append(os.Environ(), "GENTYPES_DEEP_CHILD=1") if out, err := cmd.CombinedOutput(); err != nil { @@ -540,7 +632,7 @@ func mustParse(t *testing.T, src string) *rtype { } func TestResourceAPIBehaviorSpelling(t *testing.T) { - ty := mustParse(t, "Puppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behavior: :namevar }, p: { type: 'String', behavior: :parameter } })\n") + ty := mustParse(t, "require 'puppet/resource_api'\nPuppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behavior: :namevar }, p: { type: 'String', behavior: :parameter } })\n") if len(ty.params) != 2 || !ty.params[0].namevar || ty.params[1].namevar || len(ty.props) != 0 { t.Fatalf("behavior: is an alias of behaviour: %+v %+v", ty.params, ty.props) } @@ -548,7 +640,7 @@ func TestResourceAPIBehaviorSpelling(t *testing.T) { "Puppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behavior: :namevar, behaviour: :namevar } })\n": "both behavior and behaviour", "Puppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behaviour: 'namevar' } })\n": "behaviour must be a symbol", } { - if _, err := parseWithin(t, src, nil); err == nil || !strings.Contains(err.Error(), want) { + if _, err := parseWithin(t, "require 'puppet/resource_api'\n"+src, nil); err == nil || !strings.Contains(err.Error(), want) { t.Errorf("%s: got %v, want %q", src, err, want) } } @@ -619,3 +711,52 @@ func TestLiteralNormalisation(t *testing.T) { } } } + +func TestProviderOf(t *testing.T) { + for src, want := range map[string]string{ + "Puppet::Type.type(:t).provide(:a) do\nend\n": "a ", + "require 'json'\nPuppet::Type.type('t').provide :b, parent: :a do\nend\nclass X\nend\n": "b a", + "Puppet::Type.type(:t).provide(:c, parent: Puppet::Provider::Foo) {}\n": "c ", + "class Puppet::Provider::T::Rsapi\nend\n": " ", + "": " ", + "Puppet::Type.type(:t).provide(name) do\nend\n": "error", + "Puppet::Type.type(:other).provide(:a) do\nend\n": "error", + "Puppet::Type.type(:t).provide(:a)\nPuppet::Type.type(:t).provide(:b)\n": "error", + "Puppet::Type.type(:t).provide(:a)\nPuppet::Type.type(:t).newparam(:x)\n": "error", + "module M\n Puppet::Type.type(:t).provide(:a)\nend\n": "error", + "Puppet::Type.type(:t).provide(:a, 'parent' => :b)\n": "error", + "$": " ", + } { + name, parent, err := providerOf(src, "t") + got := name + " " + parent + if err != nil { + got = "error" + } + if got != want { + t.Errorf("%q: got %q (%v), want %q", src, got, err, want) + } + } +} + +func TestLexTrailingSigil(t *testing.T) { + for _, src := range []string{"$", "x = $", "@", "@@", "Puppet::Type.newtype(:t) do\nend\n$"} { + if _, err := parseWithin(t, src, nil); err == nil { + t.Errorf("%q: want an error", src) + } + } +} + +func TestGeneratePanicFailsTheEnv(t *testing.T) { + env := t.TempDir() + in := filepath.Join(env, "modules/m/lib/puppet/type/mix.rb") + writeFile(t, in, "require 'puppet_x/m/mix'\nPuppet::Type.newtype(:mix) do\n include PuppetX::M::Mix\nend\n") + out, err := openOut(env) + if err != nil { + t.Fatal(err) + } + defer func() { _ = out.Close() }() + err = generateOne(in, out, nil, func(string, bool) ([]string, error) { panic("boom") }) + if err == nil || !strings.Contains(err.Error(), "panic: boom") || errors.As(err, new(skipErr)) { + t.Fatalf("a panic must be a hard error, got %v", err) + } +} diff --git a/internal/gentypes/lexer.go b/internal/gentypes/lexer.go index 687371b..8d9ffa7 100644 --- a/internal/gentypes/lexer.go +++ b/internal/gentypes/lexer.go @@ -231,7 +231,7 @@ func (l *lexer) next(space bool) error { if c == '@' && l.peek(0) == '@' { l.pos++ } - if c == '$' && !isIdentStart(l.peek(0)) { + if c == '$' && !isIdentStart(l.peek(0)) && l.pos < len(l.src) { l.pos++ } for l.pos < len(l.src) && isIdentChar(l.src[l.pos]) { diff --git a/internal/gentypes/parse.go b/internal/gentypes/parse.go index 3c67093..f4c7e90 100644 --- a/internal/gentypes/parse.go +++ b/internal/gentypes/parse.go @@ -5,6 +5,7 @@ import ( "fmt" "math" "math/big" + "path" "regexp" "slices" "strconv" @@ -75,15 +76,15 @@ type rval struct { func (v rval) get(key string) (rval, bool) { for i, k := range v.keys { - if (k.k == vSym || k.k == vStr) && k.s == key { + if k.k == vSym && k.s == key { return v.arr[i], true } } return rval{}, false } -// Resolver returns the sources that may define a mixin module, by Ruby's constant-to-path convention. -type Resolver func(path string) ([]string, error) +// Resolver returns the sources of lib-relative file path in every module, or only the type's own module when local. +type Resolver func(path string, local bool) ([]string, error) type parser struct { toks []token @@ -95,6 +96,7 @@ type parser struct { steps int cond int resolve Resolver + defined map[string]bool } var ( @@ -123,8 +125,8 @@ func parseFile(src string, resolve Resolver) (types []*rtype, err error) { if err != nil { return nil, err } - p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}, resolve: resolve} - if err := p.body("", p.topStmt); err != nil { + p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}, resolve: resolve, defined: map[string]bool{"Facter": true, "Puppet::Parameter::Path": true, "Puppet::Property::Ensure": true}} + if err := p.body("", p.topStmt(false)); err != nil { return nil, p.wrap(err) } for i, t := range p.toks { @@ -399,27 +401,175 @@ func (p *parser) strictConstAssign() error { return nil } -func (p *parser) topStmt() (bool, error) { - t := p.cur() - switch { - case t.kind == tIdent && t.text == "module": - p.take() - for p.cur().kind == tConst || p.op("::") { - p.take() - } - return true, p.body("end", p.topStmt) - case t.kind == tConst && p.methodCall("newtype"): - return true, p.newtype() - case t.kind == tConst && p.methodCall("register_type"): - return true, p.registerType() - case t.kind == tConst && p.at(1).kind == tOp && p.at(1).text == "=": - return p.constAssign() +var fileConsts = []string{"Puppet::Parameter::Boolean", "Puppet::Property::Boolean", "Puppet::Type::File::Owner", "Puppet::Type::File::Group", "Puppet::Type::File::Mode"} + +// Libraries a type file may require without changing its type, present in openvox 9.3.0 and its Ruby; +// puppetLibs maps each to the constants it defines beyond those loaded with Puppet::Type. +var ( + rubyLibs = set("base64 digest/md5 erb fileutils ipaddr json net/http open3 pathname resolv securerandom set socket tempfile uri") + puppetLibs = map[string][]string{ + "puppet": nil, "puppet/util": nil, "puppet/util/checksums": nil, "puppet/parameter/path": nil, "puppet/property/ensure": nil, + "puppet/parameter/boolean": fileConsts[:2], + "puppet/property/boolean": fileConsts[1:2], + "puppet/resource_api": {"Puppet::ResourceApi"}, + "puppet/type/file": fileConsts, "puppet/type/file/owner": fileConsts, "puppet/type/file/group": fileConsts, "puppet/type/file/mode": fileConsts, + } + coreConsts = set("Puppet PuppetX Type ResourceApi") +) + +// topStmt allows only statements that cannot reach a type: requires, literal constants, module Puppet and the type definition. +func (p *parser) topStmt(inPuppet bool) func() (bool, error) { + return func() (bool, error) { + t := p.cur() + switch { + case t.kind == tIdent && t.text == "module" && !inPuppet && p.at(1).kind == tConst && p.at(1).text == "Puppet" && (p.at(2).kind == tNL || p.at(2).text == ";"): + p.i += 2 + return true, p.body("end", p.topStmt(true)) + case t.kind == tIdent && (t.text == "require" || t.text == "require_relative"): + return true, p.require() + case t.kind == tIdent && t.text == "begin": + return true, p.beginRequire() + case t.kind == tConst && p.methodCall("newtype", inPuppet): + return true, p.newtype() + case t.kind == tConst && p.methodCall("register_type", inPuppet): + if !p.defined["Puppet::ResourceApi"] { + return true, fmt.Errorf("Puppet::ResourceApi used without require 'puppet/resource_api'") + } + return true, p.registerType() + case t.kind == tConst && p.assigns() && !coreConsts[t.text]: + return true, p.strictConstAssign() + } + return true, fmt.Errorf("unsupported top-level %s", p.construct()) } - return false, nil } -// methodCall matches Const(::Const)*.name at the cursor and advances past the name. -func (p *parser) methodCall(name string) bool { +func (p *parser) require() error { + rel := p.take().text == "require_relative" + args, err := p.args() + if err != nil { + return err + } + if len(args) != 1 || args[0].k != vStr { + return fmt.Errorf("unsupported require argument") + } + lib := args[0].s + if rel { + lib = path.Join("puppet/type", lib) + } + if lib == "" || path.IsAbs(args[0].s) || path.Clean(lib) != lib || lib == ".." || strings.HasPrefix(lib, "../") || strings.HasSuffix(lib, ".rb") { + return fmt.Errorf("unsupported require %q", args[0].s) + } + var srcs []string + if p.resolve != nil { + if srcs, err = p.resolve(lib+".rb", rel); err != nil { + return fmt.Errorf("require %q: %w", args[0].s, err) + } + } + if consts, core := puppetLibs[lib]; !rel && (rubyLibs[lib] || core) { + if len(srcs) > 0 { + return fmt.Errorf("require %q is shadowed by a module", lib) + } + for _, c := range consts { + p.defined[c] = true + } + return nil + } + if len(srcs) == 0 { + return fmt.Errorf("require %q: no module provides it", args[0].s) + } + var common map[string]bool + for _, src := range srcs { + mods, err := inertLib(src) + if err != nil { + return fmt.Errorf("require %q: %w", args[0].s, err) + } + next := map[string]bool{} + for _, m := range mods { + if common == nil || common[m] { + next[m] = true + } + } + common = next + } + for m := range common { + p.defined[m] = true + } + return nil +} + +// beginRequire allows begin; require ...; rescue ...; end, whose rescue never runs since every allowed require succeeds. +func (p *parser) beginRequire() error { + p.take() + for { + p.skipNL() + switch { + case p.is(tIdent, "end"): + p.take() + return nil + case p.is(tIdent, "rescue"): + for { + p.skipNL() + switch { + case p.is(tIdent, "end"): + p.take() + return nil + case p.is(tIdent, "else") || p.is(tIdent, "ensure") || p.cur().kind == tEOF: + return fmt.Errorf("unsupported %s in begin", describe(p.cur())) + } + if err := p.skipStatement(); err != nil { + return err + } + } + case p.is(tIdent, "require") || p.is(tIdent, "require_relative"): + if err := p.require(); err != nil { + return err + } + default: + return fmt.Errorf("unsupported %s in begin", p.construct()) + } + } +} + +// inertLib returns the modules a required file defines, failing on anything but nested modules of methods and literal constants under PuppetX. +func inertLib(src string) (mods []string, err error) { + defer guard(&err) + toks, err := lex(src) + if err != nil { + return nil, err + } + p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}} + var scope func(prefix string) func() (bool, error) + scope = func(prefix string) func() (bool, error) { + return func() (bool, error) { + c := p.cur() + switch { + case c.kind == tIdent && c.text == "module" && p.at(1).kind == tConst && (p.at(2).kind == tNL || p.at(2).text == ";") && (prefix != "" || p.at(1).text == "PuppetX"): + name := p.at(1).text + if prefix != "" { + name = prefix + "::" + name + } + p.i += 2 + mods = append(mods, name) + return true, p.body("end", scope(name)) + case prefix != "" && c.kind == tIdent && c.text == "def": + return true, p.skipStatement() + case prefix != "" && c.kind == tIdent && (c.text == "private" || c.text == "protected" || c.text == "public") && (p.at(1).kind == tNL || p.at(1).text == ";"): + p.take() + return true, nil + case prefix != "" && c.kind == tConst && p.assigns(): + return true, p.strictConstAssign() + } + return true, fmt.Errorf("unsupported %s in required file", p.construct()) + } + } + if err := p.body("", scope("")); err != nil { + return nil, p.wrap(err) + } + return mods, nil +} + +// methodCall matches Const(::Const)*.name at the cursor and advances past the name; a bare Type resolves only inside module Puppet. +func (p *parser) methodCall(name string, inPuppet bool) bool { j := 0 for p.at(j).kind == tConst && p.at(j+1).kind == tOp && p.at(j+1).text == "::" { j += 2 @@ -432,7 +582,7 @@ func (p *parser) methodCall(name string) bool { for k := p.i; k <= j; k++ { recv += p.toks[k].text } - if (name == "newtype" && recv != "Puppet::Type" && recv != "Type") || (name == "register_type" && recv != "Puppet::ResourceApi") { + if (name == "newtype" && recv != "Puppet::Type" && (recv != "Type" || !inPuppet)) || (name == "register_type" && recv != "Puppet::ResourceApi") { return false } p.used[j+2] = true @@ -482,7 +632,7 @@ func (p *parser) newtype() error { } a := &attr{name: "ensure", ensure: true} a.defaultValues() - t.addProp(a) + return t.addProp(a) } return nil } @@ -665,8 +815,7 @@ func (p *parser) typeStmt(t *rtype) (bool, error) { } else if err := p.body(closeTok, func() (bool, error) { return p.attrStmt(a) }); err != nil { return true, err } - t.addProp(a) - return true, nil + return true, t.addProp(a) case c.kind == tIdent && c.text == "def" && p.at(1).kind == tIdent && p.at(1).text == "self" && p.at(2).text == "." && p.at(3).text == "title_patterns": p.used[p.i+3] = true p.i += 4 @@ -715,10 +864,17 @@ func (p *parser) include(t *rtype) error { if p.resolve == nil { return fmt.Errorf("include %s: mixin source is not available", path) } - srcs, err := p.resolve(path) + if !p.defined[path] { + return fmt.Errorf("include %s: no require defines it", path) + } + rel := strings.ToLower(camel.ReplaceAllString(strings.ReplaceAll(path, "::", "/"), "${1}${3}_${2}${4}")) + ".rb" + srcs, err := p.resolve(rel, false) if err != nil { return fmt.Errorf("include %s: %w", path, err) } + if len(srcs) == 0 { + return fmt.Errorf("include %s: no module provides lib/%s", path, rel) + } for _, src := range srcs { names, err := mixinMethods(src, path) if err != nil { @@ -795,14 +951,28 @@ func mixinMethods(src, path string) (methods []string, err error) { return methods, nil } -func (t *rtype) addProp(a *attr) { +func (t *rtype) addProp(a *attr) error { + if slices.ContainsFunc(t.props, func(o *attr) bool { return o.name == a.name }) { + return fmt.Errorf("duplicate property %s", a.name) + } if a.name == "ensure" { t.props = append([]*attr{a}, t.props...) - return + return nil } t.props = append(t.props, a) + return nil } +func (t *rtype) addParam(a *attr) error { + if t.hasParam(a.name) { + return fmt.Errorf("duplicate parameter %s", a.name) + } + t.params = append(t.params, a) + return nil +} + +var camel = regexp.MustCompile(`([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])`) + var parents = map[string][]string{ "Puppet::Parameter::Boolean": {"true", "false", "yes", "no"}, "Puppet::Property::Boolean": nil, @@ -813,6 +983,51 @@ var parents = map[string][]string{ "Puppet::Type::File::Mode": nil, } +// attrOptions returns the options that change generated output, keyed by symbol. newparam reads only symbol keys and +// applies :attributes through setters; newproperty applies every key except :parent through setters, of which only +// doc= and required_features= change output (Puppet::Property.public_methods in openvox 9.3.0). +func attrOptions(h rval, property bool) (rval, error) { + var out rval + seen := map[string]bool{} + for i, k := range h.keys { + if k.k != vSym && k.k != vStr { + return out, fmt.Errorf("unsupported %s option key", k.kindName()) + } + id := k.s + if !property { + id = k.kindName() + id + } + if seen[id] { + return out, fmt.Errorf("duplicate option %s", k.s) + } + seen[id] = true + switch { + case !property && k.k == vStr: + continue + case !property && k.s == "attributes" || property && k.s == "doc": + return out, fmt.Errorf("unsupported option %s", k.s) + case property && k.k == vStr && k.s == "parent": + continue + } + out.keys, out.arr = append(out.keys, rval{k: vSym, s: k.s}), append(out.arr, h.arr[i]) + } + return out, nil +} + +func symHash(h rval, what string) error { + seen := map[string]bool{} + for _, k := range h.keys { + if k.k != vSym { + return fmt.Errorf("%s: unsupported %s key", what, k.kindName()) + } + if seen[k.s] { + return fmt.Errorf("%s: duplicate key %s", what, k.s) + } + seen[k.s] = true + } + return nil +} + func (p *parser) newattr(t *rtype, property bool) error { args, err := p.args() if err != nil { @@ -830,7 +1045,10 @@ func (p *parser) newattr(t *rtype, property bool) error { return fmt.Errorf("attribute %s: unsupported arguments", name) } if len(args) == 2 { - opts := args[1] + opts, err := attrOptions(args[1], property) + if err != nil { + return fmt.Errorf("attribute %s: %w", name, err) + } if v, ok := opts.get("parent"); ok { vals, known := parents[v.s] if v.k != vConst || !known { @@ -860,11 +1078,9 @@ func (p *parser) newattr(t *rtype, property bool) error { } } if property { - t.addProp(a) - } else { - t.params = append(t.params, a) + return t.addProp(a) } - return nil + return t.addParam(a) } func features(v rval) ([]string, error) { @@ -1327,6 +1543,9 @@ func (p *parser) primary() (rval, error) { if c, ok := p.consts[path]; ok { return c, nil } + if p.defined != nil && !p.defined[path] { + return rval{}, fmt.Errorf("uninitialized constant %s", path) + } return rval{k: vConst, s: path}, nil case tOp: switch t.text { @@ -1424,6 +1643,9 @@ func str(v rval, ok bool) (string, bool) { } func resourceAPIType(def rval) (*rtype, error) { + if err := symHash(def, "register_type"); err != nil { + return nil, err + } name, ok := str(def.get("name")) if !ok { return nil, fmt.Errorf("register_type: name must be a string") @@ -1443,7 +1665,13 @@ func resourceAPIType(def rval) (*rtype, error) { if !ok || attrs.k != vHash { return nil, fmt.Errorf("register_type: attributes must be a literal hash") } - for _, opts := range attrs.arr { + if err := symHash(attrs, "register_type attributes"); err != nil { + return nil, err + } + for i, opts := range attrs.arr { + if err := symHash(opts, "attribute "+attrs.keys[i].s); err != nil { + return nil, err + } for j, k := range opts.keys { if k.k == vSym && k.s == "behavior" { if _, both := opts.get("behaviour"); both { @@ -1460,11 +1688,12 @@ func resourceAPIType(def rval) (*rtype, error) { insyncable = true } } - if feats, _ := def.get("features"); !insyncable && feats.k == vArray { - for _, f := range feats.arr { - if f.s == "custom_insync" { - t.props = append(t.props, &attr{name: "rsapi_custom_insync_trigger", doc: "A hidden property which enables a type with custom insync to perform an insync check without specifying any insyncable properties (a Enum[do_not_specify_in_manifest])"}) - } + if feats, ok := def.get("features"); ok { + if feats.k != vArray { + return nil, fmt.Errorf("register_type: features must be a literal array") + } + if !insyncable && slices.ContainsFunc(feats.arr, func(f rval) bool { return f.k == vStr && f.s == "custom_insync" }) { + t.props = append(t.props, &attr{name: "rsapi_custom_insync_trigger", doc: "A hidden property which enables a type with custom insync to perform an insync check without specifying any insyncable properties (a Enum[do_not_specify_in_manifest])"}) } } for i, k := range attrs.keys { @@ -1473,10 +1702,11 @@ func resourceAPIType(def rval) (*rtype, error) { if !ok || opts.k != vHash { return nil, fmt.Errorf("register_type: attribute %d must be name => hash", i) } - typ, ok := str(opts.get("type")) - if !ok { + tv, ok := opts.get("type") + if !ok || tv.k != vStr { return nil, fmt.Errorf("attribute %s: type must be a string", an) } + typ := tv.s bv, hasB := opts.get("behaviour") if hasB && bv.k != vSym { return nil, fmt.Errorf("attribute %s: behaviour must be a symbol", an) @@ -1494,11 +1724,15 @@ func resourceAPIType(def rval) (*rtype, error) { case behaviour != "parameter" && behaviour != "read_only" && behaviour != "init_only": return nil, fmt.Errorf("attribute %s: invalid behaviour %s", an, behaviour) } - rsapiValues(a, typ) + if err := rsapiValues(a, typ); err != nil { + return nil, fmt.Errorf("attribute %s: %w", an, err) + } + add := t.addParam if property { - t.addProp(a) - } else { - t.params = append(t.params, a) + add = t.addProp + } + if err := add(a); err != nil { + return nil, err } } t.custom = true @@ -1507,6 +1741,9 @@ func resourceAPIType(def rval) (*rtype, error) { return nil, fmt.Errorf("title_patterns must be a literal array") } for _, e := range tp.arr { + if err := symHash(e, "title_patterns"); err != nil { + return nil, err + } re, ok := e.get("pattern") if e.k != vHash || !ok || re.k != vRegex { return nil, fmt.Errorf("title_patterns entries need a literal regex pattern") @@ -1529,13 +1766,13 @@ func resourceAPIType(def rval) (*rtype, error) { return t, nil } -func rsapiValues(a *attr, typ string) { - inner := strings.TrimSpace(typ) - if strings.HasPrefix(inner, "Optional[") && strings.HasSuffix(inner, "]") { - inner = strings.TrimSpace(inner[len("Optional[") : len(inner)-1]) +// rsapiValues adds the values puppet-resource_api's ValueCreator.create_values defines for typ. +func rsapiValues(a *attr, typ string) error { + base, err := parsePType(typ) + if err != nil { + return err } - base, _, _ := strings.Cut(inner, "[") - switch strings.TrimSpace(base) { + switch base { case "String": a.addValue("", ®ex{}) case "Boolean": @@ -1552,4 +1789,74 @@ func rsapiValues(a *attr, typ string) { a.addValue("absent", nil) a.addValue("present", nil) } + return nil +} + +// providerOf returns the name and symbol parent of the one top-level Puppet::Type.type(:typ).provide call in a provider file, +// or no name when the file makes no provide call; any other Puppet::Type statement or provide call is an error. +func providerOf(src, typ string) (name, parent string, err error) { + defer guard(&err) + toks, err := lex(src) + if err != nil { + return "", "", err + } + p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}} + calls := 0 + for i, t := range toks { + if t.kind == tIdent && t.text == "provide" && i > 0 && toks[i-1].text == "." { + calls++ + } + } + stmt := func() (bool, error) { + if !p.is(tConst, "Puppet") || p.at(1).text != "::" || p.at(2).text != "Type" { + return false, nil + } + if name != "" || p.at(3).text != "." || p.at(4).text != "type" || p.at(5).text != "(" { + return true, fmt.Errorf("unsupported %s", p.construct()) + } + p.i += 5 + args, err := p.args() + if err != nil { + return true, err + } + if len(args) != 1 || args[0].k != vSym && args[0].k != vStr || args[0].s != typ { + return true, fmt.Errorf("provide must target Puppet::Type.type(:%s)", typ) + } + if !p.op(".") || p.at(1).text != "provide" { + return true, fmt.Errorf("unsupported %s", p.construct()) + } + p.i += 2 + if args, err = p.args(); err != nil { + return true, err + } + if len(args) == 0 || len(args) > 2 || args[0].k != vSym && args[0].k != vStr || len(args) == 2 && args[1].k != vHash { + return true, fmt.Errorf("unsupported provide arguments") + } + name = args[0].s + if len(args) == 2 { + if err := symHash(args[1], "provide "+name); err != nil { + return true, err + } + if v, ok := args[1].get("parent"); ok { + switch v.k { + case vSym, vStr: + parent = v.s + case vConst: + default: + return true, fmt.Errorf("unsupported provider parent %s", v.kindName()) + } + } + } + if p.is(tIdent, "do") || p.op("{") { + return true, p.skipBlock() + } + return true, nil + } + if err := p.body("", stmt); err != nil { + return "", "", p.wrap(err) + } + if name == "" && calls > 0 || name != "" && calls != 1 { + return "", "", fmt.Errorf("unsupported provide call") + } + return name, parent, nil } diff --git a/internal/gentypes/ptype.go b/internal/gentypes/ptype.go new file mode 100644 index 0000000..d8f4969 --- /dev/null +++ b/internal/gentypes/ptype.go @@ -0,0 +1,334 @@ +package gentypes + +import ( + "fmt" + "math/big" + "regexp" + "regexp/syntax" + "strconv" + "strings" +) + +// ptype is a Resource API type string parsed the way Puppet::Pops::Types::TypeParser does, +// limited to the forms whose result puppet-resource_api's ValueCreator.create_values can be decided for. +type ptype struct { + name string + canon string + kids []*ptype +} + +type tparser struct { + s string + pos int +} + +var ( + intLit = regexp.MustCompile(`^(?:0|[1-9][0-9]*)$`) + floatLit = regexp.MustCompile(`^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$`) + enumWord = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) + typeName = regexp.MustCompile(`^[A-Z][A-Za-z0-9_]*`) + puppetKws = set("and application attr case class consumes default define else elsif environment false function if import in inherits node or private produces site true type undef unless plan apply") + // Onigmo syntax RE2 accepts with another meaning, or accepts where Ruby raises. + reUnsafe = regexp.MustCompile(`\(\?P|\(\?[imsU-]*[sU]|\\[pPxQEC0-9]|\[\^?\]`) +) + +// parsePType returns the value category ValueCreator sees after unwrapping one Optional: +// String, Boolean, Integer, Float, Numeric, or "" for any other type. +func parsePType(s string) (string, error) { + p := &tparser{s: s} + t, err := p.typ(0) + if err != nil { + return "", fmt.Errorf("type %q: %w", s, err) + } + if p.skip(); p.pos != len(p.s) { + return "", fmt.Errorf("type %q: unsupported trailing input", s) + } + if t, err = normalize(t); err != nil { + return "", fmt.Errorf("type %q: %w", s, err) + } + if t.name == "Optional" { + if len(t.kids) == 0 { + return "", nil + } + t = t.kids[0] + } + switch t.name { + case "String", "Boolean", "Integer", "Float", "Numeric": + return t.name, nil + } + return "", nil +} + +// normalize mirrors PVariantType.maybe_create: flatten nested variants, drop eql duplicates, collapse a single member. +// Members are only known eql when their canonical text matches, so a choice it cannot decide is an error. +func normalize(t *ptype) (*ptype, error) { + switch t.name { + case "Optional": + if len(t.kids) == 0 { + return t, nil + } + k, err := normalize(t.kids[0]) + if err != nil { + return nil, err + } + return &ptype{name: "Optional", canon: "Optional[" + k.canon + "]", kids: []*ptype{k}}, nil + case "Variant": + if len(t.kids) == 0 { + return t, nil + } + var members []*ptype + seen := map[string]bool{} + for _, k := range t.kids { + k, err := normalize(k) + if err != nil { + return nil, err + } + flat := []*ptype{k} + if k.name == "Variant" && len(k.kids) > 0 { + flat = k.kids + } + for _, m := range flat { + if !seen[m.canon] { + seen[m.canon] = true + members = append(members, m) + } + } + } + if len(members) == 1 { + return members[0], nil + } + for i, a := range members { + for _, b := range members[i+1:] { + if a.name == b.name && a.name != "" { + return nil, fmt.Errorf("cannot tell whether %s and %s are the same type", a.canon, b.canon) + } + } + } + canon := make([]string, len(members)) + for i, m := range members { + canon[i] = m.canon + } + return &ptype{name: "Variant", canon: "Variant[" + strings.Join(canon, ",") + "]", kids: members}, nil + } + return t, nil +} + +func (p *tparser) skip() { + for p.pos < len(p.s) && strings.IndexByte(" \t\r\n", p.s[p.pos]) >= 0 { + p.pos++ + } +} + +func (p *tparser) peek() byte { + p.skip() + if p.pos < len(p.s) { + return p.s[p.pos] + } + return 0 +} + +type targ struct { + t *ptype + text string + kind byte // 't' type, 'i' integer, 'f' float, 'd' default, 's' string, 'w' word, 'r' regex +} + +func (p *tparser) typ(depth int) (*ptype, error) { + if depth > maxDepth { + return nil, fmt.Errorf("nesting deeper than %d: %w", maxDepth, errLimit) + } + p.skip() + name := typeName.FindString(p.s[p.pos:]) + if name == "" || p.pos+len(name) < len(p.s) && p.s[p.pos+len(name)] == ':' { + return nil, fmt.Errorf("unsupported type at offset %d", p.pos) + } + p.pos += len(name) + var args []targ + hasArgs := p.peek() == '[' + if hasArgs { + p.pos++ + for { + if p.peek() == ']' { + p.pos++ + break + } + a, err := p.arg(depth) + if err != nil { + return nil, err + } + args = append(args, a) + if c := p.peek(); c == ',' { + p.pos++ + } else if c != ']' { + return nil, fmt.Errorf("expected , or ] at offset %d", p.pos) + } + } + if len(args) == 0 { + return nil, fmt.Errorf("%s[] takes parameters", name) + } + } + t := &ptype{name: name} + kinds := "" + texts := make([]string, len(args)) + for i, a := range args { + kinds += string(a.kind) + texts[i] = a.text + if a.t != nil { + t.kids = append(t.kids, a.t) + } + } + t.canon = name + if hasArgs { + t.canon += "[" + strings.Join(texts, ",") + "]" + } + ok := false + switch name { + case "String": + ok = rangeArgs(kinds, args, false) + case "Integer": + ok = rangeArgs(kinds, args, false) + case "Float": + ok = rangeArgs(kinds, args, true) + case "Numeric", "Boolean": + ok = !hasArgs + case "Optional": + ok = kinds == "" || kinds == "t" || kinds == "s" + if kinds == "s" { + t.kids = []*ptype{{name: "String", canon: "String[" + texts[0] + "]"}} + } + case "Variant": + ok = !strings.ContainsFunc(kinds, func(r rune) bool { return r != 't' }) + case "Enum", "Pattern", "Array", "Hash", "Sensitive": + t.name = "" + switch name { + case "Enum": + ok = hasArgs && !strings.ContainsFunc(kinds, func(r rune) bool { return r != 's' && r != 'w' }) + case "Pattern": + ok = hasArgs && !strings.ContainsFunc(kinds, func(r rune) bool { return r != 's' && r != 'r' }) + for i, a := range args { + if a.kind == 's' && !rubyRegexp(unquote(texts[i])) { + return nil, fmt.Errorf("unsupported regex %s", texts[i]) + } + } + case "Array": + ok = kinds == "" || len(kinds) <= 3 && kinds[0] == 't' && rangeArgs(kinds[1:], args[1:], false) + case "Hash": + ok = kinds == "" || kinds == "tt" || len(kinds) == 4 && kinds[:2] == "tt" && rangeArgs(kinds[2:], args[2:], false) + case "Sensitive": + ok = kinds == "" || kinds == "t" + } + } + if !ok { + return nil, fmt.Errorf("unsupported %s", t.canon) + } + return t, nil +} + +// rangeArgs accepts [], [min] and [min, max] of integers (or floats) and default, rejecting min > max as TypeParser does. +func rangeArgs(kinds string, args []targ, float bool) bool { + if len(kinds) > 2 || strings.ContainsFunc(kinds, func(r rune) bool { return r != 'i' && r != 'd' && (!float || r != 'f') }) { + return false + } + if kinds != "ii" && kinds != "if" && kinds != "fi" && kinds != "ff" { + return true + } + a, _, err1 := big.ParseFloat(args[0].text, 10, 256, big.ToNearestEven) + b, _, err2 := big.ParseFloat(args[1].text, 10, 256, big.ToNearestEven) + return err1 == nil && err2 == nil && a.Cmp(b) <= 0 +} + +func (p *tparser) arg(depth int) (targ, error) { + c := p.peek() + switch { + case c >= 'A' && c <= 'Z': + t, err := p.typ(depth + 1) + if err != nil { + return targ{}, err + } + return targ{t: t, text: t.canon, kind: 't'}, nil + case c == '-' || c >= '0' && c <= '9': + neg := c == '-' + if neg { + p.pos++ + p.skip() + } + s := p.pos + for p.pos < len(p.s) { + c := p.s[p.pos] + sign := c == '+' || c == '-' + if strings.IndexByte("0123456789.eE_xXabcdefABCDEF", c) < 0 && (!sign || p.pos == s || p.s[p.pos-1] != 'e' && p.s[p.pos-1] != 'E') { + break + } + p.pos++ + } + text := p.s[s:p.pos] + if neg { + text = "-" + text + } + switch { + case intLit.MatchString(strings.TrimPrefix(text, "-")): + if _, err := strconv.ParseInt(text, 10, 64); err != nil { + return targ{}, fmt.Errorf("unsupported integer %s", text) + } + return targ{text: text, kind: 'i'}, nil + case floatLit.MatchString(strings.TrimPrefix(text, "-")): + return targ{text: text, kind: 'f'}, nil + } + return targ{}, fmt.Errorf("unsupported number %s", text) + case c == '\'': + s := p.pos + for p.pos++; p.pos < len(p.s) && p.s[p.pos] != '\''; p.pos++ { + if p.s[p.pos] == '\\' { + p.pos++ + } + } + if p.pos >= len(p.s) { + return targ{}, fmt.Errorf("unterminated string") + } + p.pos++ + return targ{text: p.s[s:p.pos], kind: 's'}, nil + case c == '/': + s := p.pos + for p.pos++; p.pos < len(p.s) && p.s[p.pos] != '/'; p.pos++ { + if p.s[p.pos] == '\\' { + p.pos++ + } + } + if p.pos >= len(p.s) { + return targ{}, fmt.Errorf("unterminated regex") + } + p.pos++ + text := p.s[s:p.pos] + if !rubyRegexp(strings.ReplaceAll(text[1:len(text)-1], `\/`, "/")) { + return targ{}, fmt.Errorf("unsupported regex %s", text) + } + return targ{text: text, kind: 'r'}, nil + case c >= 'a' && c <= 'z': + s := p.pos + for p.pos < len(p.s) && (isIdentChar(p.s[p.pos]) && p.s[p.pos] < 0x80) { + p.pos++ + } + w := p.s[s:p.pos] + switch { + case w == "default": + return targ{text: w, kind: 'd'}, nil + case enumWord.MatchString(w) && !puppetKws[w] && p.peek() != ':': + return targ{text: "'" + w + "'", kind: 'w'}, nil + } + return targ{}, fmt.Errorf("unsupported word %s", w) + } + return targ{}, fmt.Errorf("unsupported parameter at offset %d", p.pos) +} + +func unquote(s string) string { + return strings.NewReplacer(`\\`, `\`, `\'`, `'`).Replace(s[1 : len(s)-1]) +} + +// rubyRegexp reports whether Ruby's Regexp.new surely accepts src: RE2 parses it and it avoids syntax the engines disagree on. +func rubyRegexp(src string) bool { + if reUnsafe.MatchString(src) { + return false + } + _, err := syntax.Parse(src, syntax.Perl) + return err == nil +} diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_class/posix.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_class/posix.rb new file mode 100644 index 0000000..82ae5a5 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_class/posix.rb @@ -0,0 +1,2 @@ +class Puppet::Provider::RProvClass +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_empty/posix.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_empty/posix.rb new file mode 100644 index 0000000..e69de29 diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_name/posix.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_name/posix.rb new file mode 100644 index 0000000..1b2939e --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_name/posix.rb @@ -0,0 +1,3 @@ +Puppet::Type.type(:r_prov_name).provide(:other) do + desc '' +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent/a.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent/a.rb new file mode 100644 index 0000000..6cb87d7 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent/a.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:r_prov_parent).provide(:a) do +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent/b.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent/b.rb new file mode 100644 index 0000000..37d66a4 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent/b.rb @@ -0,0 +1,3 @@ +require 'json' +Puppet::Type.type(:r_prov_parent).provide :b, parent: :a do +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent_missing/a.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent_missing/a.rb new file mode 100644 index 0000000..a2869a5 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/provider/r_prov_parent_missing/a.rb @@ -0,0 +1,2 @@ +Puppet::Type.type(:r_prov_parent_missing).provide(:a, parent: :nope) do +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_bare.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_bare.rb new file mode 100644 index 0000000..bb62a8a --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_bare.rb @@ -0,0 +1,3 @@ +Type.newtype(:r_bare) do + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_begin.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_begin.rb new file mode 100644 index 0000000..9d6f02a --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_begin.rb @@ -0,0 +1,10 @@ +begin + require 'ipaddr' +rescue LoadError => e + Puppet.warning("#{__FILE__}: #{e}") +end +DOC = 'Literal doc.'.freeze +Puppet::Type.newtype(:r_begin) do + @doc = DOC + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_const_call.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_const_call.rb new file mode 100644 index 0000000..c0b158a --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_const_call.rb @@ -0,0 +1,4 @@ +X = File.join('a', 'b') +Puppet::Type.newtype(:r_const_call) do + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dollar.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dollar.rb new file mode 100644 index 0000000..074444b --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dollar.rb @@ -0,0 +1,4 @@ +Puppet::Type.newtype(:r_dollar) do + newparam(:name, namevar: true) +end +$ \ No newline at end of file diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_ensure.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_ensure.rb new file mode 100644 index 0000000..785aa61 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_ensure.rb @@ -0,0 +1,5 @@ +Puppet::Type.newtype(:r_dup_ensure) do + newparam(:name, namevar: true) + ensurable + newproperty(:ensure) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_param.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_param.rb new file mode 100644 index 0000000..d5084ff --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_param.rb @@ -0,0 +1,5 @@ +Puppet::Type.newtype(:r_dup_param) do + newparam(:name, namevar: true) + newparam(:a) + newparam(:a) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_prop.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_prop.rb new file mode 100644 index 0000000..b84ec58 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_dup_prop.rb @@ -0,0 +1,5 @@ +Puppet::Type.newtype(:r_dup_prop) do + newparam(:name, namevar: true) + newproperty(:a) + newproperty(:a) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_feature_const.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_feature_const.rb new file mode 100644 index 0000000..caa15c1 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_feature_const.rb @@ -0,0 +1,4 @@ +Puppet::Type.newtype(:r_feature_const) do + feature :x, 'doc', methods: [RNope] + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_helper.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_helper.rb new file mode 100644 index 0000000..53f8339 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_helper.rb @@ -0,0 +1,9 @@ +module RHelper + def self.add(type) + type.newparam(:extra) + end +end +Puppet::Type.newtype(:r_helper) do + newparam(:name, namevar: true) +end +RHelper.add(Puppet::Type.type(:r_helper)) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_include_noreq.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_include_noreq.rb new file mode 100644 index 0000000..9a335a3 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_include_noreq.rb @@ -0,0 +1,4 @@ +Puppet::Type.newtype(:r_include_noreq) do + include PuppetX::Review::Mix + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_include_req.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_include_req.rb new file mode 100644 index 0000000..1b29a2d --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_include_req.rb @@ -0,0 +1,6 @@ +require 'puppet_x/review/mix' +Puppet::Type.newtype(:r_include_req) do + include PuppetX::Review::Mix + newparam(:name, namevar: true) + newproperty(:a) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_inline_provide.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_inline_provide.rb new file mode 100644 index 0000000..73235a5 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_inline_provide.rb @@ -0,0 +1,4 @@ +Puppet::Type.newtype(:r_inline_provide) do + newparam(:name, namevar: true) +end +Puppet::Type.type(:r_inline_provide).provide(:inline) {} diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_compact.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_compact.rb new file mode 100644 index 0000000..03e9175 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_compact.rb @@ -0,0 +1,5 @@ +module Puppet::RCompact + Type.newtype(:r_mod_compact) do + newparam(:name, namevar: true) + end +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_foo.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_foo.rb new file mode 100644 index 0000000..13eb00b --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_foo.rb @@ -0,0 +1,5 @@ +module RFoo + Type.newtype(:r_mod_foo) do + newparam(:name, namevar: true) + end +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_puppet.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_puppet.rb new file mode 100644 index 0000000..b3f3f15 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_mod_puppet.rb @@ -0,0 +1,5 @@ +module Puppet + Type.newtype(:r_mod_puppet) do + newparam(:name, namevar: true) + end +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_param_prop.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_param_prop.rb new file mode 100644 index 0000000..59a3882 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_param_prop.rb @@ -0,0 +1,5 @@ +Puppet::Type.newtype(:r_param_prop) do + newparam(:name, namevar: true) + newparam(:a) + newproperty(:a) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_class.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_class.rb new file mode 100644 index 0000000..b8f3514 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_class.rb @@ -0,0 +1,3 @@ +Puppet::Type.newtype(:r_prov_class) do + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_empty.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_empty.rb new file mode 100644 index 0000000..51b8e8a --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_empty.rb @@ -0,0 +1,3 @@ +Puppet::Type.newtype(:r_prov_empty) do + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_name.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_name.rb new file mode 100644 index 0000000..228eb3b --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_name.rb @@ -0,0 +1,3 @@ +Puppet::Type.newtype(:r_prov_name) do + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_parent.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_parent.rb new file mode 100644 index 0000000..c8ace59 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_parent.rb @@ -0,0 +1,3 @@ +Puppet::Type.newtype(:r_prov_parent) do + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_parent_missing.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_parent_missing.rb new file mode 100644 index 0000000..0f56dc9 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_prov_parent_missing.rb @@ -0,0 +1,3 @@ +Puppet::Type.newtype(:r_prov_parent_missing) do + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_require_missing.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_require_missing.rb new file mode 100644 index 0000000..2239155 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_require_missing.rb @@ -0,0 +1,4 @@ +require 'puppet_x/review/nope' +Puppet::Type.newtype(:r_require_missing) do + newparam(:name, namevar: true) +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_lower.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_lower.rb new file mode 100644 index 0000000..10c9c0d --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_lower.rb @@ -0,0 +1,8 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'r_rs_bad_lower', + attributes: { + name: { type: 'String', desc: 'n', behaviour: :namevar }, + a: { type: 'string', desc: 'a' }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_range.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_range.rb new file mode 100644 index 0000000..1cd0aa1 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_range.rb @@ -0,0 +1,8 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'r_rs_bad_range', + attributes: { + name: { type: 'String', desc: 'n', behaviour: :namevar }, + a: { type: 'Integer[5,1]', desc: 'a' }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_regex.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_regex.rb new file mode 100644 index 0000000..3ba5eb7 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_regex.rb @@ -0,0 +1,8 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'r_rs_bad_regex', + attributes: { + name: { type: 'String', desc: 'n', behaviour: :namevar }, + a: { type: 'Pattern[/(/]', desc: 'a' }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_uncertain.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_uncertain.rb new file mode 100644 index 0000000..d9de97d --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_uncertain.rb @@ -0,0 +1,8 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'r_rs_bad_uncertain', + attributes: { + name: { type: 'String', desc: 'n', behaviour: :namevar }, + a: { type: 'Variant[String, String[0]]', desc: 'a' }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_undef.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_undef.rb new file mode 100644 index 0000000..8566bf1 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_undef.rb @@ -0,0 +1,8 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'r_rs_bad_undef', + attributes: { + name: { type: 'String', desc: 'n', behaviour: :namevar }, + a: { type: 'Variant[String, Undef]', desc: 'a' }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_words.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_words.rb new file mode 100644 index 0000000..563c1fb --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_bad_words.rb @@ -0,0 +1,8 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'r_rs_bad_words', + attributes: { + name: { type: 'String', desc: 'n', behaviour: :namevar }, + a: { type: 'Enum[if]', desc: 'a' }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_str_feature.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_str_feature.rb new file mode 100644 index 0000000..1ac723d --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_str_feature.rb @@ -0,0 +1,8 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'r_rs_str_feature', + features: ['custom_insync'], + attributes: { + name: { type: 'String', desc: 'n', behaviour: :namevar }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_str_key.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_str_key.rb new file mode 100644 index 0000000..7fea364 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_str_key.rb @@ -0,0 +1,7 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + 'name' => 'r_rs_str_key', + 'attributes' => { + 'name' => { 'type' => 'String', 'behaviour' => :namevar }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_sym_feature.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_sym_feature.rb new file mode 100644 index 0000000..70d62d4 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_sym_feature.rb @@ -0,0 +1,8 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'r_rs_sym_feature', + features: [:custom_insync], + attributes: { + name: { type: 'String', desc: 'n', behaviour: :namevar }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_types.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_types.rb new file mode 100644 index 0000000..a9baab3 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_rs_types.rb @@ -0,0 +1,18 @@ +require 'puppet/resource_api' +Puppet::ResourceApi.register_type( + name: 'r_rs_types', + attributes: { + name: { type: 'String', desc: 'n', behaviour: :namevar }, + a: { type: 'Variant[String]', desc: 'a' }, + b: { type: 'Optional[Variant[Integer]]', desc: 'b' }, + c: { type: 'Variant[Optional[String]]', desc: 'c' }, + d: { type: 'Variant[Integer[ 1 , 2 ], Integer[1,2]]', desc: 'd' }, + e: { type: "Optional['x']", desc: 'e' }, + f: { type: 'Optional[Optional[String]]', desc: 'f' }, + g: { type: 'Optional[Variant[String[1], Integer]]', desc: 'g' }, + h: { type: 'Variant[Float[0.5, 1], Numeric]', desc: 'h' }, + i: { type: 'Optional[Variant[Pattern[/^a\/b$/], Array[Enum[x, \'y\']]]]', desc: 'i' }, + j: { type: 'Integer[-5,default]', desc: 'j' }, + k: { type: 'Variant[Boolean,Boolean]', desc: 'k' }, + }, +) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_send.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_send.rb new file mode 100644 index 0000000..9ea1dea --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_send.rb @@ -0,0 +1,4 @@ +Puppet::Type.newtype(:r_send) do + newparam(:name, namevar: true) +end +Puppet::Type.type(:r_send).send(:newparam, :extra) diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_str_keys.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_str_keys.rb new file mode 100644 index 0000000..c0e33e1 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet/type/r_str_keys.rb @@ -0,0 +1,6 @@ +require 'puppet/parameter/boolean' +Puppet::Type.newtype(:r_str_keys) do + newparam(:path, 'namevar' => true) + newparam(:flag, 'parent' => Puppet::Parameter::Boolean) + newproperty(:p, 'required_features' => 'feat') +end diff --git a/internal/gentypes/testdata/env/modules/review/lib/puppet_x/review/mix.rb b/internal/gentypes/testdata/env/modules/review/lib/puppet_x/review/mix.rb new file mode 100644 index 0000000..2a6bd69 --- /dev/null +++ b/internal/gentypes/testdata/env/modules/review/lib/puppet_x/review/mix.rb @@ -0,0 +1,10 @@ +module PuppetX + module Review + module Mix + VERSION = '1' + def exists?; end + def create; end + def destroy; end + end + end +end diff --git a/internal/gentypes/testdata/golden/r_begin.pp b/internal/gentypes/testdata/golden/r_begin.pp new file mode 100644 index 0000000..05035c6 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_begin.pp @@ -0,0 +1,17 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# Literal doc. +Puppet::Resource::ResourceType3.new( + 'r_begin', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_const_call.pp b/internal/gentypes/testdata/golden/r_const_call.pp new file mode 100644 index 0000000..68f0787 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_const_call.pp @@ -0,0 +1,16 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_const_call', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_helper.pp b/internal/gentypes/testdata/golden/r_helper.pp new file mode 100644 index 0000000..7bd369a --- /dev/null +++ b/internal/gentypes/testdata/golden/r_helper.pp @@ -0,0 +1,18 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_helper', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true), + + Puppet::Resource::Param(Any, 'extra') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_include_req.pp b/internal/gentypes/testdata/golden/r_include_req.pp new file mode 100644 index 0000000..dceda2a --- /dev/null +++ b/internal/gentypes/testdata/golden/r_include_req.pp @@ -0,0 +1,21 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_include_req', + [ + # The basic property that the resource should be in. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + Puppet::Resource::Param(Any, 'a') + ], + [ + Puppet::Resource::Param(Any, 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_inline_provide.pp b/internal/gentypes/testdata/golden/r_inline_provide.pp new file mode 100644 index 0000000..f7e19f5 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_inline_provide.pp @@ -0,0 +1,24 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_inline_provide', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true), + + # The specific backend to use for this `r_inline_provide` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # inline + # : + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_mod_puppet.pp b/internal/gentypes/testdata/golden/r_mod_puppet.pp new file mode 100644 index 0000000..8dea27f --- /dev/null +++ b/internal/gentypes/testdata/golden/r_mod_puppet.pp @@ -0,0 +1,16 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_mod_puppet', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_param_prop.pp b/internal/gentypes/testdata/golden/r_param_prop.pp new file mode 100644 index 0000000..b608742 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_param_prop.pp @@ -0,0 +1,18 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_param_prop', + [ + Puppet::Resource::Param(Any, 'a') + ], + [ + Puppet::Resource::Param(Any, 'name', true), + + Puppet::Resource::Param(Any, 'a') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_prov_class.pp b/internal/gentypes/testdata/golden/r_prov_class.pp new file mode 100644 index 0000000..444c08b --- /dev/null +++ b/internal/gentypes/testdata/golden/r_prov_class.pp @@ -0,0 +1,16 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_prov_class', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_prov_empty.pp b/internal/gentypes/testdata/golden/r_prov_empty.pp new file mode 100644 index 0000000..c0d2f25 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_prov_empty.pp @@ -0,0 +1,16 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_prov_empty', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_prov_name.pp b/internal/gentypes/testdata/golden/r_prov_name.pp new file mode 100644 index 0000000..f16dc3b --- /dev/null +++ b/internal/gentypes/testdata/golden/r_prov_name.pp @@ -0,0 +1,24 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_prov_name', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true), + + # The specific backend to use for this `r_prov_name` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # other + # : + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_prov_parent.pp b/internal/gentypes/testdata/golden/r_prov_parent.pp new file mode 100644 index 0000000..49f47b8 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_prov_parent.pp @@ -0,0 +1,27 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_prov_parent', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true), + + # The specific backend to use for this `r_prov_parent` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # a + # : + # + # b + # : + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_rs_bad_uncertain.pp b/internal/gentypes/testdata/golden/r_rs_bad_uncertain.pp new file mode 100644 index 0000000..23c953e --- /dev/null +++ b/internal/gentypes/testdata/golden/r_rs_bad_uncertain.pp @@ -0,0 +1,20 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_rs_bad_uncertain', + [ + # a (a Variant[String, String[0]]) + Puppet::Resource::Param(Any, 'a') + ], + [ + # n (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_rs_bad_undef.pp b/internal/gentypes/testdata/golden/r_rs_bad_undef.pp new file mode 100644 index 0000000..8b242e1 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_rs_bad_undef.pp @@ -0,0 +1,20 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_rs_bad_undef', + [ + # a (a Variant[String, Undef]) + Puppet::Resource::Param(Any, 'a') + ], + [ + # n (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_rs_str_feature.pp b/internal/gentypes/testdata/golden/r_rs_str_feature.pp new file mode 100644 index 0000000..d3f37ae --- /dev/null +++ b/internal/gentypes/testdata/golden/r_rs_str_feature.pp @@ -0,0 +1,20 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_rs_str_feature', + [ + # A hidden property which enables a type with custom insync to perform an insync check without specifying any insyncable properties (a Enum[do_not_specify_in_manifest]) + Puppet::Resource::Param(Any, 'rsapi_custom_insync_trigger') + ], + [ + # n (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_rs_sym_feature.pp b/internal/gentypes/testdata/golden/r_rs_sym_feature.pp new file mode 100644 index 0000000..cfecd22 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_rs_sym_feature.pp @@ -0,0 +1,19 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_rs_sym_feature', + [ + + ], + [ + # n (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_rs_types.pp b/internal/gentypes/testdata/golden/r_rs_types.pp new file mode 100644 index 0000000..eace816 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_rs_types.pp @@ -0,0 +1,64 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_rs_types', + [ + # a (a Variant[String]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'a'), + + # b (a Optional[Variant[Integer]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'b'), + + # c (a Variant[Optional[String]]) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'c'), + + # d (a Variant[Integer[ 1 , 2 ], Integer[1,2]]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'd'), + + # e (a Optional['x']) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'e'), + + # f (a Optional[Optional[String]]) + Puppet::Resource::Param(Any, 'f'), + + # g (a Optional[Variant[String[1], Integer]]) + Puppet::Resource::Param(Any, 'g'), + + # h (a Variant[Float[0.5, 1], Numeric]) + Puppet::Resource::Param(Any, 'h'), + + # i (a Optional[Variant[Pattern[/^a\/b$/], Array[Enum[x, 'y']]]]) + Puppet::Resource::Param(Any, 'i'), + + # j (a Integer[-5,default]) + # + # Values can match `/^-?\d+$/`. + Puppet::Resource::Param(Pattern[/^-?\d+$/], 'j'), + + # k (a Variant[Boolean,Boolean]) + # + # Valid values are `true` (also called `true, true`), `false` (also called `false, false`). + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']], 'k') + ], + [ + # n (a String) + # + # Values can match `//`. + Puppet::Resource::Param(Pattern[//], 'name', true) + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_send.pp b/internal/gentypes/testdata/golden/r_send.pp new file mode 100644 index 0000000..222228b --- /dev/null +++ b/internal/gentypes/testdata/golden/r_send.pp @@ -0,0 +1,18 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_send', + [ + + ], + [ + Puppet::Resource::Param(Any, 'name', true), + + Puppet::Resource::Param(Any, 'extra') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/r_str_keys.pp b/internal/gentypes/testdata/golden/r_str_keys.pp new file mode 100644 index 0000000..eef98f1 --- /dev/null +++ b/internal/gentypes/testdata/golden/r_str_keys.pp @@ -0,0 +1,18 @@ +# This file was automatically generated on 2026-11-08 20:40:47 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'r_str_keys', + [ + # Requires features feat. + Puppet::Resource::Param(Any, 'p') + ], + [ + Puppet::Resource::Param(Any, 'path'), + + Puppet::Resource::Param(Any, 'flag') + ], + { + }, + true, + false)