Merge pull request 'Generate augeas types through module features and core mixins' (#18) from benvin/gentypes-augeas into main
Reviewed-on: #18
This commit was merged in pull request #18.
This commit is contained in:
@@ -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.<m> at the cursor, or Puppet.features.<name>? 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.<name>?: a missing method autoloads puppet/feature/<name>.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/<name>.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])
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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_]*$`)
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'puppet/util/feature'
|
||||
|
||||
Puppet.features.add(:augeas, libs: ['augeas'])
|
||||
Vendored
+589
@@ -0,0 +1,589 @@
|
||||
#
|
||||
# Copyright 2011 Bryan Kearney <bkearney@redhat.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
|
||||
#
|
||||
# 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
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
#
|
||||
# Copyright 2011 Bryan Kearney <bkearney@redhat.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
|
||||
#
|
||||
# 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 <MATCH_PATH> and then `get` to retrieve the values from each of the returned paths.
|
||||
|
||||
Supported onlyif syntax:
|
||||
|
||||
* `get <AUGEAS_PATH> <COMPARATOR> <STRING>`
|
||||
* `values <MATCH_PATH> include <STRING>`
|
||||
* `values <MATCH_PATH> not_include <STRING>`
|
||||
* `values <MATCH_PATH> == <AN_ARRAY>`
|
||||
* `values <MATCH_PATH> != <AN_ARRAY>`
|
||||
* `match <MATCH_PATH> size <COMPARATOR> <INT>`
|
||||
* `match <MATCH_PATH> include <STRING>`
|
||||
* `match <MATCH_PATH> not_include <STRING>`
|
||||
* `match <MATCH_PATH> == <AN_ARRAY>`
|
||||
* `match <MATCH_PATH> != <AN_ARRAY>`
|
||||
|
||||
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 <PATH> <VALUE>` --- Sets the value `VALUE` at location `PATH`
|
||||
* `setm <PATH> <SUB> <VALUE>` --- Sets multiple nodes (matching `SUB` relative to `PATH`) to `VALUE`
|
||||
* `rm <PATH>` --- Removes the node at location `PATH`
|
||||
* `remove <PATH>` --- Synonym for `rm`
|
||||
* `clear <PATH>` --- Sets the node at `PATH` to `NULL`, creating it if needed
|
||||
* `clearm <PATH> <SUB>` --- Sets multiple nodes (matching `SUB` relative to `PATH`) to `NULL`
|
||||
* `touch <PATH>` --- Creates `PATH` with the value `NULL` if it does not exist
|
||||
* `ins <LABEL> (before|after) <PATH>` --- Inserts an empty node `LABEL` either before or after `PATH`.
|
||||
* `insert <LABEL> <WHERE> <PATH>` --- Synonym for `ins`
|
||||
* `mv <PATH> <OTHER PATH>` --- Moves a node at `PATH` to the new location `OTHER PATH`
|
||||
* `move <PATH> <OTHER PATH>` --- Synonym for `mv`
|
||||
* `rename <PATH> <LABEL>` --- Rename a node at `PATH` to a new `LABEL`
|
||||
* `defvar <NAME> <PATH>` --- Sets Augeas variable `$NAME` to `PATH`
|
||||
* `defnode <NAME> <PATH> <VALUE>` --- Sets Augeas variable `$NAME` to `PATH`, creating it with `VALUE` if needed
|
||||
|
||||
If the `context` parameter is set, that value is prepended to any relative `PATH`s."
|
||||
end
|
||||
|
||||
newparam(:root) do
|
||||
desc 'A file system path; all files loaded by Augeas are loaded underneath `root`.'
|
||||
defaultto '/'
|
||||
end
|
||||
|
||||
newparam(:load_path) do
|
||||
desc "Optional colon-separated list or array of directories; these directories are searched for schema definitions.
|
||||
The agent's `$libdir/augeas/lenses` path will always be added to support pluginsync."
|
||||
defaultto ''
|
||||
end
|
||||
|
||||
newparam(:force) do
|
||||
desc "Optional command to force the augeas type to execute even if it thinks changes
|
||||
will not be made. This does not override the `onlyif` parameter."
|
||||
|
||||
defaultto false
|
||||
end
|
||||
|
||||
newparam(:type_check) do
|
||||
desc 'Whether augeas should perform typechecking. Defaults to false.'
|
||||
newvalues(:true, :false)
|
||||
|
||||
defaultto :false
|
||||
end
|
||||
|
||||
newparam(:lens) do
|
||||
desc "Use a specific lens, such as `Hosts.lns`. When this parameter is set, you
|
||||
must also set the `incl` parameter to indicate which file to load.
|
||||
The Augeas documentation includes [a list of available lenses](http://augeas.net/stock_lenses.html)."
|
||||
end
|
||||
|
||||
newparam(:incl) do
|
||||
desc "Load only a specific file, such as `/etc/hosts`. This can greatly speed
|
||||
up the execution the resource. When this parameter is set, you must also
|
||||
set the `lens` parameter to indicate which lens to use."
|
||||
end
|
||||
|
||||
validate do
|
||||
has_lens = !self[:lens].nil?
|
||||
has_incl = !self[:incl].nil?
|
||||
raise(Puppet::Error, _('You must specify both the lens and incl parameters, or neither.')) if has_lens != has_incl
|
||||
end
|
||||
|
||||
newparam(:show_diff, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc "Whether to display differences when the file changes, defaulting to
|
||||
true. This parameter is useful for files that may contain passwords or
|
||||
other secret data, which might otherwise be included in Puppet reports or
|
||||
other insecure outputs. If the global `show_diff` setting
|
||||
is false, then no diffs will be shown even if this parameter is true."
|
||||
|
||||
defaultto :true
|
||||
end
|
||||
|
||||
# This is the actual meat of the code. It forces
|
||||
# augeas to be run and fails or not based on the augeas return
|
||||
# code.
|
||||
newproperty(:returns) do |_property|
|
||||
include Puppet::Util
|
||||
desc 'The expected return code from the augeas command. Should not be set.'
|
||||
|
||||
defaultto 0
|
||||
|
||||
# Make output a bit prettier
|
||||
def change_to_s(_currentvalue, _newvalue)
|
||||
_('executed successfully')
|
||||
end
|
||||
|
||||
# if the onlyif resource is provided, then the value is parsed.
|
||||
# a return value of 0 will stop execution because it matches the
|
||||
# default value.
|
||||
def retrieve
|
||||
if @resource.provider.need_to_run?
|
||||
:need_to_run
|
||||
else
|
||||
0
|
||||
end
|
||||
end
|
||||
|
||||
# Actually execute the command.
|
||||
def sync
|
||||
@resource.provider.execute_changes
|
||||
end
|
||||
end
|
||||
end
|
||||
Vendored
+217
@@ -0,0 +1,217 @@
|
||||
# rubocop:disable Style/Documentation
|
||||
module PuppetX; end
|
||||
|
||||
module PuppetX::Augeas; end
|
||||
|
||||
module PuppetX::Augeas::Util; end
|
||||
# rubocop:enable Style/Documentation
|
||||
|
||||
# Container for helpers to parse user provided data contained in manifests.
|
||||
module PuppetX::Augeas::Util::Parser
|
||||
TOKEN_ARRAY_CLOSE = %r{\s*\]\s*}.freeze
|
||||
TOKEN_ARRAY_OPEN = %r{\s*\[\s*}.freeze
|
||||
TOKEN_ARRAY_SEPARATOR = %r{\s*,\s*}.freeze
|
||||
TOKEN_CLOSE_CURLY = %r|}|.freeze
|
||||
TOKEN_DOUBLE_QUOTE = %r{"}.freeze
|
||||
TOKEN_DOUBLE_QUOTE_ESCAPED_CHAR = %r{\\(["\\abtnvfres0-7xu])}.freeze
|
||||
TOKEN_DOUBLE_QUOTE_UNESCAPED_CHAR = %r{[^"\\]}.freeze
|
||||
TOKEN_HEX_CHAR = %r{[0-9a-fA-F]{1,2}}.freeze
|
||||
TOKEN_OCTAL_CHAR = %r{[0-7]{1,3}}.freeze
|
||||
TOKEN_OPEN_CURLY = %r|{|.freeze
|
||||
TOKEN_SINGLE_QUOTE = %r{'}.freeze
|
||||
TOKEN_SINGLE_QUOTE_ESCAPED_CHAR = %r{\\(['\\])}.freeze
|
||||
TOKEN_SINGLE_QUOTE_UNESCAPED_CHAR = %r{[^'\\]}.freeze
|
||||
TOKEN_SPACE = %r{\s}.freeze
|
||||
TOKEN_UNICODE_LONG_HEX_CHAR = %r{[0-9a-fA-F]{1,6}}.freeze
|
||||
TOKEN_UNICODE_SHORT_HEX_CHAR = %r{[0-9a-fA-F]{4}}.freeze
|
||||
|
||||
# Parse a string into the (nearly) equivalent Ruby array. This only handles
|
||||
# arrays with string members (double-, or single-quoted), and does not
|
||||
# support the full quite of escape sequences that Ruby allows in
|
||||
# double-quoted strings.
|
||||
#
|
||||
# @param string [String] The string to be parsed.
|
||||
# @return [Array<String>] The parsed array elements, including handling any
|
||||
# escape sequences.
|
||||
def parse_to_array(string)
|
||||
s = StringScanner.new(string)
|
||||
match = array_open(s)
|
||||
raise "Unexpected character in array at: #{s.rest}" if match.nil?
|
||||
|
||||
array_content = array_values(s)
|
||||
|
||||
match = array_close(s)
|
||||
raise "Unexpected character in array at: #{s.rest}" if match.nil? || !s.empty?
|
||||
|
||||
array_content
|
||||
end
|
||||
|
||||
def array_open(scanner)
|
||||
scanner.scan(TOKEN_ARRAY_OPEN)
|
||||
end
|
||||
private :array_open
|
||||
|
||||
def array_close(scanner)
|
||||
scanner.scan(TOKEN_ARRAY_CLOSE)
|
||||
end
|
||||
private :array_close
|
||||
|
||||
def array_separator(scanner)
|
||||
scanner.scan(TOKEN_ARRAY_SEPARATOR)
|
||||
end
|
||||
private :array_separator
|
||||
|
||||
def single_quote_unescaped_char(scanner)
|
||||
scanner.scan(TOKEN_SINGLE_QUOTE_UNESCAPED_CHAR)
|
||||
end
|
||||
private :single_quote_unescaped_char
|
||||
|
||||
def single_quote_escaped_char(scanner)
|
||||
scanner.scan(TOKEN_SINGLE_QUOTE_ESCAPED_CHAR) && scanner[1]
|
||||
end
|
||||
private :single_quote_escaped_char
|
||||
|
||||
def single_quote_char(scanner)
|
||||
single_quote_escaped_char(scanner) || single_quote_unescaped_char(scanner)
|
||||
end
|
||||
private :single_quote_char
|
||||
|
||||
def double_quote_unescaped_char(scanner)
|
||||
scanner.scan(TOKEN_DOUBLE_QUOTE_UNESCAPED_CHAR)
|
||||
end
|
||||
private :double_quote_unescaped_char
|
||||
|
||||
# This handles the possible Ruby escape sequences in double-quoted strings,
|
||||
# except for \M-x, \M-\C-x, \M-\cx, \c\M-x, \c?, and \C-?. The full list of
|
||||
# escape sequences, and their meanings is taken from:
|
||||
# https://github.com/ruby/ruby/blob/90fdfec11a4a42653722e2ce2a672d6e87a57b8e/doc/syntax/literals.rdoc#strings
|
||||
def double_quote_escaped_char(scanner)
|
||||
match = scanner.scan(TOKEN_DOUBLE_QUOTE_ESCAPED_CHAR)
|
||||
return nil if match.nil?
|
||||
|
||||
case scanner[1]
|
||||
when '\\' then '\\'
|
||||
when '"' then '"'
|
||||
when 'a' then "\a"
|
||||
when 'b' then "\b"
|
||||
when 't' then "\t"
|
||||
when 'n' then "\n"
|
||||
when 'v' then "\v"
|
||||
when 'f' then "\f"
|
||||
when 'r' then "\r"
|
||||
when 'e' then "\e"
|
||||
when 's' then "\s"
|
||||
when %r{[0-7]}
|
||||
# Back the scanner up by one byte so we can grab all of the potential
|
||||
# octal digits at the same time.
|
||||
scanner.pos = scanner.pos - 1
|
||||
octal_character = scanner.scan(TOKEN_OCTAL_CHAR)
|
||||
|
||||
octal_character.to_i(8).chr
|
||||
when 'x'
|
||||
hex_character = scanner.scan(TOKEN_HEX_CHAR)
|
||||
return nil if hex_character.nil?
|
||||
|
||||
hex_character.to_i(16).chr
|
||||
when 'u'
|
||||
unicode_short_hex_character(scanner) || unicode_long_hex_characters(scanner)
|
||||
else
|
||||
# Not a valid escape sequence as far as we're concerned.
|
||||
nil
|
||||
end
|
||||
end
|
||||
private :double_quote_escaped_char
|
||||
|
||||
def unicode_short_hex_character(scanner)
|
||||
unicode_character = scanner.scan(TOKEN_UNICODE_SHORT_HEX_CHAR)
|
||||
return nil if unicode_character.nil?
|
||||
|
||||
[unicode_character.hex].pack 'U'
|
||||
end
|
||||
private :unicode_short_hex_character
|
||||
|
||||
def unicode_long_hex_characters(scanner)
|
||||
unicode_string = ''
|
||||
return nil unless scanner.scan(TOKEN_OPEN_CURLY)
|
||||
|
||||
loop do
|
||||
char = scanner.scan(TOKEN_UNICODE_LONG_HEX_CHAR)
|
||||
break if char.nil?
|
||||
unicode_string << [char.hex].pack('U')
|
||||
|
||||
separator = scanner.scan(TOKEN_SPACE)
|
||||
break if separator.nil?
|
||||
end
|
||||
|
||||
return nil if scanner.scan(TOKEN_CLOSE_CURLY).nil? || unicode_string.empty?
|
||||
|
||||
unicode_string
|
||||
end
|
||||
private :unicode_long_hex_characters
|
||||
|
||||
def single_quoted_string(scanner)
|
||||
quoted_string = ''
|
||||
|
||||
match = scanner.scan(TOKEN_SINGLE_QUOTE)
|
||||
return nil if match.nil?
|
||||
|
||||
loop do
|
||||
match = single_quote_char(scanner)
|
||||
break if match.nil?
|
||||
|
||||
quoted_string << match
|
||||
end
|
||||
|
||||
match = scanner.scan(TOKEN_SINGLE_QUOTE)
|
||||
return quoted_string if match
|
||||
|
||||
nil
|
||||
end
|
||||
private :single_quoted_string
|
||||
|
||||
def double_quote_char(scanner)
|
||||
double_quote_escaped_char(scanner) || double_quote_unescaped_char(scanner)
|
||||
end
|
||||
private :double_quote_char
|
||||
|
||||
def double_quoted_string(scanner)
|
||||
quoted_string = ''
|
||||
|
||||
match = scanner.scan(TOKEN_DOUBLE_QUOTE)
|
||||
return nil if match.nil?
|
||||
|
||||
loop do
|
||||
match = double_quote_char(scanner)
|
||||
break if match.nil?
|
||||
|
||||
quoted_string << match
|
||||
end
|
||||
|
||||
match = scanner.scan(TOKEN_DOUBLE_QUOTE)
|
||||
return quoted_string if match
|
||||
|
||||
nil
|
||||
end
|
||||
private :double_quoted_string
|
||||
|
||||
def quoted_string(scanner)
|
||||
single_quoted_string(scanner) || double_quoted_string(scanner)
|
||||
end
|
||||
private :quoted_string
|
||||
|
||||
def array_values(scanner)
|
||||
values = []
|
||||
|
||||
loop do
|
||||
match = quoted_string(scanner)
|
||||
break if match.nil?
|
||||
values << match
|
||||
|
||||
match = array_separator(scanner)
|
||||
break if match.nil?
|
||||
end
|
||||
|
||||
values
|
||||
end
|
||||
private :array_values
|
||||
end
|
||||
+201
@@ -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.
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'puppet/util/feature'
|
||||
|
||||
Puppet.features.add(:augeas, libs: ['augeas'])
|
||||
+906
@@ -0,0 +1,906 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'augeas' if Puppet.features.augeas?
|
||||
|
||||
# Base Augeas provider
|
||||
# Handles basics such as opening, accessing and saving changes via an Augeas
|
||||
# handle, plus standard configuration from a Puppet resource (e.g. the `target`
|
||||
# parameter).
|
||||
#
|
||||
# To use, include as parent provider:
|
||||
#
|
||||
# Puppet::Type.type(:example).provide(
|
||||
# :augeas,
|
||||
# :parent => Puppet::Type.type(:augeasprovider).provider(:default)
|
||||
# ) do
|
||||
# # [..]
|
||||
# end
|
||||
#
|
||||
Puppet::Type.type(:augeasprovider).provide(:default) do
|
||||
# Class methods automatically added to a Puppet provider by including the
|
||||
# {AugeasProviders::Provider} mixin.
|
||||
|
||||
# Returns the Augeas version used
|
||||
#
|
||||
# @return [String] Augeas version in use
|
||||
# @api public
|
||||
def self.aug_version
|
||||
@aug_version ||= Augeas.open(nil, nil, Augeas::NO_MODL_AUTOLOAD) { |aug| aug.get('/augeas/version') }
|
||||
end
|
||||
|
||||
# Returns whether a feature is supported.
|
||||
#
|
||||
# The following features are currently supported:
|
||||
#
|
||||
# * `:regexpi`: whether Augeas supports an 'i' flag in regexp expressions
|
||||
#
|
||||
# @param [Symbol] feature the feature to check
|
||||
# @return [Boolean] whether feature is supported
|
||||
# @api public
|
||||
def self.supported?(feature)
|
||||
case feature
|
||||
when :regexpi
|
||||
Puppet::Util::Package.versioncmp(aug_version, '1.0.0') >= 0
|
||||
else
|
||||
raise Puppet::Error, "Unknown feature '#{feature}'"
|
||||
end
|
||||
end
|
||||
|
||||
# Returns a node label to use for creating a new entry in an Augeas sequence
|
||||
# (seq), given the current list, e.g. '1' if it's the first. Supply
|
||||
# aug.match('$target/*') or similar.
|
||||
#
|
||||
# @param [Array<String>] existing paths, from Augeas#match
|
||||
# @return [String] new node label
|
||||
def self.next_seq(matches)
|
||||
last = matches.map { |p| path_label(nil, p).to_i }.max || 0
|
||||
(last + 1).to_s
|
||||
end
|
||||
|
||||
# Returns a shared Augeas handler for all instances of the class
|
||||
#
|
||||
# @return [Augeas] Augeas shared Augeas handle
|
||||
# @api private
|
||||
def self.aug_handler
|
||||
@aug_handler ||= Augeas.open(nil, loadpath, Augeas::NO_MODL_AUTOLOAD)
|
||||
end
|
||||
|
||||
# Close the shared Augeas handler.
|
||||
#
|
||||
# @param [Augeas] aug open Augeas handle
|
||||
# @api public
|
||||
def self.augclose!(aug)
|
||||
aug.close
|
||||
end
|
||||
|
||||
# Opens Augeas and returns a handle to use. It loads only the file
|
||||
# identified by {#target} (and the supplied `resource`) using {#lens}.
|
||||
#
|
||||
# If called with a block, this will be yielded to and the Augeas handle.
|
||||
# Otherwise, the handle will be returned and not closed automatically.
|
||||
# The handle will be closed by `post_resource_eval`.
|
||||
#
|
||||
# If `yield_resource` is set to true, the supplied `resource` will be passed
|
||||
# as a yieldparam to the block, after the `aug` handle. Any arguments passed
|
||||
# after `yield_resource` will be added as yieldparams to the block.
|
||||
#
|
||||
# @param [Puppet::Resource] resource resource being evaluated
|
||||
# @param [Boolean] yield_resource whether to send `resource` as a yieldparam
|
||||
# @param [Splat] yield_params a splat of parameters to pass as yieldparams if `yield_resource` is true
|
||||
# @return [Augeas] Augeas handle if no block is given
|
||||
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
|
||||
# @yieldparam [Augeas] aug open Augeas handle
|
||||
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
|
||||
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
|
||||
# @raise [Puppet::Error] if Augeas did not load the file
|
||||
# @api public
|
||||
def self.augopen(resource = nil, yield_resource = false, *yield_params, &block)
|
||||
augopen_internal(resource, yield_resource, *yield_params, &block)
|
||||
end
|
||||
|
||||
# Opens Augeas and returns a handle to use. It loads only the file
|
||||
# for the current Puppet resource using {AugeasProviders::Provider::ClassMethods#lens}.
|
||||
# #augsave! is called after the block is evaluated.
|
||||
#
|
||||
# If called with a block, this will be yielded to and the Augeas handle.
|
||||
# Otherwise, the handle will be returned and not closed automatically.
|
||||
# The handle will be closed by `post_resource_eval`.
|
||||
#
|
||||
# If `yield_resource` is set to true, the supplied `resource` will be passed
|
||||
# as a yieldparam to the block, after the `aug` handle. Any arguments passed
|
||||
# after `yield_resource` will be added as yieldparams to the block.
|
||||
#
|
||||
# @param [Puppet::Resource] resource resource being evaluated
|
||||
# @param [Boolean] yield_resource whether to send `resource` as a yieldparam
|
||||
# @param [Splat] yield_params a splat of parameters to pass as yieldparams if `yield_resource` is true
|
||||
# @return [Augeas] Augeas handle if no block is given
|
||||
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
|
||||
# @yieldparam [Augeas] aug open Augeas handle
|
||||
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
|
||||
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
|
||||
# @raise [Puppet::Error] if Augeas did not load the file
|
||||
# @api public
|
||||
def self.augopen!(resource = nil, yield_resource = false, *yield_params, &block)
|
||||
augopen_internal(resource, yield_resource, *yield_params, &block)
|
||||
end
|
||||
|
||||
# Saves all changes made in the current Augeas handle and checks for any
|
||||
# errors while doing so.
|
||||
# Reloads the tree afterwards to remove specific changes for next resource.
|
||||
#
|
||||
# @param [Augeas] aug open Augeas handle
|
||||
# @param [Boolean] reload whether to reload the tree after saving
|
||||
# @raise [Augeas::Error] if saving fails
|
||||
# @api public
|
||||
def self.augsave!(aug, reload = false)
|
||||
aug.save!
|
||||
rescue Augeas::Error
|
||||
errors = []
|
||||
aug.match('/augeas//error').each do |errnode|
|
||||
aug.match("#{errnode}/*").each do |subnode|
|
||||
subvalue = aug.get(subnode)
|
||||
errors << "#{subnode} = #{subvalue}"
|
||||
end
|
||||
end
|
||||
debug("Save failure details:\n#{errors.join("\n")}")
|
||||
raise Augeas::Error, 'Failed to save Augeas tree to file. See debug logs for details.'
|
||||
ensure
|
||||
aug.load! if reload
|
||||
# https://github.com/hercules-team/augeas/commit/eb04250a05671b2d001444b72b8778328d209d75 introduced a bug in libaugeas.so.0.25.0
|
||||
# bundled with puppet7.
|
||||
# A temporary fix is to invoke load! twice.
|
||||
aug.load! if reload && Puppet::Util::Package.versioncmp(aug_version, '1.13.0') >= 0
|
||||
end
|
||||
|
||||
# Define a method with a block passed to #augopen
|
||||
#
|
||||
# @param [Symbol] method the name of the method to create
|
||||
# @yield [aug, resource, *args] block that uses the Augeas handle
|
||||
# @yieldparam [Augeas] aug open Augeas handle
|
||||
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource
|
||||
# @yieldparam [Splat] *args a splat of additional arguments sent to the block
|
||||
# @api public
|
||||
def self.define_aug_method(method, &block)
|
||||
define_method(method) do |*args|
|
||||
# We are calling the resource's augopen here, not the class
|
||||
augopen(true, *args, &block)
|
||||
end
|
||||
end
|
||||
|
||||
# Define a method with a block passed to #augopen!
|
||||
#
|
||||
# @param [Symbol] method the name of the method to create
|
||||
# @yield [aug, resource, *args] block that uses the Augeas handle
|
||||
# @yieldparam [Augeas] aug open Augeas handle
|
||||
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource
|
||||
# @yieldparam [Splat] *args a splat of additional arguments sent to the block
|
||||
# @api public
|
||||
def self.define_aug_method!(method, &block)
|
||||
define_method(method) do |*args|
|
||||
# We are calling the resource's augopen! here, not the class
|
||||
augopen!(true, *args, &block)
|
||||
end
|
||||
end
|
||||
|
||||
# Defines a property getter with a provided implementation. It works from
|
||||
# a node identified with the given `label` beneath the resource.
|
||||
#
|
||||
# Supports three implementations based on the type specified:
|
||||
#
|
||||
# :string causes the getter to return the value of the node below
|
||||
# resource with the label given in opts
|
||||
#
|
||||
# :array causes the getter to return an array of values matching the label.
|
||||
# If sublabel is given, values of matching nodes beneath the
|
||||
# label node will be returned in an array. If sublabel is :seq, values of
|
||||
# nodes matching a numbered seq will be returned.
|
||||
#
|
||||
# :hash causes the getter to return a hash of the value of each matching
|
||||
# label node against the value of each sublabel node.
|
||||
#
|
||||
# @param [String] name the name of the property
|
||||
# @param [Hash] opts the options to create the setter
|
||||
# @option opts [String] label node label to match beneath resource, default is `name.to_s`. When the value is `:resource`, `$resource` will be used as the path to the node
|
||||
# @option opts [Symbol] type either :string, :array or :hash
|
||||
# @option opts [String] default default value for hash values if sublabel doesn't exist
|
||||
# @option opts [String] sublabel label of next node(s) beneath node label, used in array and hash values, or :seq for array values representing a numbered seq
|
||||
# @api public
|
||||
def self.attr_aug_reader(name, opts = {})
|
||||
label = opts[:label] || name.to_s
|
||||
default = opts[:default] || nil
|
||||
type = opts[:type] || :string
|
||||
sublabel = opts[:sublabel] || nil
|
||||
split_by = opts[:split_by] || nil
|
||||
|
||||
rpath = label == :resource ? '$resource' : "$resource/#{label}"
|
||||
|
||||
raise(Puppet::Error, 'You must provide a sublabel for type hash') if type == :hash && sublabel.nil?
|
||||
|
||||
raise(Puppet::Error, "Invalid type: #{type}") unless %i[string array hash].include? type
|
||||
|
||||
# Class getter method using an existing aug handler
|
||||
# Emulate define_singleton_method for Ruby 1.8
|
||||
metaclass = class << self; self; end
|
||||
metaclass.send(:define_method, "attr_aug_reader_#{name}") do |aug, *_args|
|
||||
case type
|
||||
when :string
|
||||
aug.get(rpath)
|
||||
when :array
|
||||
return (aug.get(rpath) || '').split(split_by) if split_by
|
||||
|
||||
aug.match(rpath).map do |p|
|
||||
if sublabel.nil?
|
||||
aug.get(p)
|
||||
else
|
||||
sp = sublabel == :seq ? "#{p}/*[label()=~regexp('[0-9]+')]" : "#{p}/#{sublabel}"
|
||||
aug.match(sp).map { |spp| aug.get(spp) }
|
||||
end
|
||||
end.flatten
|
||||
when :hash
|
||||
values = {}
|
||||
aug.match(rpath).each do |p|
|
||||
sp = "#{p}/#{sublabel}"
|
||||
values[aug.get(p)] = aug.get(sp) || default
|
||||
end
|
||||
values
|
||||
end
|
||||
end
|
||||
|
||||
# Instance getter method for the instance
|
||||
define_method("attr_aug_reader_#{name}") do |aug, *args|
|
||||
self.class.send("attr_aug_reader_#{name}", aug, *args)
|
||||
end
|
||||
|
||||
# We are calling the resource's augopen here, not the class
|
||||
define_method(name) do |*args|
|
||||
augopen do |aug|
|
||||
send("attr_aug_reader_#{name}", aug, *args)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Defines a property setter using #augopen
|
||||
#
|
||||
# @param [String] name the name of the property
|
||||
# @param [Hash] opts the options to create the setter
|
||||
# @option opts [String] label node label to match beneath resource, default is `name.to_s`. When the value is `:resource`, `$resource` will be used as the path to the node
|
||||
# @option opts [Symbol] type either :string, :array or :hash
|
||||
# @option opts [String] default default value for hash values if sublabel doesn't exist
|
||||
# @option opts [String] sublabel label of next node(s) beneath node label, used in array and hash values, or :seq for array values representing a numbered seq
|
||||
# @option opts [Boolean] purge_ident whether to purge other matches (keeps the last one only)
|
||||
# @option opts [Boolean] rm_node whether setting a string value to `nil` removes the node (default is to clear its value)
|
||||
# @api public
|
||||
def self.attr_aug_writer(name, opts = {})
|
||||
label = opts[:label] || name.to_s
|
||||
default = opts[:default] || nil
|
||||
type = opts[:type] || :string
|
||||
sublabel = opts[:sublabel] || nil
|
||||
purge_ident = opts[:purge_ident] || false
|
||||
rm_node = opts[:rm_node] || false
|
||||
split_by = opts[:split_by] || nil
|
||||
|
||||
rpath = label == :resource ? '$resource' : "$resource/#{label}"
|
||||
|
||||
raise(Puppet::Error, 'You must provide a sublabel for type hash') if type == :hash && sublabel.nil?
|
||||
|
||||
raise(Puppet::Error, "Invalid type: #{type}") unless %i[string array hash].include? type
|
||||
|
||||
# Class setter method using an existing aug handler
|
||||
# Emulate define_singleton_method for Ruby 1.8
|
||||
metaclass = class << self; self; end
|
||||
metaclass.send(:define_method, "attr_aug_writer_#{name}") do |aug, *args|
|
||||
aug.rm("#{rpath}[position() != 1]") if purge_ident
|
||||
case type
|
||||
when :string
|
||||
if args[0]
|
||||
aug.set(rpath, args[0].to_s)
|
||||
elsif rm_node
|
||||
aug.rm(rpath)
|
||||
else
|
||||
aug.clear(rpath)
|
||||
end
|
||||
when :array
|
||||
if args[0].nil? || args[0].empty?
|
||||
aug.rm(rpath)
|
||||
elsif split_by
|
||||
aug.set(rpath, args[0].join(split_by))
|
||||
elsif sublabel.nil?
|
||||
aug.rm(rpath)
|
||||
count = 0
|
||||
args[0].each do |v|
|
||||
count += 1
|
||||
aug.set("#{rpath}[#{count}]", v)
|
||||
end
|
||||
elsif sublabel == :seq
|
||||
# Make sure only our values are used
|
||||
aug.rm("#{rpath}/*[label()=~regexp('[0-9]+')]")
|
||||
count = 0
|
||||
args[0].each do |v|
|
||||
count += 1
|
||||
aug.set("#{rpath}/#{count}", v)
|
||||
end
|
||||
else
|
||||
# Make sure only our values are used
|
||||
aug.rm("#{rpath}/#{sublabel}")
|
||||
count = 0
|
||||
args[0].each do |v|
|
||||
count += 1
|
||||
aug.set("#{rpath}/#{sublabel}[#{count}]", v)
|
||||
end
|
||||
end
|
||||
when :hash
|
||||
# First get rid of all entries
|
||||
aug.rm(rpath)
|
||||
args[0].each do |k, v|
|
||||
aug.set("#{rpath}[.='#{k}']", k)
|
||||
aug.set("#{rpath}[.='#{k}']/#{sublabel}", v) unless v == default
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Instance setter method for the instance
|
||||
define_method("attr_aug_writer_#{name}") do |aug, *args|
|
||||
self.class.send("attr_aug_writer_#{name}", aug, *args)
|
||||
end
|
||||
|
||||
# We are calling the resource's augopen here, not the class
|
||||
define_method("#{name}=") do |*args|
|
||||
augopen! do |aug|
|
||||
send("attr_aug_writer_#{name}", aug, *args)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Define getter and setter for a property
|
||||
#
|
||||
# @param [Symbol] name the name of the property
|
||||
# @param [Hash] opts the options to create the setter
|
||||
# @option opts [String] label node label to match beneath resource, default is `name.to_s`. When the value is `:resource`, `$resource` will be used as the path to the node
|
||||
# @option opts [Symbol] type either :string, :array or :hash
|
||||
# @option opts [String] default default value for hash values if sublabel doesn't exist
|
||||
# @option opts [String] sublabel label of next node(s) beneath node label, used in array and hash values, or :seq for array values representing a numbered seq
|
||||
# @option opts [Boolean] purge_ident whether to purge other matches (keeps the last one only)
|
||||
# @api public
|
||||
def self.attr_aug_accessor(name, opts = {})
|
||||
attr_aug_reader(name, opts)
|
||||
attr_aug_writer(name, opts)
|
||||
end
|
||||
|
||||
# Setter for the default file path managed by the provider.
|
||||
#
|
||||
# Takes a block to store, but doesn't yield. Will be called when it's
|
||||
# needed.
|
||||
#
|
||||
# @yield block that identifies the default file path managed by the provider
|
||||
# @yieldreturn [String] default file path
|
||||
# @api public
|
||||
def self.default_file(&block)
|
||||
@default_file_block = block
|
||||
end
|
||||
|
||||
# Getter and setter for the Augeas lens used for this provider.
|
||||
#
|
||||
# When called with a block, will only store the block - it doesn't yield.
|
||||
#
|
||||
# When called without a block, expects `resource` parameter which is
|
||||
# passed into the block, which returns the lens to be used.
|
||||
#
|
||||
# @param resource [Puppet::Resource] required for getter, resource being evaluated
|
||||
# @yield [resource] block that identifies the lens to use
|
||||
# @yieldparam [Puppet::Resource] resource resource being evaluted
|
||||
# @yieldreturn [String] Augeas lens to use, e.g. `'Hosts.lns'`
|
||||
# @return [String] Augeas lens to use, e.g. `'Hosts.lns'`
|
||||
# @raise [Puppet::Error] if no block has been set when getting
|
||||
# @api public
|
||||
def self.lens(resource = nil, &block)
|
||||
if block
|
||||
@lens_block = block
|
||||
else
|
||||
raise(Puppet::Error, 'Lens is not provided') unless @lens_block
|
||||
|
||||
@lens_block.call(resource)
|
||||
end
|
||||
end
|
||||
|
||||
# Wrapper around aug.label for older versions of Augeas
|
||||
# and values not found in the tree.
|
||||
#
|
||||
# @param [Augeas] aug Augeas handler
|
||||
# @param [String] path expression to get the label from
|
||||
# @return [String] label of the given path
|
||||
# @api public
|
||||
def self.path_label(aug, path)
|
||||
label = aug.label(path) if aug.respond_to? :label
|
||||
|
||||
# Fallback
|
||||
label || path.split('/')[-1].split('[')[0]
|
||||
end
|
||||
|
||||
# Determine which quote is needed
|
||||
#
|
||||
# @param [String] value the value to quote
|
||||
# @param [String] oldvalue the optional old value, used to auto-detect existing quoting
|
||||
# @return [String] the quoted value
|
||||
# @api public
|
||||
def self.whichquote(value, resource = nil, oldvalue = nil)
|
||||
oldquote = readquote oldvalue
|
||||
|
||||
quote = if resource&.parameters&.include?(:quoted)
|
||||
resource[:quoted]
|
||||
else
|
||||
:auto
|
||||
end
|
||||
|
||||
if quote == :auto
|
||||
quote = if oldquote
|
||||
oldquote
|
||||
elsif value.match?(%r{[|&;()<>\s]})
|
||||
:double
|
||||
else
|
||||
:none
|
||||
end
|
||||
end
|
||||
|
||||
case quote
|
||||
when :double
|
||||
'"'
|
||||
when :single
|
||||
"'"
|
||||
else
|
||||
''
|
||||
end
|
||||
end
|
||||
|
||||
# Automatically quote a value
|
||||
#
|
||||
# @param [String] value the value to quote
|
||||
# @param [String] oldvalue the optional old value, used to auto-detect existing quoting
|
||||
# @return [String] the quoted value
|
||||
# @api public
|
||||
def self.quoteit(value, resource = nil, oldvalue = nil)
|
||||
quote = whichquote(value, resource, oldvalue)
|
||||
"#{quote}#{value}#{quote}"
|
||||
end
|
||||
|
||||
# Detect what type of quoting a value uses
|
||||
#
|
||||
# @param [String] value the value to be analyzed
|
||||
# @return [Symbol] the type of quoting used (:double, :single or nil)
|
||||
# @api public
|
||||
def self.readquote(value)
|
||||
if value =~ %r{^(["'])(.*)(?:\1)$}
|
||||
case Regexp.last_match(1)
|
||||
when '"' then :double
|
||||
when "'" then :single
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Getter and setter for the Augeas path expression representing an
|
||||
# individual resource inside a file, that's managed by this provider.
|
||||
#
|
||||
# When called with a block, will only store the block - it doesn't yield.
|
||||
# The block is later used to generate the path expression.
|
||||
#
|
||||
# When called without a block, expects `resource` parameter which is
|
||||
# passed into the block, which returns the path expression representing
|
||||
# the supplied resource.
|
||||
#
|
||||
# If no block has already been set, it returns the path expression
|
||||
# representing the top-level of the file.
|
||||
#
|
||||
# @param resource [Puppet::Resource] required for getter, resource being evaluated
|
||||
# @yield [resource] block that identifies the path expression
|
||||
# @yieldparam [Puppet::Resource] resource resource being evaluted
|
||||
# @yieldreturn [String] Augeas path expression, e.g. `'/files/etc/hosts/1'`
|
||||
# @return [String] Augeas path expression to use, e.g. `'/files/etc/hosts/1'`
|
||||
# @raise [Puppet::Error] if no default file block is set and no resource is passed
|
||||
# @see AugeasProviders::Provider#resource_path
|
||||
# @see #target
|
||||
# @api public
|
||||
def self.resource_path(resource = nil, &block)
|
||||
if block
|
||||
@resource_path_block = block
|
||||
elsif @resource_path_block
|
||||
@resource_path_block.call(resource)
|
||||
else
|
||||
"#{target(resource)}/#{resource[:name]}"
|
||||
end
|
||||
end
|
||||
|
||||
# Sets useful Augeas variables for the session.
|
||||
#
|
||||
# * `$target` points to the root of the target file
|
||||
# * `$resource` points to path defined by #resource_path
|
||||
#
|
||||
# It also sets `/augeas/context` to the target file so
|
||||
# relative paths can be used, before the variables are set.
|
||||
#
|
||||
# If supplied with a resource, it will be used to determine the
|
||||
# path to the used file.
|
||||
#
|
||||
# @param [Augeas] aug Augeas handle
|
||||
# @param [Puppet::Resource] resource resource being evaluated
|
||||
# @see #resource_path
|
||||
# @api public
|
||||
def self.setvars(aug, resource = nil)
|
||||
aug.context = "/files#{target(resource)}"
|
||||
aug.defnode('target', "/files#{target(resource)}", nil)
|
||||
aug.defvar('resource', resource_path(resource)) if resource
|
||||
end
|
||||
|
||||
# Gets the path expression representing the file being managed.
|
||||
#
|
||||
# If supplied with a resource, this will represent the file identified by
|
||||
# the resource, else the default file that the provider manages.
|
||||
#
|
||||
# @param [Puppet::Resource] resource resource being evaluated
|
||||
# @return [String] path expression representing the file being managed
|
||||
# @raise [Puppet::Error] if no default block is set and no resource is passed
|
||||
# @see AugeasProviders::Provider#target
|
||||
# @see #resource_path
|
||||
# @api public
|
||||
def self.target(resource = nil)
|
||||
file = @default_file_block.call if @default_file_block
|
||||
file = resource[:target] if resource && resource[:target]
|
||||
raise(Puppet::Error, 'No target file given') if file.nil?
|
||||
|
||||
file.chomp('/')
|
||||
end
|
||||
|
||||
# Automatically unquote a value
|
||||
#
|
||||
# @param [String] value the value to unquote
|
||||
# @return [String] the unquoted value
|
||||
# @api public
|
||||
def self.unquoteit(value)
|
||||
if value =~ %r{^(["'])(.*)(?:\1)$}
|
||||
Regexp.last_match(2)
|
||||
else
|
||||
value
|
||||
end
|
||||
end
|
||||
|
||||
# Returns whether text is parsed as path using lens
|
||||
#
|
||||
# @param [String] text the text to test
|
||||
# @param [String] path the relative path to test
|
||||
# @param [String] lens the lens to use for parsing
|
||||
# @return [Boolean] whether the path was found when parsing text with lens
|
||||
# @api public
|
||||
def self.parsed_as?(text, path, lens)
|
||||
Augeas.open(nil, nil, Augeas::NO_MODL_AUTOLOAD) do |aug|
|
||||
if aug.respond_to? :text_store
|
||||
aug.set('/input', text)
|
||||
return aug.match("/parsed/#{path}").any? if aug.text_store(lens, '/input', '/parsed')
|
||||
else
|
||||
# ruby-augeas < 0.5 doesn't support text_store
|
||||
Tempfile.open('aug_text_store') do |tmpfile|
|
||||
tmpfile.write(text)
|
||||
tmpfile.flush
|
||||
aug.transform(
|
||||
lens: lens,
|
||||
name: 'Text_store',
|
||||
incl: tmpfile.path.to_s,
|
||||
excl: []
|
||||
)
|
||||
aug.load!
|
||||
return aug.match("/files#{tmpfile.path}/#{path}").any?
|
||||
end
|
||||
end
|
||||
end
|
||||
false
|
||||
end
|
||||
|
||||
# Sets the post_resource_eval class hook for Puppet
|
||||
# This allows to clean the shared Augeas handler.
|
||||
def self.post_resource_eval
|
||||
augclose!(aug_handler)
|
||||
@aug_handler = nil
|
||||
end
|
||||
|
||||
# Returns a set of load paths to use when initialising Augeas.
|
||||
#
|
||||
# @return [String] colon-separated string of module paths, or nil if defaults are to be used
|
||||
def self.loadpath
|
||||
loadpath = nil
|
||||
plugins = File.join(Puppet[:libdir], 'augeas', 'lenses')
|
||||
loadpath = loadpath.to_s.split(File::PATH_SEPARATOR).push(plugins).join(File::PATH_SEPARATOR) if File.exist?(plugins)
|
||||
loadpath
|
||||
end
|
||||
|
||||
# Opens Augeas and returns a handle to use. It loads only the file
|
||||
# identified by {#target} (and the supplied `resource`) using {#lens}.
|
||||
#
|
||||
# If called with a block, this will be yielded to and the Augeas handle.
|
||||
# Otherwise, the handle will be returned and not closed automatically.
|
||||
# The handle will be closed by `post_resource_eval`.
|
||||
#
|
||||
# If `yield_resource` is set to true, the supplied `resource` will be passed
|
||||
# as a yieldparam to the block, after the `aug` handle. Any arguments passed
|
||||
# after `yield_resource` will be added as yieldparams to the block.
|
||||
#
|
||||
# @param [Puppet::Resource] resource resource being evaluated
|
||||
# @param [Boolean] yield_resource whether to send `resource` as a yieldparam
|
||||
# @param [Splat] yield_params a splat of parameters to pass as yieldparams if `yield_resource` is true
|
||||
# @return [Augeas] Augeas handle if no block is given
|
||||
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
|
||||
# @yieldparam [Augeas] aug open Augeas handle
|
||||
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
|
||||
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
|
||||
# @raise [Puppet::Error] if Augeas did not load the file
|
||||
# @api private
|
||||
def self.augopen_internal(resource = nil, yield_resource = false, *yield_params, &block)
|
||||
aug = aug_handler
|
||||
file = target(resource)
|
||||
begin
|
||||
lens_name = lens[%r{[^.]+}]
|
||||
if aug.match("/augeas/load/#{lens_name}").empty?
|
||||
aug.transform(
|
||||
lens: lens,
|
||||
name: lens_name,
|
||||
incl: file,
|
||||
excl: []
|
||||
)
|
||||
aug.load!
|
||||
elsif aug.match("/augeas/load/#{lens_name}/incl[.='#{file}']").empty?
|
||||
# Only add missing file
|
||||
aug.set("/augeas/load/#{lens_name}/incl[.='#{file}']", file)
|
||||
aug.load!
|
||||
end
|
||||
|
||||
if File.exist?(file) && aug.match("/files#{file}").empty?
|
||||
message = aug.get("/augeas/files#{file}/error/message")
|
||||
unless aug.match("/augeas/files#{file}/error/pos").empty?
|
||||
line = aug.get("/augeas/files#{file}/error/line")
|
||||
char = aug.get("/augeas/files#{file}/error/char")
|
||||
message += " (line:#{line}, character:#{char})"
|
||||
end
|
||||
from = loadpath.nil? ? '' : " from #{loadpath}"
|
||||
raise(Puppet::Error, "Augeas didn't load #{file} with #{lens}#{from}: #{message}")
|
||||
end
|
||||
|
||||
if block
|
||||
setvars(aug, resource)
|
||||
if yield_resource
|
||||
block.call(aug, resource, *yield_params)
|
||||
else
|
||||
block.call(aug)
|
||||
end
|
||||
else
|
||||
aug
|
||||
end
|
||||
rescue StandardError
|
||||
raise
|
||||
end
|
||||
end
|
||||
|
||||
# Returns the Augeas version used
|
||||
#
|
||||
# @return [String] Augeas version in use
|
||||
# @api public
|
||||
def aug_version
|
||||
self.class.aug_version
|
||||
end
|
||||
|
||||
# Returns whether a feature is supported.
|
||||
#
|
||||
# The following features are currently supported:
|
||||
#
|
||||
# * `:regexpi`: whether Augeas supports an 'i' flag in regexp expressions
|
||||
#
|
||||
# @param [Symbol] feature the feature to check
|
||||
# @return [Boolean] whether feature is supported
|
||||
# @api public
|
||||
def supported?(feature)
|
||||
self.class.supported?(feature)
|
||||
end
|
||||
|
||||
# Opens Augeas and returns a handle to use. It loads only the file
|
||||
# for the current Puppet resource using {AugeasProviders::Provider::ClassMethods#lens}.
|
||||
#
|
||||
# If called with a block, this will be yielded to and the Augeas handle.
|
||||
# Otherwise, the handle will be returned and not closed automatically.
|
||||
# The handle will be closed by `post_resource_eval`.
|
||||
#
|
||||
# If `yield_resource` is set to true, the supplied `resource` will be passed
|
||||
# as a yieldparam to the block, after the `aug` handle. Any arguments passed
|
||||
# after `yield_resource` will be added as yieldparams to the block.
|
||||
#
|
||||
# @return [Augeas] Augeas handle if no block is given
|
||||
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
|
||||
# @yieldparam [Augeas] aug open Augeas handle
|
||||
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
|
||||
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
|
||||
# @raise [Puppet::Error] if Augeas did not load the file
|
||||
# @api public
|
||||
def augopen(yield_resource = false, *yield_params, &block)
|
||||
self.class.augopen(resource, yield_resource, *yield_params, &block)
|
||||
end
|
||||
|
||||
# Opens Augeas and returns a handle to use. It loads only the file
|
||||
# for the current Puppet resource using {AugeasProviders::Provider::ClassMethods#lens}.
|
||||
# #augsave! is called after the block is evaluated.
|
||||
#
|
||||
# If called with a block, this will be yielded to and the Augeas handle.
|
||||
# Otherwise, the handle will be returned and not closed automatically.
|
||||
# The handle will be closed by `post_resource_eval`.
|
||||
#
|
||||
# @return [Augeas] Augeas handle if no block is given
|
||||
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
|
||||
# @yieldparam [Augeas] aug open Augeas handle
|
||||
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
|
||||
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
|
||||
# @raise [Puppet::Error] if Augeas did not load the file
|
||||
# @api public
|
||||
def augopen!(yield_resource = false, *yield_params, &block)
|
||||
self.class.augopen!(resource, yield_resource, *yield_params, &block)
|
||||
end
|
||||
|
||||
# Saves all changes made in the current Augeas handle and checks for any
|
||||
# errors while doing so.
|
||||
#
|
||||
# @param [Augeas] aug open Augeas handle
|
||||
# @param [Boolean] reload whether to reload the tree after saving
|
||||
# @raise [Augeas::Error] if saving fails
|
||||
# @api public
|
||||
def augsave!(aug, reload = false)
|
||||
self.class.augsave!(aug, reload)
|
||||
end
|
||||
|
||||
# Close the shared Augeas handler.
|
||||
#
|
||||
# @param [Augeas] aug open Augeas handle
|
||||
# @api public
|
||||
def augclose!(aug)
|
||||
self.class.augclose!(aug)
|
||||
end
|
||||
|
||||
# Stores and returns a shared Augeas handler for all instances of the class
|
||||
#
|
||||
# @return [Augeas] Augeas shared Augeas handle
|
||||
# @api private
|
||||
def aug_handler
|
||||
self.class.aug_handler
|
||||
end
|
||||
|
||||
# Wrapper around Augeas#label for older versions of Augeas
|
||||
#
|
||||
# @param [Augeas] aug Augeas handler
|
||||
# @param [String] path expression to get the label from
|
||||
# @return [String] label of the given path
|
||||
# @api public
|
||||
def path_label(aug, path)
|
||||
self.class.path_label(aug, path)
|
||||
end
|
||||
|
||||
# Determine which quote is needed
|
||||
#
|
||||
# @param [String] value the value to quote
|
||||
# @param [String] oldvalue the optional old value, used to auto-detect existing quoting
|
||||
# @return [String] the quoted value
|
||||
# @api public
|
||||
def whichquote(value, oldvalue = nil)
|
||||
self.class.whichquote(value, resource, oldvalue)
|
||||
end
|
||||
|
||||
# Automatically quote a value
|
||||
#
|
||||
# @param [String] value the value to quote
|
||||
# @param [String] oldvalue the optional old value, used to auto-detect existing quoting
|
||||
# @return [String] the quoted value
|
||||
# @api public
|
||||
def quoteit(value, oldvalue = nil)
|
||||
self.class.quoteit(value, resource, oldvalue)
|
||||
end
|
||||
|
||||
# Detect what type of quoting a value uses
|
||||
#
|
||||
# @param [String] value the value to be analyzed
|
||||
# @return [Symbol] the type of quoting used (:double, :single or nil)
|
||||
# @api public
|
||||
def readquote(value)
|
||||
self.class.readquote(value)
|
||||
end
|
||||
|
||||
# Gets the Augeas path expression representing the individual resource inside
|
||||
# the file, that represents the current Puppet resource.
|
||||
#
|
||||
# If no block was set by the provider's class method, it returns the path
|
||||
# expression representing the top-level of the file.
|
||||
#
|
||||
# @return [String] Augeas path expression to use, e.g. `'/files/etc/hosts/1'`
|
||||
# @see AugeasProviders::Provider::ClassMethods#resource_path
|
||||
# @see #target
|
||||
# @api public
|
||||
def resource_path
|
||||
self.class.resource_path(resource)
|
||||
end
|
||||
|
||||
# Sets useful Augeas variables for the session:
|
||||
#
|
||||
# * `$target` points to the root of the target file
|
||||
# * `$resource` points to path defined by #resource_path
|
||||
#
|
||||
# It also sets `/augeas/context` to the target file so
|
||||
# relative paths can be used, before the variables are set.
|
||||
#
|
||||
# If supplied with a resource, it will be used to determine the
|
||||
# path to the used file.
|
||||
#
|
||||
# @param [Augeas] aug Augeas handle
|
||||
# @see #resource_path
|
||||
# @api public
|
||||
def setvars(aug)
|
||||
self.class.setvars(aug, resource)
|
||||
end
|
||||
|
||||
# Gets the path expression representing the file being managed for the
|
||||
# current Puppet resource.
|
||||
#
|
||||
# @return [String] path expression representing the file being managed
|
||||
# @see AugeasProviders::Provider::ClassMethods#target
|
||||
# @see #resource_path
|
||||
# @api public
|
||||
def target
|
||||
self.class.target(resource)
|
||||
end
|
||||
|
||||
# Automatically unquote a value
|
||||
#
|
||||
# @param [String] value the value to unquote
|
||||
# @return [String] the unquoted value
|
||||
# @api public
|
||||
def unquoteit(value)
|
||||
self.class.unquoteit(value)
|
||||
end
|
||||
|
||||
# Returns whether text is parsed as path using lens
|
||||
#
|
||||
# @param [String] text the text to test
|
||||
# @param [String] path the relative path to test
|
||||
# @param [String] lens the lens to use for parsing
|
||||
# @return [Boolean] whether the path was found when parsing text with lens
|
||||
# @api public
|
||||
def parsed_as?(text, path, lens = nil)
|
||||
lens ||= self.class.lens(resource)
|
||||
self.class.parsed_as?(text, path, lens)
|
||||
end
|
||||
|
||||
# Default method to determine the existence of a resource
|
||||
# can be overridden if necessary
|
||||
def exists?
|
||||
augopen do |aug|
|
||||
!aug.match('$resource').empty?
|
||||
end
|
||||
end
|
||||
|
||||
# Default method to destroy a resource
|
||||
# can be overridden if necessary
|
||||
def destroy
|
||||
augopen! do |aug|
|
||||
aug.rm('$resource')
|
||||
end
|
||||
end
|
||||
|
||||
# Default method to flush a resource
|
||||
#
|
||||
# Takes care of saving the tree for the shared Augeas handler.
|
||||
#
|
||||
# This method can be overridden in your provider
|
||||
# but you should make sure to call `super`
|
||||
# to ensure that the tree will be saved.
|
||||
def flush
|
||||
augsave!(aug_handler, true)
|
||||
end
|
||||
|
||||
# Returns a node label to use for creating a new entry in an Augeas sequence
|
||||
# (seq), given the current list, e.g. '1' if it's the first. Supply
|
||||
# aug.match('$target/*') or similar.
|
||||
#
|
||||
# @param [Array<String>] existing paths, from Augeas#match
|
||||
# @return [String] new node label
|
||||
def next_seq(matches)
|
||||
self.class.next_seq(matches)
|
||||
end
|
||||
end
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
# Dumb augeasprovider type
|
||||
|
||||
Puppet::Type.newtype(:augeasprovider) do
|
||||
@doc = 'Dumb Augeas provider type'
|
||||
end
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
# This file was automatically generated on 2026-11-08 22:33:56 +1100.
|
||||
# Use the 'puppet generate types' command to regenerate this file.
|
||||
|
||||
# @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",
|
||||
# }
|
||||
Puppet::Resource::ResourceType3.new(
|
||||
'augeas',
|
||||
[
|
||||
# The expected return code from the augeas command. Should not be set.
|
||||
Puppet::Resource::Param(Any, 'returns')
|
||||
],
|
||||
[
|
||||
# The name of this task. Used for uniqueness.
|
||||
Puppet::Resource::Param(Any, 'name', true),
|
||||
|
||||
# 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.
|
||||
Puppet::Resource::Param(Any, 'context'),
|
||||
|
||||
# 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 <MATCH_PATH> and then `get` to retrieve the values from each of the returned paths.
|
||||
#
|
||||
# Supported onlyif syntax:
|
||||
#
|
||||
# * `get <AUGEAS_PATH> <COMPARATOR> <STRING>`
|
||||
# * `values <MATCH_PATH> include <STRING>`
|
||||
# * `values <MATCH_PATH> not_include <STRING>`
|
||||
# * `values <MATCH_PATH> == <AN_ARRAY>`
|
||||
# * `values <MATCH_PATH> != <AN_ARRAY>`
|
||||
# * `match <MATCH_PATH> size <COMPARATOR> <INT>`
|
||||
# * `match <MATCH_PATH> include <STRING>`
|
||||
# * `match <MATCH_PATH> not_include <STRING>`
|
||||
# * `match <MATCH_PATH> == <AN_ARRAY>`
|
||||
# * `match <MATCH_PATH> != <AN_ARRAY>`
|
||||
#
|
||||
# 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']`
|
||||
Puppet::Resource::Param(Any, 'onlyif'),
|
||||
|
||||
# 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 <PATH> <VALUE>` --- Sets the value `VALUE` at location `PATH`
|
||||
# * `setm <PATH> <SUB> <VALUE>` --- Sets multiple nodes (matching `SUB` relative to `PATH`) to `VALUE`
|
||||
# * `rm <PATH>` --- Removes the node at location `PATH`
|
||||
# * `remove <PATH>` --- Synonym for `rm`
|
||||
# * `clear <PATH>` --- Sets the node at `PATH` to `NULL`, creating it if needed
|
||||
# * `clearm <PATH> <SUB>` --- Sets multiple nodes (matching `SUB` relative to `PATH`) to `NULL`
|
||||
# * `touch <PATH>` --- Creates `PATH` with the value `NULL` if it does not exist
|
||||
# * `ins <LABEL> (before|after) <PATH>` --- Inserts an empty node `LABEL` either before or after `PATH`.
|
||||
# * `insert <LABEL> <WHERE> <PATH>` --- Synonym for `ins`
|
||||
# * `mv <PATH> <OTHER PATH>` --- Moves a node at `PATH` to the new location `OTHER PATH`
|
||||
# * `move <PATH> <OTHER PATH>` --- Synonym for `mv`
|
||||
# * `rename <PATH> <LABEL>` --- Rename a node at `PATH` to a new `LABEL`
|
||||
# * `defvar <NAME> <PATH>` --- Sets Augeas variable `$NAME` to `PATH`
|
||||
# * `defnode <NAME> <PATH> <VALUE>` --- Sets Augeas variable `$NAME` to `PATH`, creating it with `VALUE` if needed
|
||||
#
|
||||
# If the `context` parameter is set, that value is prepended to any relative `PATH`s.
|
||||
Puppet::Resource::Param(Any, 'changes'),
|
||||
|
||||
# A file system path; all files loaded by Augeas are loaded underneath `root`.
|
||||
Puppet::Resource::Param(Any, 'root'),
|
||||
|
||||
# Optional colon-separated list or array of directories; these directories are searched for schema definitions.
|
||||
# The agent's `$libdir/augeas/lenses` path will always be added to support pluginsync.
|
||||
Puppet::Resource::Param(Any, 'load_path'),
|
||||
|
||||
# Optional command to force the augeas type to execute even if it thinks changes
|
||||
# will not be made. This does not override the `onlyif` parameter.
|
||||
Puppet::Resource::Param(Any, 'force'),
|
||||
|
||||
# Whether augeas should perform typechecking. Defaults to false.
|
||||
#
|
||||
# Valid values are `true`, `false`.
|
||||
Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'type_check'),
|
||||
|
||||
# Use a specific lens, such as `Hosts.lns`. When this parameter is set, you
|
||||
# must also set the `incl` parameter to indicate which file to load.
|
||||
# The Augeas documentation includes [a list of available lenses](http://augeas.net/stock_lenses.html).
|
||||
Puppet::Resource::Param(Any, 'lens'),
|
||||
|
||||
# Load only a specific file, such as `/etc/hosts`. This can greatly speed
|
||||
# up the execution the resource. When this parameter is set, you must also
|
||||
# set the `lens` parameter to indicate which lens to use.
|
||||
Puppet::Resource::Param(Any, 'incl'),
|
||||
|
||||
# Whether to display differences when the file changes, defaulting to
|
||||
# true. This parameter is useful for files that may contain passwords or
|
||||
# other secret data, which might otherwise be included in Puppet reports or
|
||||
# other insecure outputs. If the global `show_diff` setting
|
||||
# is false, then no diffs will be shown even if this parameter is true.
|
||||
#
|
||||
# Valid values are `true`, `false`, `yes`, `no`.
|
||||
Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'show_diff'),
|
||||
|
||||
# The specific backend to use for this `augeas`
|
||||
# resource. You will seldom need to specify this --- OpenVox will usually
|
||||
# discover the appropriate provider for your platform.Available providers are:
|
||||
#
|
||||
# augeas
|
||||
# : The Augeas provider
|
||||
#
|
||||
# * Supported features: `execute_changes`, `need_to_run?`, `parse_commands`.
|
||||
Puppet::Resource::Param(Any, 'provider')
|
||||
],
|
||||
{
|
||||
/(?m-ix:(.*))/ => ['name']
|
||||
},
|
||||
true,
|
||||
false)
|
||||
@@ -0,0 +1,22 @@
|
||||
# This file was automatically generated on 2026-11-08 22:33:56 +1100.
|
||||
# Use the 'puppet generate types' command to regenerate this file.
|
||||
|
||||
# Dumb Augeas provider type
|
||||
Puppet::Resource::ResourceType3.new(
|
||||
'augeasprovider',
|
||||
[
|
||||
|
||||
],
|
||||
[
|
||||
# The specific backend to use for this `augeasprovider`
|
||||
# resource. You will seldom need to specify this --- OpenVox will usually
|
||||
# discover the appropriate provider for your platform.Available providers are:
|
||||
#
|
||||
# default
|
||||
# :
|
||||
Puppet::Resource::Param(Any, 'provider')
|
||||
],
|
||||
{
|
||||
},
|
||||
true,
|
||||
false)
|
||||
Reference in New Issue
Block a user