diff --git a/internal/gentypes/eval.go b/internal/gentypes/eval.go index 6165da8..db4253d 100644 --- a/internal/gentypes/eval.go +++ b/internal/gentypes/eval.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "maps" + "regexp" "slices" "strconv" "strings" @@ -439,6 +440,17 @@ func (p *parser) atom() (rval, error) { case t.kind == tConst && t.text == "Regexp" && p.at(1).text == "." && p.at(2).text == "new" && p.coreConst("Regexp"): p.i += 3 return p.regexpNew() + case p.featuresCall(""): + p.i += 4 + name, _ := strings.CutSuffix(p.take().text, "?") + if p.op("(") && !p.cur().space { + return rval{}, fmt.Errorf("unsupported arguments to Puppet.features.%s?", name) + } + ok, err := p.featureTest(name) + if ok { + return rval{k: vTrue}, err + } + return rval{k: vFalse}, err case t.kind == tIdent && t.text == "defined?": return p.definedExpr() case isLocal(t) && (p.locals != nil || p.cls != nil): @@ -1253,3 +1265,96 @@ func (p *parser) typeProvider(v rval) (rval, error) { } return rval{k: vConst, s: "Puppet::Type::" + capitalize(v.s) + "::Provider" + capitalize(args[0].s)}, nil } + +// libName is a require path $LOAD_PATH resolves: no absolute, home or ./ path. +var libName = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]*(/[A-Za-z0-9_][A-Za-z0-9_.-]*)*$`) + +// openvoxFeatures are the features openvox 9.3.0 adds, whose results depend on the host. +var openvoxFeatures = set("bolt cfpropertylist dbus eventlog hiera hiera_eyaml hocon ldap libshadow libuser manages_symlinks microsoft_windows minitar msgpack openssl pe_license posix pson puppetserver_ca root selinux sqlite ssh syslog telnet usage zlib") + +// featuresCall matches Puppet.features. at the cursor, or Puppet.features.? for an empty m. +func (p *parser) featuresCall(m string) bool { + n := p.at(4) + return p.w != nil && p.is(tConst, "Puppet") && p.lexical("Puppet") == "Puppet" && p.at(1).text == "." && p.at(2).text == "features" && p.at(3).text == "." && n.kind == tIdent && + (m == "" && strings.HasSuffix(n.text, "?") && n.text != "?" || n.text == m) +} + +// featureAdd runs Puppet.features.add(:name, libs: lib or [libs]) without a block. +func (p *parser) featureAdd() error { + p.i += 5 + args, err := p.args() + if err != nil { + return err + } + if len(args) != 2 || args[0].k != vSym || args[1].k != vHash || len(args[1].keys) != 1 || p.is(tIdent, "do") || p.op("{") { + return fmt.Errorf("unsupported Puppet.features.add arguments") + } + libs, ok := args[1].get("libs") + if libs.k == vStr { + libs = rval{k: vArray, arr: []rval{libs}} + } + if !ok || libs.k != vArray || slices.ContainsFunc(libs.arr, func(l rval) bool { return l.k != vStr }) { + return fmt.Errorf("unsupported Puppet.features.add libs") + } + p.w.features[args[0].s] = nil + for _, l := range libs.arr { + p.w.features[args[0].s] = append(p.w.features[args[0].s], l.s) + } + return nil +} + +// featureTest ports Puppet.features.?: a missing method autoloads puppet/feature/.rb, and a feature with +// libs is true when requiring each loads, which for a gem holds only when it is declared. +func (p *parser) featureTest(name string) (bool, error) { + if openvoxFeatures[name] || coreLib("puppet/feature/"+name) { + return false, fmt.Errorf("feature %s? depends on the host", name) + } + if _, ok := p.w.features[name]; !ok { + if err := p.loadFeature(name); err != nil { + return false, err + } + } + libs, ok := p.w.features[name] + if !ok { + return false, nil + } + for _, lib := range libs { + if p.w.resolve == nil || !libName.MatchString(lib) || strings.Contains(lib, "..") { + return false, fmt.Errorf("feature %s?: require %q is not modelled", name, lib) + } + _, modelled := puppetLibs[lib] + _, gem, declared := p.w.gemFor(lib) + srcs, err := p.w.resolve(lib+".rb", "") + switch { + case err != nil: + return false, err + case len(srcs) > 0 || coreLib(lib) && !modelled && !rubyLibs[lib] || declared && gem.entry != lib: + return false, fmt.Errorf("feature %s?: require %q is not modelled", name, lib) + case !modelled && !rubyLibs[lib] && !declared: + return false, nil + } + if err := p.requireLib(lib, false); err != nil { + return false, err + } + } + return true, nil +} + +// loadFeature loads the first puppet/feature/.rb in module lib dirs, which every copy must match. +func (p *parser) loadFeature(name string) error { + if p.w.resolve == nil { + return fmt.Errorf("feature %s?: module sources are not available", name) + } + srcs, err := p.w.resolve("puppet/feature/"+name+".rb", "") + switch { + case err != nil: + return err + case len(srcs) == 0: + return nil + case slices.ContainsFunc(srcs, func(f libFile) bool { return f.src != srcs[0].src }): + return fmt.Errorf("feature %s?: module copies of its feature file differ", name) + case p.w.loaded[srcs[0].mod+"\x00"+srcs[0].rel]: + return fmt.Errorf("feature %s?: its feature file loads again", name) + } + return p.load(srcs[0]) +} diff --git a/internal/gentypes/fidelity_test.go b/internal/gentypes/fidelity_test.go index 8934309..a42bdac 100644 --- a/internal/gentypes/fidelity_test.go +++ b/internal/gentypes/fidelity_test.go @@ -1,6 +1,7 @@ package gentypes import ( + "maps" "os" "path/filepath" "strings" @@ -294,3 +295,44 @@ func TestCrossTypeSkips(t *testing.T) { }) } } + +const featureTypeSrc = "Puppet::Type.newtype(:t) do\n feature :fm, 'm', methods: [:m]\n feature :fk, 'k', methods: [:k]\n feature :fd, 'd', methods: [:lcs_diff]\n" + + " newparam(:name) { |_n| isnamevar }\n newproperty(:p) do |prop|\n include Puppet::Util\n desc 'p'\n end\n ensurable { |x| defaultvalues }\nend\n" + +func featureEnv(prov string, extra map[string]string) map[string]string { + files := map[string]string{"m/lib/puppet/type/t.rb": featureTypeSrc, "m/lib/puppet/provider/t/x.rb": prov, + "m/lib/puppet/feature/nolib.rb": "require 'puppet/util/feature'\nPuppet.features.add(:nolib, libs: ['no_such_lib_w10k'])\n", + "m/lib/puppet/feature/jsonf.rb": "Puppet.features.add(:jsonf, libs: 'json')\n", + "m/lib/puppet_x/m/mix.rb": "module PuppetX\n module M\n module Mix\n def m; end\n private :m\n def k; end\n end\n end\nend\n"} + maps.Copy(files, extra) + return files +} + +// A provider gated on module features, with core and module mixins, loads in openvox 9.3.0 and documents want. +func TestFidelityFeatures(t *testing.T) { + env := fidelityEnv(t, featureEnv("require 'zzz_absent' if Puppet.features.nolib?\nrequire 'json' if Puppet.features.jsonf?\n"+ + "require 'zzz_absent2' if Puppet.features.undefined_feat?\nrequire 'puppet/util/diff'\nrequire 'puppet_x/m/mix'\n"+ + "Puppet::Type.type(:t).provide(:x) do\n include Puppet::Util::Diff\n include PuppetX::M::Mix\n desc 'x'\nend\n", nil)) + if b := readFile(t, filepath.Join(env, OutDir, "t.pp")); !strings.Contains(b, " # x\n # : x\n # \n # * Supported features: `fd`, `fk`.\n") { + t.Fatalf("t.pp lacks the provider doc:\n%s", b) + } +} + +// Each provider is gated on a feature that makes puppet fail to load it or that w10k cannot evaluate, so w10k skips. +func TestFeatureSkips(t *testing.T) { + for name, files := range map[string]map[string]string{ + "true feature requires a missing lib": featureEnv("require 'zzz_absent' if Puppet.features.jsonf?\nPuppet::Type.type(:t).provide(:x) do\nend\n", nil), + "false feature unless": featureEnv("require 'zzz_absent' unless Puppet.features.nolib?\nPuppet::Type.type(:t).provide(:x) do\nend\n", nil), + "openvox feature": featureEnv("require 'json' if Puppet.features.posix?\nPuppet::Type.type(:t).provide(:x) do\nend\n", nil), + "feature file copies differ": featureEnv("require 'json' if Puppet.features.dup?\nPuppet::Type.type(:t).provide(:x) do\nend\n", + map[string]string{"m/lib/puppet/feature/dup.rb": "Puppet.features.add(:dup, libs: ['json'])\n", "n/lib/puppet/feature/dup.rb": "Puppet.features.add(:dup, libs: ['set'])\n"}), + "feature lib a module provides": featureEnv("require 'json' if Puppet.features.modlib?\nPuppet::Type.type(:t).provide(:x) do\nend\n", + map[string]string{"m/lib/puppet/feature/modlib.rb": "Puppet.features.add(:modlib, libs: ['mylib'])\n", "m/lib/mylib.rb": "raise 'x'\n"}), + } { + t.Run(name, func(t *testing.T) { + if exists(filepath.Join(fidelityEnv(t, files), OutDir, "t.pp")) { + t.Fatal("t.pp written") + } + }) + } +} diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index b0da310..2cf5a68 100644 --- a/internal/gentypes/generate.go +++ b/internal/gentypes/generate.go @@ -18,7 +18,7 @@ import ( const OutDir = ".resource_types" // Version changes whenever generated output can change, so deploys rebuild typed environments. -const Version = "11" +const Version = "12" var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) diff --git a/internal/gentypes/generate_test.go b/internal/gentypes/generate_test.go index da7885f..2343f56 100644 --- a/internal/gentypes/generate_test.go +++ b/internal/gentypes/generate_test.go @@ -679,7 +679,7 @@ func TestTypeBodyRejectsUnknownStatements(t *testing.T) { "validate(compute) do\n end": "validate: unsupported expression", "newparam(:b) do\n defaultto Facter.value(:x)\n end": `unsupported "." after "defaultto"`, "newparam(:b) do\n def self.doc; end\n end": "unsupported def self.doc in attribute b", - "newparam(:b) do\n include Foo\n end": "unsupported include Foo in attribute b", + "newparam(:b) do\n include Foo\n end": "include Foo: no require defines it as a module", "newparam(:b) do\n @doc2 = 'x'\n end": "unsupported @doc2 in attribute b", "newparam(:b) do\n newvalues(:a) if x\n end": `unsupported "if" after "newvalues"`, "newparam(:b) do\n if defined? X\n desc 'x'\n end\n end": "unsupported conditional desc", @@ -702,6 +702,8 @@ func TestMixinMethods(t *testing.T) { "module PuppetX::M::Mix\n include Other\nend\n": "unsupported include Other in mixin", "module PuppetX::M::Mix\n extend ActiveSupport::Concern\nend\n": "unsupported extend", "module PuppetX::M\nend\n": "not defined", + "module PuppetX::M::Mix\n def a; end\n def b; end\n private :a, :b\n public :b\n def c; end\nend\n": "b c", + "module PuppetX::M::Mix\n private :a\nend\n": "private: undefined method a", } { got, err := mixinMethods(src, path) if g := strings.Join(got, " "); err != nil && !strings.Contains(err.Error(), want) || err == nil && g != want { diff --git a/internal/gentypes/load.go b/internal/gentypes/load.go index 2da6c9d..8a8b00b 100644 --- a/internal/gentypes/load.go +++ b/internal/gentypes/load.go @@ -36,6 +36,8 @@ type world struct { // provFiles are the provider files by type; types are the types Puppet::Type.type returns, nil where none loads provFiles map[string][]string types map[string]*loadedType + // features are the libs of each Puppet.features.add a loaded file ran + features map[string][]string } // loadedType is a type newtype stored; provs is set once its providerloader.loadall finished. @@ -68,7 +70,7 @@ var startup = func() map[string]byte { }() func newWorld(resolve Resolver) *world { - w := &world{resolve: resolve, defined: map[string]bool{}, kind: map[string]byte{}, sup: map[string]string{}, user: map[string]bool{}, mods: map[string][]string{}, loaded: map[string]bool{}, classes: map[string]*classCtx{}, tclasses: map[string]bool{}, types: map[string]*loadedType{}} + w := &world{resolve: resolve, defined: map[string]bool{}, kind: map[string]byte{}, sup: map[string]string{}, user: map[string]bool{}, mods: map[string][]string{}, loaded: map[string]bool{}, classes: map[string]*classCtx{}, tclasses: map[string]bool{}, types: map[string]*loadedType{}, features: map[string][]string{}} for c, k := range startup { w.define(c, k) } @@ -229,6 +231,8 @@ func (p *parser) fileStmt(prov func() (bool, error)) func() (bool, error) { return true, p.strictConstAssign() case t.kind == tGVar && t.text == "$LOAD_PATH" && p.at(1).text == "." && p.at(2).text == "unshift": return true, p.unshift() + case p.featuresCall("add"): + return true, p.featureAdd() case prov != nil: if ok, err := prov(); ok || err != nil { return true, err @@ -621,12 +625,22 @@ func (p *parser) alias(c *classCtx) error { return c.addMethod(to, c.hidden[from]) } +// coreMixins are openvox 9.3.0 modules without include hooks, with their public instance methods. +var coreMixins = map[string][]string{"Puppet::Util": nil, "Puppet::Util::Diff": {"lcs_diff", "string_file_diff"}, "Puppet::Util::Package": nil} + +func coreMixin(m string) bool { + _, ok := coreMixins[m] + return ok +} + // mixin returns the public instance methods of module m, which one loaded file must define without include hooks. func (p *parser) mixin(m string) ([]string, error) { r := p.lexical(m) switch { case r == "Enumerable" || r == "Comparable": return nil, nil + case coreMixin(r) && p.w.defined[r]: + return coreMixins[r], nil case r == "" || p.w.kind[r] != kMod: return nil, fmt.Errorf("include %s: no require defines it as a module", m) case len(p.w.mods[r]) == 0: diff --git a/internal/gentypes/parse.go b/internal/gentypes/parse.go index 6e3d513..243d7ab 100644 --- a/internal/gentypes/parse.go +++ b/internal/gentypes/parse.go @@ -472,7 +472,7 @@ var fileConsts = []string{"Puppet::Parameter::Boolean c", "Puppet::Property::Boo // Libraries a type file may require without changing its type, present in openvox 9.3.0 and its Ruby; // puppetLibs maps each to the constants ("name kind") it defines beyond those loaded at startup. var ( - rubyLibs = set("English base64 cgi deep_merge digest digest/md5 erb etc expect fileutils ipaddr json net/http net/https open-uri open3 pathname pp pty resolv securerandom set shellwords socket tempfile time timeout tmpdir uri yaml") + rubyLibs = set("English base64 cgi deep_merge digest digest/md5 erb etc expect fileutils ipaddr json net/http net/https open-uri open3 pathname pp pty resolv securerandom set shellwords socket strscan tempfile time timeout tmpdir uri yaml") puppetLibs = map[string][]string{ "puppet": nil, "puppet/util": nil, "puppet/util/checksums": nil, "puppet/parameter/path": nil, "puppet/property/ensure": nil, "puppet/util/execution": nil, "puppet/parameter/boolean": fileConsts[:2], @@ -484,6 +484,9 @@ var ( "puppet/util/suidmanager": {"Puppet::Util::SUIDManager m"}, "puppet/util/filetype": {"Puppet::Util::FileType c"}, "puppet/util/inifile": iniConsts, + "puppet/util/diff": {"Puppet::Util::Diff m", "Tempfile c", "Tempfile::Closer c", "Tempfile::Remover c"}, + "puppet/util/package": nil, + "puppet/util/feature": nil, "puppet/network/http_pool": {"Puppet::Network m", "Puppet::Network::HttpPool m"}, "puppet/type/file": fileConsts, "puppet/type/file/owner": fileConsts, "puppet/type/file/group": fileConsts, "puppet/type/file/mode": fileConsts, } @@ -539,6 +542,18 @@ func (p *parser) require() error { return err } } + if p.is(tIdent, "if") || p.is(tIdent, "unless") { + unless := p.take().text == "unless" + cond, err := p.eval() + if err != nil || truthy(cond) == unless { + return err + } + } + return p.requireLib(lib, abs) +} + +// requireLib requires lib, a $LOAD_PATH name or, when abs, a path in the requiring module's lib. +func (p *parser) requireLib(lib string, abs bool) error { lib = strings.TrimSuffix(lib, ".rb") if lib == "" || path.IsAbs(lib) || path.Clean(lib) != lib || lib == ".." || strings.HasPrefix(lib, "../") { return fmt.Errorf("unsupported require %q", lib) @@ -762,6 +777,19 @@ func (p *parser) blockOpen() (string, error) { return "end", nil } +// attrBlockOpen opens an attribute block, which class_eval yields its class to; a parameter for it changes nothing. +func (p *parser) attrBlockOpen() (string, error) { + if t := p.at(2); (p.is(tIdent, "do") || p.op("{")) && p.at(1).text == "|" && (isLocal(t) || t.kind == tIdent && strings.HasPrefix(t.text, "_")) && p.at(3).text == "|" { + closeTok := "end" + if p.take().text == "{" { + closeTok = "}" + } + p.i += 3 + return closeTok, nil + } + return p.blockOpen() +} + func (p *parser) docExpr() (string, error) { v, err := p.expr() if err != nil { @@ -957,7 +985,7 @@ func (p *parser) typeStmt(t *rtype) (bool, error) { p.used[p.i] = true p.take() a := &attr{name: "ensure", ensure: true} - closeTok, err := p.blockOpen() + closeTok, err := p.attrBlockOpen() if err != nil { return true, err } @@ -1032,6 +1060,10 @@ func mixinMethods(src, path string) (methods []string, err error) { p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}} want := strings.Split(path, "::") found, private := false, false + public := map[string]bool{} + defer func() { + methods = slices.DeleteFunc(methods, func(m string) bool { return !public[m] }) + }() target := func() (bool, error) { c := p.cur() switch { @@ -1043,14 +1075,24 @@ func mixinMethods(src, path string) (methods []string, err error) { case c.kind == tIdent && (c.text == "module" || c.text == "class") && p.at(1).kind == tConst: return true, p.skipStatement() case c.kind == tIdent && c.text == "def": - if !private { - methods = append(methods, p.at(1).text) + if n := p.at(1).text; !slices.Contains(methods, n) { + methods = append(methods, n) } + public[p.at(1).text] = !private return true, p.skipStatement() case c.kind == tIdent && (c.text == "private" || c.text == "protected" || c.text == "public") && (p.at(1).kind == tNL || p.at(1).text == ";"): p.take() private = c.text != "public" return true, nil + case c.kind == tIdent && (c.text == "private" || c.text == "protected" || c.text == "public"): + names, err := p.symArgs() + for _, n := range names { + if !slices.Contains(methods, n) { + return true, fmt.Errorf("%s: undefined method %s", c.text, n) + } + public[n] = c.text == "public" + } + return true, err case c.kind == tConst && p.assigns(): return true, p.strictConstAssign() } @@ -1213,7 +1255,7 @@ func (p *parser) newattr(t *rtype, property bool) error { } } } - closeTok, err := p.blockOpen() + closeTok, err := p.attrBlockOpen() if err != nil { return err } @@ -1305,6 +1347,9 @@ func (p *parser) attrStmt(a *attr) (bool, error) { if c.kind == tConst && p.assigns() { return true, p.strictConstAssign() } + if c.kind == tIdent && c.text == "include" && p.at(1).kind == tConst { + return true, p.include(&rtype{methods: map[string]bool{}}) + } if c.kind != tIdent || !watched[c.text] { return true, fmt.Errorf("unsupported %s in attribute %s", p.construct(), a.name) } diff --git a/internal/gentypes/testdata/env/external_modules/augeas_core/LICENSE b/internal/gentypes/testdata/env/external_modules/augeas_core/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/augeas_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/augeas_core/lib/puppet/feature/augeas.rb b/internal/gentypes/testdata/env/external_modules/augeas_core/lib/puppet/feature/augeas.rb new file mode 100644 index 0000000..681ba68 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/augeas_core/lib/puppet/feature/augeas.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +require 'puppet/util/feature' + +Puppet.features.add(:augeas, libs: ['augeas']) diff --git a/internal/gentypes/testdata/env/external_modules/augeas_core/lib/puppet/provider/augeas/augeas.rb b/internal/gentypes/testdata/env/external_modules/augeas_core/lib/puppet/provider/augeas/augeas.rb new file mode 100644 index 0000000..56daf92 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/augeas_core/lib/puppet/provider/augeas/augeas.rb @@ -0,0 +1,589 @@ +# +# Copyright 2011 Bryan Kearney +# +# 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 +# +# https://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. + +require 'augeas' if Puppet.features.augeas? +require 'strscan' +require 'puppet/util' +require 'puppet/util/diff' +require 'puppet/util/package' +require_relative '../../../puppet_x/augeas/util/parser' + +Puppet::Type.type(:augeas).provide(:augeas) do + desc 'The Augeas provider' + + include Puppet::Util + include Puppet::Util::Diff + include Puppet::Util::Package + include PuppetX::Augeas::Util::Parser + + confine feature: :augeas + + has_features :parse_commands, :need_to_run?, :execute_changes + + SAVE_NOOP = 'noop'.freeze + SAVE_OVERWRITE = 'overwrite'.freeze + SAVE_NEWFILE = 'newfile'.freeze + SAVE_BACKUP = 'backup'.freeze + + COMMANDS = { + 'set' => [:path, :string], + 'setm' => [:path, :string, :string], + 'rm' => [:path], + 'remove' => [:path], + 'clear' => [:path], + 'clearm' => [:path, :string], + 'touch' => [:path], + 'mv' => [:path, :path], + 'move' => [:path, :path], + 'rename' => [:path, :string], + 'insert' => [:string, :string, :path], + 'ins' => [:string, :string, :path], + 'get' => [:path, :comparator, :string], + 'values' => [:path, :glob], + 'defvar' => [:string, :path], + 'defnode' => [:string, :path, :string], + 'match' => [:path, :glob], + 'size' => [:comparator, :int], + 'include' => [:string], + 'not_include' => [:string], + '==' => [:glob], + '!=' => [:glob], + }.freeze + + attr_accessor :aug + + # Extracts an 2 dimensional array of commands which are in the + # form of command path value. + # The input can be + # - A string with one command + # - A string with many commands per line + # - An array of strings. + def parse_commands(data) + context = resource[:context] + # Add a trailing / if it is not there + unless context.empty? + context << '/' if context[-1, 1] != '/' + end + + data = data.split($INPUT_RECORD_SEPARATOR) if data.is_a?(String) + data = data.flatten + args = [] + data.each do |line| + next if line.nil? + line.strip! + next if line.empty? + argline = [] + sc = StringScanner.new(line) + cmd = sc.scan(%r{\w+|==|!=}) + formals = COMMANDS[cmd] + raise(_('Unknown command %{cmd}') % { cmd: cmd }) unless formals + argline << cmd + narg = 0 + formals.each do |f| + sc.skip(%r{\s+}) + narg += 1 + if f == :path + start = sc.pos + nbracket = 0 + in_single_tick = false + in_double_tick = false + loop do + sc.skip(%r{([^\]\[\s\\'"]|\\.)+}) + ch = sc.getch + nbracket += 1 if ch == '[' + nbracket -= 1 if ch == ']' + in_single_tick = !in_single_tick if ch == "'" + in_double_tick = !in_double_tick if ch == '"' + raise(_('unmatched [')) if nbracket < 0 + break if (nbracket == 0 && !in_single_tick && !in_double_tick && (ch =~ %r{\s})) || sc.eos? + end + len = sc.pos - start + len -= 1 unless sc.eos? + p = sc.string[start, len] + raise(_('missing path argument %{narg} for %{cmd}') % { narg: narg, cmd: cmd }) if p.nil? + + # Rip off any ticks if they are there. + p = p[1, (p.size - 2)] if p[0, 1] == "'" || p[0, 1] == '"' + p.chomp!('/') + argline << if p[0, 1] != '$' && p[0, 1] != '/' + context + p + else + p + end + elsif f == :string + delim = sc.peek(1) + if ["'", '"'].include?(delim) + sc.getch + argline << sc.scan(%r{([^\\#{delim}]|(\\.))*}) + # Unescape the delimiter so it's actually possible to have a + # literal delim inside the string. We only unescape the + # delimeter and not every backslash-escaped character so that + # things like escaped spaces '\ ' get passed through because + # Augeas needs to see them. If we unescaped them, too, users + # would be forced to double-escape them + argline.last.gsub!(%r{\\(#{delim})}, '\1') + sc.getch + else + argline << sc.scan(%r{[^\s]+}) + end + raise(_('missing string argument %{narg} for %{cmd}') % { narg: narg, cmd: cmd }) unless argline[-1] + elsif f == :comparator + argline << sc.scan(%r{(==|!=|=~|<=|>=|<|>)}) + unless argline[-1] + puts sc.rest + raise(_('invalid comparator for command %{cmd}') % { cmd: cmd }) + end + elsif f == :int + argline << sc.scan(%r{\d+}).to_i + elsif f == :glob + argline << sc.rest + end + end + args << argline + end + args + end + + def open_augeas + unless @aug + flags = Augeas::NONE + flags = Augeas::TYPE_CHECK if resource[:type_check] == :true + + flags |= if resource[:incl] + Augeas::NO_MODL_AUTOLOAD + else + Augeas::NO_LOAD + end + + root = resource[:root] + load_path = get_load_path(resource) + debug("Opening augeas with root #{root}, lens path #{load_path}, flags #{flags}") + @aug = Augeas.open(root, load_path, flags) + + debug("Augeas version #{get_augeas_version} is installed") if versioncmp(get_augeas_version, '0.3.6') >= 0 + + # Optimize loading if the context is given and it's a simple path, + # requires the glob function from Augeas 0.8.2 or up + glob_avail = !aug.match('/augeas/version/pathx/functions/glob').empty? + opt_ctx = resource[:context].match("^/files/[^'\"\\[\\]]+$") if resource[:context] + + if resource[:incl] + aug.set('/augeas/load/Xfm/lens', resource[:lens]) + aug.set('/augeas/load/Xfm/incl', resource[:incl]) + restricted_metadata = '/augeas//error' + elsif glob_avail && opt_ctx + # Optimize loading if the context is given, requires the glob function + # from Augeas 0.8.2 or up + ctx_path = resource[:context].sub(%r{^/files(.*?)/?$}, '\1/') + load_path = "/augeas/load/*['%s' !~ glob(incl) + regexp('/.*')]" % ctx_path + + if aug.match(load_path).size < aug.match('/augeas/load/*').size + aug.rm(load_path) + restricted_metadata = "/augeas/files#{ctx_path}/error" + else + # This will occur if the context is less specific than any glob + debug('Unable to optimize files loaded by context path, no glob matches') + end + end + aug.load + print_load_errors(restricted_metadata) + end + @aug + end + + def close_augeas + return if @aug.nil? + + @aug.close + debug('Closed the augeas connection') + @aug = nil + end + + def numeric?(s) + case s + when Integer + true + when String + s.match(%r{\A[+-]?\d+?(\.\d+)?\Z}n).nil? ? false : true + else + false + end + end + + # Used by the need_to_run? method to process get filters. Returns + # true if there is a match, false if otherwise + # Assumes a syntax of get /files/path [COMPARATOR] value + def process_get(cmd_array) + return_value = false + + # validate and tear apart the command + raise(_('Invalid command: %{cmd}') % { cmd: cmd_array.join(' ') }) if cmd_array.length < 4 + _ = cmd_array.shift + path = cmd_array.shift + comparator = cmd_array.shift + arg = cmd_array.join(' ') + + # check the value in augeas + result = @aug.get(path) || '' + + if ['<', '<=', '>=', '>'].include?(comparator) && numeric?(result) && + numeric?(arg) + resultf = result.to_f + argf = arg.to_f + return_value = resultf.send(comparator, argf) + elsif comparator == '!=' + return_value = (result != arg) + elsif comparator == '=~' + regex = Regexp.new(arg) + return_value = (result =~ regex) + else + return_value = result.send(comparator, arg) + end + !!return_value + end + + # Used by the need_to_run? method to process values filters. Returns + # true if there is a matched value, false if otherwise + def process_values(cmd_array) + return_value = false + + # validate and tear apart the command + raise(_('Invalid command: %{cmd}') % { cmd: cmd_array.join(' ') }) if cmd_array.length < 3 + _ = cmd_array.shift + path = cmd_array.shift + + # Need to break apart the clause + clause_array = parse_commands(cmd_array.shift)[0] + verb = clause_array.shift + + # Get the match paths from augeas + result = @aug.match(path) || [] + raise(_("Error trying to get path '%{path}'") % { path: path }) if result == -1 + + # Get the values of the match paths from augeas + values = result.map { |r| @aug.get(r) } + + case verb + when 'include' + arg = clause_array.shift + return_value = values.include?(arg) + when 'not_include' + arg = clause_array.shift + return_value = !values.include?(arg) + when '==' + begin + arg = clause_array.shift + new_array = parse_to_array(arg) + return_value = (values == new_array) + rescue + raise(_('Invalid array in command: %{cmd}') % { cmd: cmd_array.join(' ') }) + end + when '!=' + begin + arg = clause_array.shift + new_array = parse_to_array(arg) + return_value = (values != new_array) + rescue + raise(_('Invalid array in command: %{cmd}') % { cmd: cmd_array.join(' ') }) + end + end + !!return_value + end + + # Used by the need_to_run? method to process match filters. Returns + # true if there is a match, false if otherwise + def process_match(cmd_array) + return_value = false + + # validate and tear apart the command + raise(_('Invalid command: %{cmd}') % { cmd: cmd_array.join(' ') }) if cmd_array.length < 3 + _ = cmd_array.shift + path = cmd_array.shift + + # Need to break apart the clause + clause_array = parse_commands(cmd_array.shift)[0] + verb = clause_array.shift + + # Get the values from augeas + result = @aug.match(path) || [] + raise(_("Error trying to match path '%{path}'") % { path: path }) if result == -1 + + # Now do the work + case verb + when 'size' + raise(_('Invalid command: %{cmd}') % { cmd: cmd_array.join(' ') }) if clause_array.length != 2 + comparator = clause_array.shift + arg = clause_array.shift + return_value = case comparator + when '!=' + !result.size.send(:==, arg) + else + result.size.send(comparator, arg) + end + when 'include' + arg = clause_array.shift + return_value = result.include?(arg) + when 'not_include' + arg = clause_array.shift + return_value = !result.include?(arg) + when '==' + begin + arg = clause_array.shift + new_array = parse_to_array(arg) + return_value = (result == new_array) + rescue + raise(_('Invalid array in command: %{cmd}') % { cmd: cmd_array.join(' ') }) + end + when '!=' + begin + arg = clause_array.shift + new_array = parse_to_array(arg) + return_value = (result != new_array) + rescue + raise(_('Invalid array in command: %{cmd}') % { cmd: cmd_array.join(' ') }) + end + end + !!return_value + end + + # Generate lens load paths from user given paths and local pluginsync dir + def get_load_path(resource) + load_path = [] + + # Permits colon separated strings or arrays + if resource[:load_path] + load_path = [resource[:load_path]].flatten + load_path.map! { |path| path.split(%r{:}) } + load_path.flatten! + end + + if Puppet.run_mode.name == :agent + if Puppet::FileSystem.exist?("#{Puppet[:libdir]}/augeas/lenses") + load_path << "#{Puppet[:libdir]}/augeas/lenses" + end + else + env = Puppet.lookup(:current_environment) + env.each_plugin_directory do |dir| + lenses = File.join(dir, 'augeas', 'lenses') + if File.exist?(lenses) + load_path << lenses + end + end + end + + load_path.join(':') + end + + def get_augeas_version + @aug.get('/augeas/version') || '' + end + + def set_augeas_save_mode(mode) + @aug.set('/augeas/save', mode) + end + + def print_load_errors(path) + errors = @aug.match('/augeas//error') + unless errors.empty? + if path && !@aug.match(path).empty? + warning(_('Loading failed for one or more files, see debug for /augeas//error output')) + else + debug('Loading failed for one or more files, output from /augeas//error:') + end + end + print_errors(errors) + end + + def print_put_errors + errors = @aug.match("/augeas//error[. = 'put_failed']") + debug('Put failed on one or more files, output from /augeas//error:') unless errors.empty? + print_errors(errors) + end + + def print_errors(errors) + errors.each do |errnode| + error = @aug.get(errnode) + debug("#{errnode} = #{error}") unless error.nil? + @aug.match("#{errnode}/*").each do |subnode| + subvalue = @aug.get(subnode) + debug("#{subnode} = #{subvalue}") + end + end + end + + # Determines if augeas actually needs to run. + def need_to_run? + force = resource[:force] + return_value = true + begin + open_augeas + filter = resource[:onlyif] + unless filter == '' + cmd_array = parse_commands(filter)[0] + command = cmd_array[0] + begin + case command + when 'get' then return_value = process_get(cmd_array) + when 'values' then return_value = process_values(cmd_array) + when 'match' then return_value = process_match(cmd_array) + end + rescue StandardError => e + raise(_("Error sending command '%{command}' with params %{param}/%{message}") % { command: command, param: cmd_array[1..-1].inspect, message: e.message }) + end + end + + unless force + # If we have a version of augeas which is at least 0.3.6 then we + # can make the changes now and see if changes were made. + if return_value && versioncmp(get_augeas_version, '0.3.6') >= 0 + debug('Will attempt to save and only run if files changed') + # Execute in NEWFILE mode so we can show a diff + set_augeas_save_mode(SAVE_NEWFILE) + do_execute_changes + save_result = @aug.save + unless save_result + print_put_errors + raise(Puppet::Error, _('Save failed, see debug output for details')) + end + + saved_files = @aug.match('/augeas/events/saved') + if !saved_files.empty? + root = resource[:root].sub(%r{^/$}, '') + saved_files.map! { |key| @aug.get(key).sub(%r{^/files}, root) } + saved_files.uniq.each do |saved_file| + if Puppet[:show_diff] && @resource[:show_diff] + send(@resource[:loglevel], "\n" + diff(saved_file, saved_file + '.augnew')) + end + File.delete(saved_file + '.augnew') + end + debug('Files changed, should execute') + return_value = true + else + debug('Skipping because no files were changed') + return_value = false + end + end + end + ensure + if !return_value || resource.noop? || !save_result + close_augeas + end + end + return_value + end + + def execute_changes + # Workaround Augeas bug where changing the save mode doesn't trigger a + # reload of the previously saved file(s) when we call Augeas#load + @aug.match('/augeas/events/saved').each do |file| + @aug.rm("/augeas#{@aug.get(file)}/mtime") + end + + # Reload augeas, and execute the changes for real + set_augeas_save_mode(SAVE_OVERWRITE) if versioncmp(get_augeas_version, '0.3.6') >= 0 + @aug.load + do_execute_changes + unless @aug.save + print_put_errors + raise(Puppet::Error, _('Save failed, see debug output for details')) + end + + :executed + ensure + close_augeas + end + + # Actually execute the augeas changes. + # rubocop:disable Style/GuardClause + def do_execute_changes + commands = parse_commands(resource[:changes]) + commands.each do |cmd_array| + raise(_('invalid command %{cmd}') % { value0: cmd_array.join[' '] }) if cmd_array.length < 2 + command = cmd_array[0] + cmd_array.shift + begin + case command + when 'set' + debug("sending command '#{command}' with params #{cmd_array.inspect}") + rv = aug.set(cmd_array[0], cmd_array[1]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv + when 'setm' + if aug.respond_to?(command) + debug("sending command '#{command}' with params #{cmd_array.inspect}") + rv = aug.setm(cmd_array[0], cmd_array[1], cmd_array[2]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1 + else + raise(_("command '%{command}' not supported in installed version of ruby-augeas") % { command: command }) + end + when 'rm', 'remove' + debug("sending command '#{command}' with params #{cmd_array.inspect}") + rv = aug.rm(cmd_array[0]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1 + when 'clear' + debug("sending command '#{command}' with params #{cmd_array.inspect}") + rv = aug.clear(cmd_array[0]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv + when 'clearm' + # Check command exists ... doesn't currently in ruby-augeas 0.4.1 + if aug.respond_to?(command) + debug("sending command '#{command}' with params #{cmd_array.inspect}") + rv = aug.clearm(cmd_array[0], cmd_array[1]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv + else + raise(_("command '%{command}' not supported in installed version of ruby-augeas") % { command: command }) + end + when 'touch' + debug("sending command '#{command}' (match, set) with params #{cmd_array.inspect}") + if aug.match(cmd_array[0]).empty? + rv = aug.clear(cmd_array[0]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv + end + when 'insert', 'ins' + label = cmd_array[0] + where = cmd_array[1] + path = cmd_array[2] + case where + when 'before' then before = true + when 'after' then before = false + else raise(_("Invalid value '%{where}' for where param") % { where: where }) + end + debug("sending command '#{command}' with params #{[label, where, path].inspect}") + rv = aug.insert(path, label, before) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1 + when 'defvar' + debug("sending command '#{command}' with params #{cmd_array.inspect}") + rv = aug.defvar(cmd_array[0], cmd_array[1]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv + when 'defnode' + debug("sending command '#{command}' with params #{cmd_array.inspect}") + rv = aug.defnode(cmd_array[0], cmd_array[1], cmd_array[2]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv + when 'mv', 'move' + debug("sending command '#{command}' with params #{cmd_array.inspect}") + rv = aug.mv(cmd_array[0], cmd_array[1]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1 + when 'rename' + debug("sending command '#{command}' with params #{cmd_array.inspect}") + rv = aug.rename(cmd_array[0], cmd_array[1]) + raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1 + else raise(_("Command '%{command}' is not supported") % { command: command }) + end + rescue StandardError => e + raise(_("Error sending command '%{command}' with params %{params}/%{message}") % { command: command, params: cmd_array.inspect, message: e.message }) + end + end + end + # rubocop:enable Style/GuardClause +end diff --git a/internal/gentypes/testdata/env/external_modules/augeas_core/lib/puppet/type/augeas.rb b/internal/gentypes/testdata/env/external_modules/augeas_core/lib/puppet/type/augeas.rb new file mode 100644 index 0000000..ef93bce --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/augeas_core/lib/puppet/type/augeas.rb @@ -0,0 +1,208 @@ +# +# Copyright 2011 Bryan Kearney +# +# 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 +# +# https://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. + +require 'puppet/parameter/boolean' + +Puppet::Type.newtype(:augeas) do + include Puppet::Util + + feature :parse_commands, 'Parse the command string' + feature :need_to_run?, 'If the command should run' + feature :execute_changes, 'Actually make the changes' + + @doc = <<-'EOT' + @summary Apply a change or an array of changes to the filesystem using the augeas tool. + + Requires: + + - [Augeas](http://www.augeas.net) + - The ruby-augeas bindings + + @example Sample usage with a string: + + augeas { "test1": + context => "/files/etc/sysconfig/firstboot", + changes => "set RUN_FIRSTBOOT YES", + onlyif => "match other_value size > 0", + } + + @example Sample usage with an array and custom lenses: + + augeas { "jboss_conf": + context => "/files", + changes => [ + "set etc/jbossas/jbossas.conf/JBOSS_IP $ipaddress", + "set etc/jbossas/jbossas.conf/JAVA_HOME /usr", + ], + load_path => "$/usr/share/jbossas/lenses", + } + + EOT + + newparam(:name) do + desc 'The name of this task. Used for uniqueness.' + isnamevar + end + + newparam(:context) do + desc "Optional context path. This value is prepended to the paths of all + changes if the path is relative. If the `incl` parameter is set, + defaults to `/files + incl`; otherwise, defaults to the empty string." + defaultto '' + munge do |value| + if value.empty? && resource[:incl] + '/files' + resource[:incl] + else + value + end + end + end + + newparam(:onlyif) do + desc "Optional augeas command and comparisons to control the execution of this type. + + Note: `values` is not an actual augeas API command. It calls `match` to retrieve an array of paths + in and then `get` to retrieve the values from each of the returned paths. + + Supported onlyif syntax: + + * `get ` + * `values include ` + * `values not_include ` + * `values == ` + * `values != ` + * `match size ` + * `match include ` + * `match not_include ` + * `match == ` + * `match != ` + + where: + + * `AUGEAS_PATH` is a valid path scoped by the context + * `MATCH_PATH` is a valid match syntax scoped by the context + * `COMPARATOR` is one of `>, >=, !=, ==, <=,` or `<` + * `STRING` is a string + * `INT` is a number + * `AN_ARRAY` is in the form `['a string', 'another']`" + defaultto '' + end + + newparam(:changes) do + desc "The changes which should be applied to the filesystem. This + can be a command or an array of commands. The following commands are supported: + + * `set ` --- Sets the value `VALUE` at location `PATH` + * `setm ` --- Sets multiple nodes (matching `SUB` relative to `PATH`) to `VALUE` + * `rm ` --- Removes the node at location `PATH` + * `remove ` --- Synonym for `rm` + * `clear ` --- Sets the node at `PATH` to `NULL`, creating it if needed + * `clearm ` --- Sets multiple nodes (matching `SUB` relative to `PATH`) to `NULL` + * `touch ` --- Creates `PATH` with the value `NULL` if it does not exist + * `ins