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)